问:
OkHttpClient get response body
I want get body response, but get error 403, although the page opens in webview and browser. My code:

```<code>OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder()
                            .url(url)
                            .build();

                    client.newCall(request).enqueue(new Callback()
                    {
                        @Override
                        public void onFailure(Call call, IOException e)
                        {
                            Log.e("Error load URL", e.toString());
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException
                        {
                            if (response.isSuccessful())
                            {
                                htmlPage = response.body().string();
                            }
                            else
                            {
                                //I find myself here.
                                Log.e("Error load URL", "Response error");
                            }
                        }
                    });
</code>```

url =
  "http://shop.lenovo.com/SEUILibrary/controller/e/web/LenovoPortal/en_US/cart.workflow:ShowCart?shopping-menu-selected-line=cart&menu-id=currentcart"

response from server:

Response{protocol=http/1.1, code=403, message=Forbidden,
  url=http://shop.lenovo.com/SEUILibrary/controller/e/web/LenovoPortal/en_US/cart.workflow:ShowCart?shopping-menu-selected-line=cart&menu-id=currentcart}

In browser everything is good. Why?

答: Extension to Kiran, 403 represents an authorization issue. Not an authentication issue. It's very possible that in browser authentication and authorization is managed using a cookie which may not be handled in your code. </p>

Title: OkHttpClient get response body

Body:
I want get body response, but get error 403, although the page opens in webview and browser. My code:

OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder()
                            .url(url)
                            .build();

                    client.newCall(request).enqueue(new Callback()
                    {
                        @Override
                        public void onFailure(Call call, IOException e)
                        {
                            Log.e("Error load URL", e.toString());
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException
                        {
                            if (response.isSuccessful())
                            {
                                htmlPage = response.body().string();
                            }
                            else
                            {
                                //I find myself here.
                                Log.e("Error load URL", "Response error");
                            }
                        }
                    });

url =
  "http://shop.lenovo.com/SEUILibrary/controller/e/web/LenovoPortal/en_US/cart.workflow:ShowCart?shopping-menu-selected-line=cart&menu-id=currentcart"

response from server:

Response{protocol=http/1.1, code=403, message=Forbidden,
  url=http://shop.lenovo.com/SEUILibrary/controller/e/web/LenovoPortal/en_US/cart.workflow:ShowCart?shopping-menu-selected-line=cart&menu-id=currentcart}

In browser everything is good. Why?


来源: stackexchange

问:
Extracting nested values in a Javascript object
I have the following object:

```<code>var result = [{
"id": 89304,
"employeeDetails": {
    "id": 102524,
    "version": 9
}
}];
</code>```

This is a snippet from a larger object that I'm trying to push into a MySQL table.
What I'm trying to achieve is extract just the values into their own array, which would return this:

```<code>[ '89304', '102524', '9' ]
</code>```

This way, I can easily push the values to the DB.

I have tried doing the following which works fine without nesting:

obKeys = Object.keys(result);
console.log(obKeys);

However, with the nesting, the result I am getting is the following:

[ '0' ]

Can anyone let me know where I am going wrong, or suggest an alternative (better) way of doing this?

Thanks.

答:
Get data from result list and into myList one by one.
@Jim Dover Try this

```<code> var myList;
    myList.push(result[0].id);
    myList.push(result[0].employeeDetails.id);
    myList.push(result[0].employeeDetails.version);
</code>```

Or Simply

```<code>    result.forEach(function(item,index) {
var TempList;
        TempList.push(item.id);
            TempList.push(item.employeeDetails.id);
            TempList.push(item.employeeDetails.version);

    myList.push(TempList);
    });
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have the following object:

var result = [{
"id": 89304,
"employeeDetails": {
    "id": 102524,
    "version": 9
}
}];

This is a snippet from a larger object that I'm trying to push into a MySQL table.
What I'm trying to achieve is extract just the values into their own array, which would return this:

[ '89304', '102524', '9' ]

This way, I can easily push the values to the DB.

I have tried doing the following which works fine without nesting:

obKeys = Object.keys(result);
console.log(obKeys);

However, with the nesting, the result I am getting is the following:

[ '0' ]

Can anyone let me know where I am going wrong, or suggest an alternative (better) way of doing this?

Thanks.

Body:
Get data from result list and into myList one by one.
@Jim Dover Try this

 var myList;
    myList.push(result[0].id);
    myList.push(result[0].employeeDetails.id);
    myList.push(result[0].employeeDetails.version);

Or Simply

    result.forEach(function(item,index) {
var TempList;
        TempList.push(item.id);
            TempList.push(item.employeeDetails.id);
            TempList.push(item.employeeDetails.version);

    myList.push(TempList);
    });


问:
Why am I getting this JspException?
Can anyone explain this exception and its cause:

javax.servlet.jsp.JspException: No getter method for property: "loanInfoSearch_dto.branchCode" of bean: "org.apache.struts.validator.DynaValidatorActionForm"

答:
Just a guess, but if you've got a class named LoanInfoSearch_dto and you've got an instance of it named loanInfoSearch_dto, and it has a private variable named branchCode, then you're missing a method named

```<code>public T getBranchCode() {
   return branchCode;
}
</code>```

where T is branchCode's type. From its name, I'd assume its an int or some other numeric type.

ContentLicense: CC BY-SA 2.5

Title: Why am I getting this JspException?

Body:
Just a guess, but if you've got a class named LoanInfoSearch_dto and you've got an instance of it named loanInfoSearch_dto, and it has a private variable named branchCode, then you're missing a method named

public T getBranchCode() {
   return branchCode;
}

where T is branchCode's type. From its name, I'd assume its an int or some other numeric type.


答:
It's because 'result' is actually an Array so the key that's being outputted is the key for the WHOLE object within the array.

To extract the values from the object you'll first have to iterate over the array and then for EACH of the items then iterate over the keys (Object.keys(obj)).

Here's a rough example for you to work off of, hope it helps.

```<code>var result = [{
"id": 89304,
"employeeDetails": {
    "id": 102524,
    "version": 9
}
}];

for (var i = 0; i < result.length; i++) {

  var item = result[i];

  Object.keys(item).forEach(function(key) {

    console.log(item[key]); // This will provide you the value for each key.

  });

}
</code>```

As one of your properties inside the object is also and object, you'll have to check for that and then further iterate over it.

Title: Extracting nested values in a Javascript object

Body:
It's because 'result' is actually an Array so the key that's being outputted is the key for the WHOLE object within the array.

To extract the values from the object you'll first have to iterate over the array and then for EACH of the items then iterate over the keys (Object.keys(obj)).

Here's a rough example for you to work off of, hope it helps.

var result = [{
"id": 89304,
"employeeDetails": {
    "id": 102524,
    "version": 9
}
}];

for (var i = 0; i < result.length; i++) {

  var item = result[i];

  Object.keys(item).forEach(function(key) {

    console.log(item[key]); // This will provide you the value for each key.

  });

}

As one of your properties inside the object is also and object, you'll have to check for that and then further iterate over it.


问:
$http POST call in angularjs returns HTTP status code 405
I try to make a POST call from a javascript client to a foursquare API called addvenue.
This the API endpoint documentation link.

  But the server returns 405 - Method not allowed. Here is the snippet making the call

```<code>var postdata = {'oauth_token':$scope.access_token_foursquare,
                        'v':'20141217','name':'randomlisting',
                        'll':'44.3,37.2','m':'foursquare'};
var req = {
            method: 'POST',
            url: 'https://api.foursquare.com/v2/venues/add',
            headers: {
              'content-type': 'application/x-www-form-urlencoded'
            },
            data: postdata
          }

$http(req).then(function(response){
      console.log(response);
           });
</code>```

Following is the Request and response packet for the above call.

```<code>Remote Address:103.245.222.185:443
Request URL:https://api.foursquare.com/v2/venues/add
Request Method:OPTIONS
Status Code:405 Method Not Allowed

**Request Headers**
Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:accept, authorization, content-type
Access-Control-Request-Method:POST
Connection:keep-alive
Host:api.foursquare.com
Origin:http://localhost:9000
Referer:http://localhost:9000/foursquare
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36

**Response Headers**

Accept-Ranges:bytes
Access-Control-Allow-Origin:*
Connection:Keep-Alive
Content-Length:90
Content-Type:application/json; charset=utf-8
Date:Wed, 17 Dec 2014 12:15:15 GMT
Keep-Alive:timeout=10, max=50
Server:nginx
Tracer-Time:1
Via:1.1 varnish
X-Cache:MISS
X-Cache-Hits:0
X-Served-By:cache-sn87-SIN
</code>```

I also studied about CORS issue. In my case the server is allowing all origins, as seen in the response headers. I am struck with this issue and could not proceed further.

Any help would be appreciated.
Thanks in advance.

答:
Request Method:OPTIONS

The client is making a pre-flight OPTIONS request to the server.

An OPTIONS request is automatically made by the browser before making a non-simple (e.g. not a GET) cross domain (CORS) request.

The purpose of the OPTIONS request is a quick check with the server to ensure that the client is permitted to make the POST before actually making the POST. Thus the client makes 1 or 2 requests.

An OPTIONS request and if the OPTIONS request responds with success (not a 405) then make the POST.

The OPTIONS request is failing most likely because you have not stated in your server response that your server supports OPTIONS requests.

Add this header to your server response ..

```<code>Access-Control-Allow-Methods: POST, GET, PUT, DELETE, OPTIONS
</code>```

Then it should all work.

See https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Preflighted_requests for more info

Body:
I try to make a POST call from a javascript client to a foursquare API called addvenue.
This the API endpoint documentation link.

  But the server returns 405 - Method not allowed. Here is the snippet making the call

var postdata = {'oauth_token':$scope.access_token_foursquare,
                        'v':'20141217','name':'randomlisting',
                        'll':'44.3,37.2','m':'foursquare'};
var req = {
            method: 'POST',
            url: 'https://api.foursquare.com/v2/venues/add',
            headers: {
              'content-type': 'application/x-www-form-urlencoded'
            },
            data: postdata
          }

$http(req).then(function(response){
      console.log(response);
           });

Following is the Request and response packet for the above call.

Remote Address:103.245.222.185:443
Request URL:https://api.foursquare.com/v2/venues/add
Request Method:OPTIONS
Status Code:405 Method Not Allowed

**Request Headers**
Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:accept, authorization, content-type
Access-Control-Request-Method:POST
Connection:keep-alive
Host:api.foursquare.com
Origin:http://localhost:9000
Referer:http://localhost:9000/foursquare
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36

**Response Headers**

Accept-Ranges:bytes
Access-Control-Allow-Origin:*
Connection:Keep-Alive
Content-Length:90
Content-Type:application/json; charset=utf-8
Date:Wed, 17 Dec 2014 12:15:15 GMT
Keep-Alive:timeout=10, max=50
Server:nginx
Tracer-Time:1
Via:1.1 varnish
X-Cache:MISS
X-Cache-Hits:0
X-Served-By:cache-sn87-SIN

I also studied about CORS issue. In my case the server is allowing all origins, as seen in the response headers. I am struck with this issue and could not proceed further.

Any help would be appreciated.
Thanks in advance.

Body:
Request Method:OPTIONS

The client is making a pre-flight OPTIONS request to the server.

An OPTIONS request is automatically made by the browser before making a non-simple (e.g. not a GET) cross domain (CORS) request.

The purpose of the OPTIONS request is a quick check with the server to ensure that the client is permitted to make the POST before actually making the POST. Thus the client makes 1 or 2 requests.

An OPTIONS request and if the OPTIONS request responds with success (not a 405) then make the POST.

The OPTIONS request is failing most likely because you have not stated in your server response that your server supports OPTIONS requests.

Add this header to your server response ..

Access-Control-Allow-Methods: POST, GET, PUT, DELETE, OPTIONS

Then it should all work.

See https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Preflighted_requests for more info


问:
How to remove all special characters in Linux text

How to remove the special characters shown as blue color in the picture 1 like: ^M, ^A, ^@, ^[. In my understanding, ^M is a windows newline character, I can use sed -i '/^M//g' to remove it, but it doesn't work to remove others. The command dos2unix doesn't work, neither. Are there exist any ways that I can use to remove them both?

答:
Remove everything except the printable characters (character class [:print:]), with sed:

```<code>sed $'s/[^[:print:]\t]//g' file.txt
</code>```

[:print:] includes:

[:alnum:] (alpha-numerics)

[:punct:] (punctuations)

space

The ANSI C quoting ($'') is used for interpreting \t as literal tab inside $'' (in bash and alike).

Body:
Remove everything except the printable characters (character class [:print:]), with sed:

sed $'s/[^[:print:]\t]//g' file.txt

[:print:] includes:

[:alnum:] (alpha-numerics)

[:punct:] (punctuations)

space

The ANSI C quoting ($'') is used for interpreting \t as literal tab inside $'' (in bash and alike).


问:
How to render only the Year when using date picker from OctoberCMS backend?
I’m using the date picker from the backend, and I’d like to display only the year that the user has selected. For example, instead of rendering 23-12-2017 on the DOM when is use {{ record.year }}, I’d only like to render the year 2017. How do I do this ? Is there a filter or something ?</p>

答:
You can use the date filter for Twig:

```<code>{{ record.date|date("Y") }}
</code>```

By the way, if you are only using the year part of the date, you should also only save the year to the database, not the whole date. This would also mean you wouldn't have to format it in the first place.
And if you need to save the whole date, please consider naming it something other than just year :)

Body:
You can use the date filter for Twig:

{{ record.date|date("Y") }}

By the way, if you are only using the year part of the date, you should also only save the year to the database, not the whole date. This would also mean you wouldn't have to format it in the first place.
And if you need to save the whole date, please consider naming it something other than just year :)


问:
Apply filter to stream in Java
Given the following code I expect the output to be "-3-2-101231" since the filter should go through all the items of the stream, thus printing the item that is evaluating. When the allMatch function is evaluated it should print "1" since it is receiving a stream of positive integers, so it should short-circuit after finding that the first element is not negative.

Why does it print "-3-2-1011" instead of "-3-2-101231"?

```<code>    List<Integer> list = Arrays.asList(-3,-2,-1,0,1,2,3);
    Predicate<Integer> positive = i->{
        System.out.print(i);
        return i>0;
    };
    Predicate<Integer> negative = i->{
        System.out.print(i);
        return i<0;
    };

    list.stream().filter(positive).allMatch(negative);
</code>```

答:
for '1' the value is false. and false && (anything else) will always be false, so it will not evaluate anything else.

Similarly with if statements for both true and false it does lazy evaluation:

```<code>public static void main(String[] args){
    System.out.println("Test1: False && anything else:");
    if (returnFalse() && returnTrue()) {

    }

    System.out.println("Test2: False || anything else:");
    if (returnFalse() || returnTrue()) {

    }
    System.out.println("Test3: True || anything else:");
    if (returnTrue() || returnTrue()) {

    }
    System.out.println("Test4: True && anything else:");
    if (returnTrue() && returnTrue()) {

    }

}
public static boolean returnFalse() {
    System.out.println("false");
    return false;
}

public static boolean returnTrue() {
    System.out.println("true");
    return true;
}
</code>```

The results for this will be:

```<code>Test1: False && anything else:
false
Test2: False || anything else:
false
true
Test3: True || anything else:
true
Test4: True && anything else:
true
true
</code>```

Title: Apply filter to stream in Java

Body:
Given the following code I expect the output to be "-3-2-101231" since the filter should go through all the items of the stream, thus printing the item that is evaluating. When the allMatch function is evaluated it should print "1" since it is receiving a stream of positive integers, so it should short-circuit after finding that the first element is not negative.

Why does it print "-3-2-1011" instead of "-3-2-101231"?

    List<Integer> list = Arrays.asList(-3,-2,-1,0,1,2,3);
    Predicate<Integer> positive = i->{
        System.out.print(i);
        return i>0;
    };
    Predicate<Integer> negative = i->{
        System.out.print(i);
        return i<0;
    };

    list.stream().filter(positive).allMatch(negative);

Body:
for '1' the value is false. and false && (anything else) will always be false, so it will not evaluate anything else.

Similarly with if statements for both true and false it does lazy evaluation:

public static void main(String[] args){
    System.out.println("Test1: False && anything else:");
    if (returnFalse() && returnTrue()) {

    }

    System.out.println("Test2: False || anything else:");
    if (returnFalse() || returnTrue()) {

    }
    System.out.println("Test3: True || anything else:");
    if (returnTrue() || returnTrue()) {

    }
    System.out.println("Test4: True && anything else:");
    if (returnTrue() && returnTrue()) {

    }

}
public static boolean returnFalse() {
    System.out.println("false");
    return false;
}

public static boolean returnTrue() {
    System.out.println("true");
    return true;
}

The results for this will be:

Test1: False && anything else:
false
Test2: False || anything else:
false
true
Test3: True || anything else:
true
Test4: True && anything else:
true
true


问:
What Microsoft tSql code will create "Group Identifiers" for groups of rows delimited by a 1

--drop table GroupIdentifierTest
go
Create table GroupIdentifierTest
(
RowId varchar(10),
[Delimiter] int
)

insert into GroupIdentifierTest
select 'a', 0 union all
select 'b', 0 union all
select 'c', 0 union all
select 'd', 1 union all
select 'e', 0 union all
select 'f', 1
select * from GroupIdentifierTest
delete GroupIdentifierTest
insert into GroupIdentifierTest
select 'a', 1 union all
select 'b', 1 union all
select 'c', 1 union all
select 'd',  2 union all
select 'e', 2 union all
select 'f', 2
select r.RowId, r.Delimiter As GroupId from GroupIdentifierTest r```

If you have a rowset, and the data is in groupings, indicated by a column value of 1,  how can you generate GroupId numbers?

In this example, the first rowset needs to be transformed into the second rowset.

答:
How many groups do you need? Perhaps this will help:

```<code>WITH prep AS
(
  SELECT RowId, delimiter, GroupId = NTILE(2) OVER (ORDER BY RowID)
  FROM GroupIdentifierTest
)
UPDATE prep
SET delimiter = GroupId;

SELECT RowId, Delimiter AS groupID
FROM GroupIdentifierTest;
</code>```

Results:

```<code>RowId      groupID
---------- -----------
a          1
b          1
c          1
d          2
e          2
f          2
</code>```

Body:
--drop table GroupIdentifierTest
go
Create table GroupIdentifierTest
(
RowId varchar(10),
[Delimiter] int
)

insert into GroupIdentifierTest
select 'a', 0 union all
select 'b', 0 union all
select 'c', 0 union all
select 'd', 1 union all
select 'e', 0 union all
select 'f', 1
select * from GroupIdentifierTest
delete GroupIdentifierTest
insert into GroupIdentifierTest
select 'a', 1 union all
select 'b', 1 union all
select 'c', 1 union all
select 'd',  2 union all
select 'e', 2 union all
select 'f', 2
select r.RowId, r.Delimiter As GroupId from GroupIdentifierTest r

If you have a rowset, and the data is in groupings, indicated by a column value of 1,  how can you generate GroupId numbers?

In this example, the first rowset needs to be transformed into the second rowset.

Body:
How many groups do you need? Perhaps this will help:

WITH prep AS
(
  SELECT RowId, delimiter, GroupId = NTILE(2) OVER (ORDER BY RowID)
  FROM GroupIdentifierTest
)
UPDATE prep
SET delimiter = GroupId;

SELECT RowId, Delimiter AS groupID
FROM GroupIdentifierTest;

Results:

RowId      groupID
---------- -----------
a          1
b          1
c          1
d          2
e          2
f          2


问:
How to rename a specific cell in R?
I just want to change the "District of Columbia" to "D.C."

答:
If you have a data frame, you can refer to a position using row and column number. So to change row 9, column 1 of data frame data:

```<code>data[9, 1] <- "D.C."
</code>```

If you had for example a column named state, you could use the column name:

```<code>data[9, "state"] <- "D.C."
</code>```

If you wanted to change all occurrences in the state column:

```<code>data$state <- gsub("District of Columbia", "D.C.", data$state)
</code>```

Title: How to rename a specific cell in R?

Body:
If you have a data frame, you can refer to a position using row and column number. So to change row 9, column 1 of data frame data:

data[9, 1] <- "D.C."

If you had for example a column named state, you could use the column name:

data[9, "state"] <- "D.C."

If you wanted to change all occurrences in the state column:

data$state <- gsub("District of Columbia", "D.C.", data$state)


问:
Start listening again with Socket after a disconnect
I'm writing a small C# Sockets application. Actually I have two, a server and a client.

The user runs the client, enters the IP and port for the server, presses 'connect', and then once connected they can enter text into a textbox and send it to the server.

The server simply displays either "No connection" or "Connection from [ip]:[port]", and the most recent received message underneath.

The server successfully receives messages, and even handles the client disconnect fine.
Now I'm trying to make it listen again after the client has disconnected but for some reason nothing I try will allow it to start listening again.

Here is part of my code:

```<code>    Socket socket;
    private void listen()
    {
        socket = new Socket(AddressFamily.InterNetwork,
            SocketType.Stream, ProtocolType.Tcp);
        socket.Bind(new IPEndPoint(IPAddress.Any, 12345));
        socket.Listen(10);
        socket.BeginAccept(new AsyncCallback(acceptAsync), socket);
    }
</code>```

and

```<code>    private void receiveAsync(IAsyncResult res)
    {
        Socket socket = (Socket)res.AsyncState;

        try
        {
            int nBytes = socket.EndReceive(res);
            if (nBytes > 0)
            {
                Invoke(new MethodInvoker(delegate()
                {
                    lMessage.Text = encoder.GetString(buffer);
                }));
                setupReceiveAsync(socket);
            }
            else
            {
                Invoke(new MethodInvoker(delegate()
                {
                    lConnections.Text = "No Connections.";
                    lMessage.Text = "No Messages.";
                    socket.Shutdown(SocketShutdown.Both);
                    socket.Close();
                    listen();
                }));
            }
        }
        catch { }
    }
</code>```

The last line: listen(); is what throws the error.
I have tried simply calling socket.BeginAccept() again, but that also throws an exception.

The message I'm getting is:

Only one usage of each socket address (protocol/network address/port) is normally permitted

If I don't call my listen() function and instead just call socket.BeginAccept(), then I get "You must first call socket.listen()"

If I call the socket.listen() function, then it tells me it's already connected and cart start listening.

Once I have made an asynchronous connection, and received several asynchronous messages, how then do I begin receiving again?

答:
In async Begin* is always followed by End*. See Using an Asynchronous Server Socket. Your accept method should be something like:

```<code>try {
        listener.Bind(localEP);
        listener.Listen(10);

        while (true) {
            allDone.Reset();

            Console.WriteLine("Waiting for a connection...");
            listener.BeginAccept(
                new AsyncCallback(SocketListener.acceptCallback),
                listener );

            allDone.WaitOne();
        }
    } catch (Exception e) {
</code>```

Server, means that an app that listens on specified port/ip. Is usually, always in a listening mode - that's why it is called a server. It can connect and disconnect a client, but is always in listening mode.

This means, when a server disconnects a client - even then - it is in listening mode; meaning it can accept the incoming connections as well.

Though, disconnection request can come from client or can be forcefully applied by server.

The process for a server is:

Bind to socket

Listen

Accept connections

The process for client is:

Connect to the server

Send/receive messages

There are several ways for server to handle the incoming clients, couple, as follows:

Incoming connections are maintained in a list, for instance within a List<TcpClient>.

One way of handling the incoming clients is through threads. For instance, for each incoming client, spawn a thread that would handle the communication between server and client. For instance, checkout this example.

_

```<code>private  void ListenForClients()
{
  this.tcpListener.Start();

  while (true)
  {
    //blocks until a client has connected to the server
    TcpClient client = this.tcpListener.AcceptTcpClient();

    //create a thread to handle communication
    //with connected client
    Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
    clientThread.Start(client);
  }
}
</code>```

Use single thread and use context switching to manage client communications (TX/RX).

Body:
I'm writing a small C# Sockets application. Actually I have two, a server and a client.

The user runs the client, enters the IP and port for the server, presses 'connect', and then once connected they can enter text into a textbox and send it to the server.

The server simply displays either "No connection" or "Connection from [ip]:[port]", and the most recent received message underneath.

The server successfully receives messages, and even handles the client disconnect fine.
Now I'm trying to make it listen again after the client has disconnected but for some reason nothing I try will allow it to start listening again.

Here is part of my code:

    Socket socket;
    private void listen()
    {
        socket = new Socket(AddressFamily.InterNetwork,
            SocketType.Stream, ProtocolType.Tcp);
        socket.Bind(new IPEndPoint(IPAddress.Any, 12345));
        socket.Listen(10);
        socket.BeginAccept(new AsyncCallback(acceptAsync), socket);
    }

and

    private void receiveAsync(IAsyncResult res)
    {
        Socket socket = (Socket)res.AsyncState;

        try
        {
            int nBytes = socket.EndReceive(res);
            if (nBytes > 0)
            {
                Invoke(new MethodInvoker(delegate()
                {
                    lMessage.Text = encoder.GetString(buffer);
                }));
                setupReceiveAsync(socket);
            }
            else
            {
                Invoke(new MethodInvoker(delegate()
                {
                    lConnections.Text = "No Connections.";
                    lMessage.Text = "No Messages.";
                    socket.Shutdown(SocketShutdown.Both);
                    socket.Close();
                    listen();
                }));
            }
        }
        catch { }
    }

The last line: listen(); is what throws the error.
I have tried simply calling socket.BeginAccept() again, but that also throws an exception.

The message I'm getting is:

Only one usage of each socket address (protocol/network address/port) is normally permitted

If I don't call my listen() function and instead just call socket.BeginAccept(), then I get "You must first call socket.listen()"

If I call the socket.listen() function, then it tells me it's already connected and cart start listening.

Once I have made an asynchronous connection, and received several asynchronous messages, how then do I begin receiving again?

Body:
In async Begin* is always followed by End*. See Using an Asynchronous Server Socket. Your accept method should be something like:

try {
        listener.Bind(localEP);
        listener.Listen(10);

        while (true) {
            allDone.Reset();

            Console.WriteLine("Waiting for a connection...");
            listener.BeginAccept(
                new AsyncCallback(SocketListener.acceptCallback),
                listener );

            allDone.WaitOne();
        }
    } catch (Exception e) {

Server, means that an app that listens on specified port/ip. Is usually, always in a listening mode - that's why it is called a server. It can connect and disconnect a client, but is always in listening mode.

This means, when a server disconnects a client - even then - it is in listening mode; meaning it can accept the incoming connections as well.

Though, disconnection request can come from client or can be forcefully applied by server.

The process for a server is:

Bind to socket

Listen

Accept connections

The process for client is:

Connect to the server

Send/receive messages

There are several ways for server to handle the incoming clients, couple, as follows:

Incoming connections are maintained in a list, for instance within a List<TcpClient>.

One way of handling the incoming clients is through threads. For instance, for each incoming client, spawn a thread that would handle the communication between server and client. For instance, checkout this example.

_

private  void ListenForClients()
{
  this.tcpListener.Start();

  while (true)
  {
    //blocks until a client has connected to the server
    TcpClient client = this.tcpListener.AcceptTcpClient();

    //create a thread to handle communication
    //with connected client
    Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
    clientThread.Start(client);
  }
}

Use single thread and use context switching to manage client communications (TX/RX).


答:
Just loop through the results array, this should do the trick.

var result = [
  {
    "id": 89304,
    "employeeDetails": {
    "id": 102524,
    "version": 9
    }
  },
  {
    "id": 89123,
    "employeeDetails": {
    "id": 102456,
    "version": 18
    }
  }
];

var arr1 = result.map(function(item){
    return [item.id, item.employeeDetails.id, item.employeeDetails.version];
});

/* ES6 Syntax */
let arr2 = result.map((item) => [item.id, item.employeeDetails.id, item.employeeDetails.version]);

console.log(arr1);
console.log(arr2);```


问:
DELETE_FAILED_INTERNAL_ERROR Error while Installing APK
I am using Android Studio 2.2 Preview. I am facing the issue

Failure: Install failed invalid apk

Error: While installing apk,

I have made changes in build.gradle but could not retrack it, please suggest me solution???

答:
For Android Studio on Mac :

Navigation Bar :

Android Studio > Preferences > Build, Execution, Deployment > Instant Run >
Uncheck : Enable Instant Run

For Android Studio on Windows :

File > Settings > Build, Execution, Deployment > Instant Run >
Uncheck : Enable Instant Run


问:
hiding a div with a value/ output from a php and css stament
I am going to use a button to set a value to a variable, I want to be able to hide a
 using the result from a PHP / CSS statement.

$day and $time would be set using the CSS set_date() function. Example below:

```<code>//Check if $day is within a business week/day
if ($day > 5) {
    //Hide the div
    //Check $time is within business hours and day
} else if ($time>=9 && $time<17) {
    //Show the div
    //Otherwise
} else {
   //Make div invisible
}
</code>```

That's how I want to do it but it isn't working as expected, any help would be much appreciated!

If necessary, here's the button resource:

答:
```<code><?php
//check if it is within a business week/day
if ($day > 5) {
?>
//hide the div
<script language="javascript">
$(document).ready(function() {
$("#mydiv").hide();
});
</script>
<?php
}

//check if it is within business hours and day
//if yes show div
elseif ($time>=9 && $time<17) {
?>
//hide the div
<script language="javascript">
$(document).ready(function() {
$("#mydiv").show();
});
</script>
<?php
}
//if not make div not visable
else {
<script language="javascript">
$(document).ready(function() {
$("#mydiv").hide();
});
</script>
}
?>
</code>```

Body:
I am going to use a button to set a value to a variable, I want to be able to hide a
 using the result from a PHP / CSS statement.

$day and $time would be set using the CSS set_date() function. Example below:

//Check if $day is within a business week/day
if ($day > 5) {
    //Hide the div
    //Check $time is within business hours and day
} else if ($time>=9 && $time<17) {
    //Show the div
    //Otherwise
} else {
   //Make div invisible
}

That's how I want to do it but it isn't working as expected, any help would be much appreciated!

If necessary, here's the button resource:


问:
Flask-security Flask-login | login as a user before first request
I am trying to login as a user as soon as I start the server. I am using flask-security which uses flask-login to handle users log in and out.

I attempted this:
Code:

```<code>@app.before_first_request
   def login_user():
       user_datastore.create_user(email='admin', password='admin')
       login_user("admin","admin")
</code>```

Any idea on how to do this?

答:
You can't call your login_user function inside login_user().

Try:

```<code>from flask_security.utils import login_user
@app.before_first_request
def login_admin()
    admin = user_datastore.create_user(email='admin', password='admin')
    login_user(admin)
</code>```

From flask-security docs:

http://pythonhosted.org/Flask-Security-Fork/api.html?#utils

Body:
I am trying to login as a user as soon as I start the server. I am using flask-security which uses flask-login to handle users log in and out.

I attempted this:
Code:

@app.before_first_request
   def login_user():
       user_datastore.create_user(email='admin', password='admin')
       login_user("admin","admin")

Any idea on how to do this?

Body:
You can't call your login_user function inside login_user().

Try:

from flask_security.utils import login_user
@app.before_first_request
def login_admin()
    admin = user_datastore.create_user(email='admin', password='admin')
    login_user(admin)

From flask-security docs:

http://pythonhosted.org/Flask-Security-Fork/api.html?#utils

ContentLicense: CC BY-SA 4.0


问:
lambda with more than one effect
I have three different classes of some common interface Bag. Those are simple containers with some properties. I can add a bunch of stuff in them, e.g ints. For purposes of unit testing, I wanted to add a number of values to each and every one of those Bags. So I used the following IntConsumer:

```<code>IntStream.rangeClosed(1, 300).forEach(new IntConsumer() {
    @Override
    public void accept(int value) {
        staticBag.add(value);
        shuffledBag.add(value);
        randomAccessBag.add(value);
        }
    });
</code>```

My question is how that might be changeable to a lambda expression. Intellij is usually doing a pretty good job at changing those things automatically, but at this point it hasn't been showing me any tips.

答:
How about this:</p>

```<code>IntStream.rangeClosed(1, 300)
  .peek(staticBag::add)
  .peek(shuffledBag::add)
  .forEach(randomAccessBag::add);
</code>```

Title: lambda with more than one effect

Body:
I have three different classes of some common interface Bag. Those are simple containers with some properties. I can add a bunch of stuff in them, e.g ints. For purposes of unit testing, I wanted to add a number of values to each and every one of those Bags. So I used the following IntConsumer:

IntStream.rangeClosed(1, 300).forEach(new IntConsumer() {
    @Override
    public void accept(int value) {
        staticBag.add(value);
        shuffledBag.add(value);
        randomAccessBag.add(value);
        }
    });

My question is how that might be changeable to a lambda expression. Intellij is usually doing a pretty good job at changing those things automatically, but at this point it hasn't been showing me any tips.

Body:
How about this:

IntStream.rangeClosed(1, 300)
  .peek(staticBag::add)
  .peek(shuffledBag::add)
  .forEach(randomAccessBag::add);


问:
Magento2 Database Import Error
I am facing below error when try to import Magento 2 Database to popular hosting company,

ERROR 1227 (42000) at line 1251: Access denied; you need (at least one of) the SUPER privilege(s) for this operation

I read some website/article/blog post and most of place suggested to use --routines tag while we do export, so that will remove MySQL Procedure.

Example: mysqldump --routines

I stuck since last 3 day and no solution work to import database.

Please help somebody to sort out issue.

Error Screenshot

答:
I had same issue and no body can help to you without hosting team. You might have shared hosting and they cant provide supper user privilege, You have to reach to them OR you have to go for own VPS OR Dedicate server.

I personally at that time taken help from Support Team and they imported everything at their end and saved my life :)

Hope it will work fine with you as well.

Title: Magento2 Database Import Error


问:
I'm getting NoSuchElement exception error
I have shared the below code please let me know the correction

```<code>import org.openqa.selenium.By;
import org.openqa.selenium.ie.InternetExplorerDriver;

public class MyClass {

    public static void main(String[] args) throws InterruptedException {
        // TODO Auto-generated method stub
        /*System.setProperty("webdriver.ie.driver","D:\\Backup\\Documents\\Automation\\drivers\\IEDriverServer.exe");
        InternetExplorerDriver driver = new InternetExplorerDriver();
        driver.get("https://www.google.com");

        WebDriverWait driverWait = new WebDriverWait(driver,50);

        driverWait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[@id='lst-ib']"))).click();
        driver.findElementByXPath("//*[@id='lst-ib']").sendKeys("Make My Trip");
        driver.findElementById("_fZl").click();
        driverWait.until(ExpectedConditions.elementToBeClickable(By.linkText("MakeMyTrip, India's No 1 Travel Site | Book Hotels, Flights, Holiday ..."))).click();
        Screenshot S1 = new Screenshot();
        S1.Takescreen();*/
        String username = null;
        String password = null;
        MyClass C1 = new MyClass();
        C1.URLs(username, password);
    }

    public void URLs  (String username, String password) throws InterruptedException
    {

        System.setProperty("webdriver.ie.driver","D:\\Backup\\Documents\\Automation\\drivers\\IEDriverServer.exe");
        InternetExplorerDriver driver = new InternetExplorerDriver();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.get("https://google.com");
        driver.findElement(By.className("lst lst-tbb sbibps")).sendKeys("irctc");
        driver.findElement(By.id("_fZl")).click();
        Thread.sleep(10000);
        driver.findElement(By.linkText("IRCTC Next Generation eTicketing System")).click();
        username = driver.findElement(By.id("usernameId")).getTagName();
        password = driver.findElement(By.className("loginPassword")).getTagName();
        System.out.println(username);
        System.out.println(password);
    }
}
</code>```

Error :

Exception in thread "main" org.openqa.selenium.NoSuchElementException:
  Unable to find element with class name == lst lst-tbb sbibps (WARNING:
  The server did not provide any stacktrace information) Command
  duration or timeout: 10.45 seconds

答:
lst lst-tbb sbibps are actually 3 different classes. To use all of them you can use cssSelector

```<code>driver.findElement(By.cssSelector(".lst.lst-tbb.sbibps")).sendKeys("irctc");
</code>```

With className you can use only one class, although none of them looks unique

```<code>driver.findElement(By.className("lst")).sendKeys("irctc");
// or
driver.findElement(By.className("lst-tbb")).sendKeys("irctc");
// or
river.findElement(By.className("sbibps")).sendKeys("irctc");
</code>```

Body:
I have shared the below code please let me know the correction

import org.openqa.selenium.By;
import org.openqa.selenium.ie.InternetExplorerDriver;

public class MyClass {

    public static void main(String[] args) throws InterruptedException {
        // TODO Auto-generated method stub
        /*System.setProperty("webdriver.ie.driver","D:\\Backup\\Documents\\Automation\\drivers\\IEDriverServer.exe");
        InternetExplorerDriver driver = new InternetExplorerDriver();
        driver.get("https://www.google.com");

        WebDriverWait driverWait = new WebDriverWait(driver,50);

        driverWait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[@id='lst-ib']"))).click();
        driver.findElementByXPath("//*[@id='lst-ib']").sendKeys("Make My Trip");
        driver.findElementById("_fZl").click();
        driverWait.until(ExpectedConditions.elementToBeClickable(By.linkText("MakeMyTrip, India's No 1 Travel Site | Book Hotels, Flights, Holiday ..."))).click();
        Screenshot S1 = new Screenshot();
        S1.Takescreen();*/
        String username = null;
        String password = null;
        MyClass C1 = new MyClass();
        C1.URLs(username, password);
    }

    public void URLs  (String username, String password) throws InterruptedException
    {

        System.setProperty("webdriver.ie.driver","D:\\Backup\\Documents\\Automation\\drivers\\IEDriverServer.exe");
        InternetExplorerDriver driver = new InternetExplorerDriver();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.get("https://google.com");
        driver.findElement(By.className("lst lst-tbb sbibps")).sendKeys("irctc");
        driver.findElement(By.id("_fZl")).click();
        Thread.sleep(10000);
        driver.findElement(By.linkText("IRCTC Next Generation eTicketing System")).click();
        username = driver.findElement(By.id("usernameId")).getTagName();
        password = driver.findElement(By.className("loginPassword")).getTagName();
        System.out.println(username);
        System.out.println(password);
    }
}

Error :

Exception in thread "main" org.openqa.selenium.NoSuchElementException:
  Unable to find element with class name == lst lst-tbb sbibps (WARNING:
  The server did not provide any stacktrace information) Command
  duration or timeout: 10.45 seconds

Body:
lst lst-tbb sbibps are actually 3 different classes. To use all of them you can use cssSelector

driver.findElement(By.cssSelector(".lst.lst-tbb.sbibps")).sendKeys("irctc");

With className you can use only one class, although none of them looks unique

driver.findElement(By.className("lst")).sendKeys("irctc");
// or
driver.findElement(By.className("lst-tbb")).sendKeys("irctc");
// or
river.findElement(By.className("sbibps")).sendKeys("irctc");


问:
Object referring to the object running a specific piece of code in Game Maker
Java Script has it's this.property in it's constructor functions to access the variables of that object such as this.y or this.x. Is there an easy way to do this in game maker without going through a process if gathering the instance id?

I'm trying to draw a button at the position of a specific object, but that button appears in multiple spots on the screen. I tried draw_button(instance.x, instance.y, instance.x+100, instance.y+30, false), but that throws an error.

答:
Each instance has own name. Room Editor -> RMB on instance -> Copy Instance Name (or also Rename Object Instance). Then you can refer the instance using that name.

If you create button using code, but not Room Editor, then you can store id of "parent", like:

```<code>/// Create event of your object
var btn = instance_create(x, y, obj_button);
btn.parent = id;
</code>```

Button's Draw event:

```<code>draw_button(parent.x, parent.y, parent.x + 100, parent.y + 100, true);
</code>```

Body:
Each instance has own name. Room Editor -> RMB on instance -> Copy Instance Name (or also Rename Object Instance). Then you can refer the instance using that name.

If you create button using code, but not Room Editor, then you can store id of "parent", like:

/// Create event of your object
var btn = instance_create(x, y, obj_button);
btn.parent = id;

Button's Draw event:

draw_button(parent.x, parent.y, parent.x + 100, parent.y + 100, true);


答:
result is itself a array which keys are by default 0,1,2 so that you are getting 0

This is actually what you want

```<code>var result = [{
  "id": 89304,
  "employeeDetails": {
    "id": 102524,
    "version": 9
  }
}];

var finalresult = [];
result.forEach(function(record) {
  console.log(getObjValue(record));
})

function getObjValue(obj) {
  var keys = Object.keys(obj);
  for (i = 0; i < keys.length; i++) {
    if (typeof obj[keys[i]] == 'object') {
      getObjValue(obj[keys[i]]);
    } else {
      finalresult.push(obj[keys[i]])
    }
  }
  return finalresult
}
</code>```

Body:
I have the following object:

var result = [{
"id": 89304,
"employeeDetails": {
    "id": 102524,
    "version": 9
}
}];

This is a snippet from a larger object that I'm trying to push into a MySQL table.
What I'm trying to achieve is extract just the values into their own array, which would return this:

[ '89304', '102524', '9' ]

This way, I can easily push the values to the DB.

I have tried doing the following which works fine without nesting:

obKeys = Object.keys(result);
console.log(obKeys);

However, with the nesting, the result I am getting is the following:

[ '0' ]

Can anyone let me know where I am going wrong, or suggest an alternative (better) way of doing this?

Thanks.

Body:
result is itself a array which keys are by default 0,1,2 so that you are getting 0

This is actually what you want

var result = [{
  "id": 89304,
  "employeeDetails": {
    "id": 102524,
    "version": 9
  }
}];

var finalresult = [];
result.forEach(function(record) {
  console.log(getObjValue(record));
})

function getObjValue(obj) {
  var keys = Object.keys(obj);
  for (i = 0; i < keys.length; i++) {
    if (typeof obj[keys[i]] == 'object') {
      getObjValue(obj[keys[i]]);
    } else {
      finalresult.push(obj[keys[i]])
    }
  }
  return finalresult
}


问:
WPML - get sorted list of all plugin languages, both active and inactive
I want to get a full list of all languages included in the WPML plugin, regardless of whether or not they were active. The function icl_get_languages() only returns languages which are active on the site, so does not work here. The language list should be returned in the language of the current locale and should be sorted however that particular language sorts words (e.g. English: A -> Z, Japanese: ア -> オ).

I did "answer your own question", the solution is below. Full credit to the following (my solution is basically just these three stuck together):

https://stackoverflow.com/a/10000042/5374743

https://wpml.org/forums/topic/outputting-language-tag-in-theme/

The fellow at WPML who responded to my support ticket

答:
If anyone's found a cleaner way of doing this, please do share.</p>

```<code><?php

function get_all_langs_names( $lang ) {

    global $wpdb;

    $lang_data = array();

    $languages = $wpdb -> get_results(

        $wpdb -> prepare( "
            SELECT code, english_name, active, tag, name
            FROM {$wpdb -> prefix}icl_languages lang
            INNER JOIN {$wpdb -> prefix}icl_languages_translations trans
            ON lang.code = trans.language_code
            AND trans.display_language_code=%s",
        $lang )

    );

    foreach( $languages as $l ) {

        $lang_data[$l -> code] = array(
            'english_name' => $l -> english_name,
            'active' => $l -> active,
            'tag' => $l -> tag,
            'name' => $l -> name,
        );

    }

    return $lang_data;

}

// get language tag of current site locale...
$code = ICL_LANGUAGE_CODE;

$lang_tag = $wpdb -> get_var("
    SELECT tag
    FROM {$wpdb -> prefix}icl_languages
    WHERE code='{$code}'"
);

// ... and then get language names associated with that tag
$languages = get_all_langs_names( $lang_tag );

// sort language array alphabetically, or however current language orders words
function sort_languages( $a, $b ) {

    return strcmp( $a['name'], $b['name'] );

}

usort( $languages, 'sort_languages' );

print_r( $languages );
</code>```

Body:
If anyone's found a cleaner way of doing this, please do share.

<?php

function get_all_langs_names( $lang ) {

    global $wpdb;

    $lang_data = array();

    $languages = $wpdb -> get_results(

        $wpdb -> prepare( "
            SELECT code, english_name, active, tag, name
            FROM {$wpdb -> prefix}icl_languages lang
            INNER JOIN {$wpdb -> prefix}icl_languages_translations trans
            ON lang.code = trans.language_code
            AND trans.display_language_code=%s",
        $lang )

    );

    foreach( $languages as $l ) {

        $lang_data[$l -> code] = array(
            'english_name' => $l -> english_name,
            'active' => $l -> active,
            'tag' => $l -> tag,
            'name' => $l -> name,
        );

    }

    return $lang_data;

}

// get language tag of current site locale...
$code = ICL_LANGUAGE_CODE;

$lang_tag = $wpdb -> get_var("
    SELECT tag
    FROM {$wpdb -> prefix}icl_languages
    WHERE code='{$code}'"
);

// ... and then get language names associated with that tag
$languages = get_all_langs_names( $lang_tag );

// sort language array alphabetically, or however current language orders words
function sort_languages( $a, $b ) {

    return strcmp( $a['name'], $b['name'] );

}

usort( $languages, 'sort_languages' );

print_r( $languages );


问:
WSO2 IoT 3.0.0 cannot started in mac
I try to start  WSO2 IoT 3.0.0 server on macOS it's stuck like below. However I was using the old version and it has been working like a charm.

Another note: me deployment server is : windows server 2012, WSO2 IoT 3.0.0 server works successfully, but I can not access devicemgt link, it's redirect me to black page.

https://localhost:9443/devicemgt/uuf/login?referer=/

--------------------- Update --------------------
FYI: carbon works like a charm
https://localhost:9443/carbon/admin/login.jsp

Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize=512m; support was removed in 8.0
[2017-02-10 19:37:36,170] [IoT-Core]  INFO - AppDiscoveryComponent WebApp Discovery component activated
[2017-02-10 19:37:36,317] [IoT-Core]  INFO - AppManagerMobileComponent WSO2MDM_INTERNAL MDM is bound to App Manager.
[2017-02-10 19:37:36,317] [IoT-Core]  INFO - AppManagerMobileComponent App Manger Mobile Component activated.
[2017-02-10 19:37:36,456] [IoT-Core]  INFO - CarbonCoreActivator Starting WSO2 Carbon...
[2017-02-10 19:37:36,457] [IoT-Core]  INFO - CarbonCoreActivator Operating System : Mac OS X 10.12.2, x86_64
[2017-02-10 19:37:36,457] [IoT-Core]  INFO - CarbonCoreActivator Java Home        : /Library/Java/JavaVirtualMachines/jdk1.8.0_111.jdk/Contents/Home/jre
[2017-02-10 19:37:36,458] [IoT-Core]  INFO - CarbonCoreActivator Java Version     : 1.8.0_111
[2017-02-10 19:37:36,458] [IoT-Core]  INFO - CarbonCoreActivator Java VM          : Java HotSpot(TM) 64-Bit Server VM 25.111-b14,Oracle Corporation
[2017-02-10 19:37:36,458] [IoT-Core]  INFO - CarbonCoreActivator Carbon Home      : /Volumes/WorkSpace/ParentApp/wso2iot-3.0.0/core
[2017-02-10 19:37:36,459] [IoT-Core]  INFO - CarbonCoreActivator Java Temp Dir    : /Volumes/WorkSpace/ParentApp/wso2iot-3.0.0/core/tmp
[2017-02-10 19:37:36,460] [IoT-Core]  INFO - CarbonCoreActivator User             : root, en-US, Asia/Kuala_Lumpur
[2017-02-10 19:37:36,620] [IoT-Core]  WARN - ValidationResultPrinter Swap Memory size (MB): 1024 of the system is below the recommended minimum size :2047
[2017-02-10 19:37:36,621] [IoT-Core]  WARN - ValidationResultPrinter Carbon is configured to use the default keystore (wso2carbon.jks). To maximize security when deploying to a production environment, configure a new keystore with a unique password in the production server profile.
Activating org.wso2.jaggery.scxml with RealmService enabled
[2017-02-10 19:37:54,558] [IoT-Core]  INFO - TaglibUriRule TLD skipped. URI: http://tiles.apache.org/tags-tiles is already defined

答:
What is the version of your OS, are you using Sierra or above? if so you may want to have a look at your /etc/host configurations, as host resolution is known to cause this type of problems.

Please have a look at :

https://medium.com/@ruwanyatawara/how-to-fix-macos-sierra-wso2-server-starting-delay-4279b9e69133

Title: WSO2 IoT 3.0.0 cannot started in mac


问:
Set web.config transform in Asp.NET Core
I've just came across with problem of web.config transformation in asp.net core.

There are two files: base web.config and web.prod-zone-a.config. My aim is to use transformation inside web.prod-zone-a.config when publishing my project.
I have the following "prod-zone-a" configuration settings in .csproj:

<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'prod-zone-a|AnyCPU' ">
    <IntermediateOutputPath>obj\Debug\netcoreapp1.1</IntermediateOutputPath>
    <DebugSymbols>true</DebugSymbols>
    <Optimize>false</Optimize>
    <DefineConstants>TRACE;DEBUG;NETCOREAPP1_1</DefineConstants>
    <Configuration>prod-zone-a</Configuration>
</PropertyGroup>
```

<p>web.prod-zone-a.config looks like:</p>

<pre class="lang-xml prettyprint-override"><code><system.webServer>
    <handlers>
        <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
    </handlers>
    <aspNetCore>
        <environmentVariables xdt:Transform="Replace">
            <environmentVariable name="ASPNETCORE_ENVIRONMENT" value="prod-zone-a" />
        </environmentVariables>
    </aspNetCore>
</system.webServer>
</code>```

I tried to run publish by two commands:

```<code>dotnet msbuild /t:Publish /p:OutputPath=c:\delivery /p:Configuration=prod-zone-a
</code>```

and

```<code>dotnet publish --configuration prod-zone-a --output c:\delivery
</code>```

But no transformation applies to web.config on output - just the default value.
Do I miss something in configuration or command executing?

答:
There is a well-documented tool on github for xdt-transformations.
Also it doesn't depend on command, both of dotnet publish and dotnet msbuild works fine

Body:
I've just came across with problem of web.config transformation in asp.net core.

There are two files: base web.config and web.prod-zone-a.config. My aim is to use transformation inside web.prod-zone-a.config when publishing my project.
I have the following "prod-zone-a" configuration settings in .csproj:

<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'prod-zone-a|AnyCPU' ">
    <IntermediateOutputPath>obj\Debug\netcoreapp1.1</IntermediateOutputPath>
    <DebugSymbols>true</DebugSymbols>
    <Optimize>false</Optimize>
    <DefineConstants>TRACE;DEBUG;NETCOREAPP1_1</DefineConstants>
    <Configuration>prod-zone-a</Configuration>
</PropertyGroup>

web.prod-zone-a.config looks like:

<system.webServer>
    <handlers>
        <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
    </handlers>
    <aspNetCore>
        <environmentVariables xdt:Transform="Replace">
            <environmentVariable name="ASPNETCORE_ENVIRONMENT" value="prod-zone-a" />
        </environmentVariables>
    </aspNetCore>
</system.webServer>

I tried to run publish by two commands:

dotnet msbuild /t:Publish /p:OutputPath=c:\delivery /p:Configuration=prod-zone-a

and

dotnet publish --configuration prod-zone-a --output c:\delivery

But no transformation applies to web.config on output - just the default value.
Do I miss something in configuration or command executing?


问:
Memory management regarding CATransition's delegate
According to the documentation:

Important: The delegate object is retained by the receiver. This is a rare exception to the memory management rules described in Memory Management Programming Guide.

Right now, I'm setting the delegate and not releasing it, which is what I'd normally do.

When I set the delegate of a CATransition object, am I leaking the delegate by not releasing it? I've tried this method and it crashed my code.

答: I don't think so. I think the documentation is just saying that the receiver is retaining the delegate internally, which means it also has the responsibility to release it internally. Imo, you should not be doing an extra release. </p>


问:
Change JavaScript variable depending on selected DropDownList
I have a table that has a lot of DropDownList that i had change each of the class name depending on the iteration :

```<code><table id="categoryTable" class="table table-striped table-hover">
    <tr class="header">
        <th>
            @Html.DisplayNameFor(model => model.Category)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.SubCategory)
        </th>
        <th>New Category</th>
        <th>New Subcategory</th>
        <th></th>
    </tr>

    @if (Model != null) { int i = 1; foreach (var item in Model) {

    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Category)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.SubCategory)
        </td>

        <td>
            <input type="hidden" class="varIteration" value="@i" /> @Html.DropDownList("CategoryId", null, "Select Your Category", htmlAttributes: new { @class = "form-control Category" + i })
        </td>
        <td>
            <input type="hidden" class=@( "SubCategoryID_CategoryID_initial"+@i) value="@i" /> @Html.DropDownList("SubCategoryId", null, "Select Your Subcategory", htmlAttributes: new { @class = "form-control SubCategory" + i })
        </td>
        <td>
            <button type="submit" class="btn">
                <i class="fa fa-check"> Update</i>
            </button>
            @*
            <input type="submit" value="Save" class="fa fa-check" />*@
        </td>
    </tr>
    i++; } }

</table>
</code>```

I need to change the subcategory values depending on the selected value in the Category using the next script below that doesn't work only on time with the first category drop down list:

```<code>$(document).ready(function(e) {
    var iteration = $(".varIteration").val(); // iteration = 1 only
    getSubCat(true, $(".SubCategoryID_CategoryID_initial" + iteration).val(), iteration);
    $(document).on("change", ".Category" + iteration, function(event) {
        getSubCat(false, $(".Category" + iteration).val(), iteration);
    });

    function getSubCat(load, changed, iteration) {
        alert(iteration)
        var url = "/auc.accesscontrol/profiles/GetSubCatIDByCatID";
        var initialSubCat = $(".SubCategoryID_CategoryID_initial").val();
        var initialCat = $(".SubCategoryID_SubCategoryID_initial").val();
        if (load) {
            $('.Category' + iteration + ' option[value="' + initialCat + '"]').prop("selected", true);
        }
        if (initialCat == null) {
            changed = $(".Category" + iteration).val();
        }
        $.getJSON(url, {
            id: changed
        }, function(data) {
            alert(changed);
            $(".SubCategory" + iteration).empty();
            $(".SubCategory" + iteration).append("<option value= '0'>Select Your Subcategory</option>");
            $.each(data, function(index, item) {
                $(".SubCategory" + iteration).append("<option value='" + item.SubCategoryId + "'>" + item.Name + "</option>");
                $('.SubCategory' + iteration + ' option[value="' + initialSubCat + '"]').prop("selected", true);
            });
        });
    };
});
</code>```

When I check the view class names will find that drop down list for categories like : Category1, Category2 ,...etc
and the Subcategory : SubCategory1, Subcategory2, ....etc
hidden input values : will changed depending on the last i.
Need a help to change the iteration variable depending on the selected category drop down list.

EDIT :
This is the JsonResult function:

```<code>public JsonResult GetSubCatIDByCatID(int id)
    {
        db.Configuration.ProxyCreationEnabled = false;
        var subCategoryList = db.SubCategory.Where(m => m.CategoryId == id).ToList();
        return Json(subCategoryList, JsonRequestBehavior.AllowGet);
    }
</code>```

答:
I had Solved it using the below code:
HTML View:

```<code>        <table id="categoryTable" class="table table-striped table-hover">
        <tr class="header">
            <th>
                @Html.DisplayNameFor(model => model.Category)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.SubCategory)
            </th>
            <th></th>
        </tr>

        @if (Model != null)
        {
            int i = 1;
            foreach (var item in Model)
            {

                <tr>
                    <td>
                        @Html.DisplayFor(modelItem => item.Category)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.SubCategory)
                    </td>
                    <td>
                        <div class="col-md-10">
                            <input type="hidden" id="varIteration" value="@i" />
                            @Html.DropDownListFor(m => item.Category, new SelectList(db.Category.Where(x => !x.IsDeleted), "CategoryId", "Name"), "Select Your Category", htmlAttributes: new { @class = "form-control Category", @id = "Category" + i })
                        </div>
                    </td>
                    <td>
                        <div class="col-md-10">
                            <input type="hidden" id="SubCategoryID_CategoryID_initial" value="@item.SubCategory" />
                            @Html.DropDownListFor(m => item.SubCategory, new SelectList(db.SubCategory.Where(x => !x.IsDeleted), "SubCategoryId", "Name"), "Select Your Subcategory", htmlAttributes: new { @class = "form-control", @id = "SubCategory" + i })
                        </div>
                    </td>

                    <td>
                        @Html.ActionLink("    ", "UnifiedAccessCategoryIndex", new { Category = item.Category, Subcategory = item.SubCategory }, new { @class = "fa fa-edit fa-lg" })
                        @*<button type="submit" class="btn">

                                <i class="fa fa-check"> Update</i>
                            </button>*@
                        @*<input type="submit" value="Save" class="fa fa-check" />*@
                    </td>
                </tr>
                i++;
            }
        }

    </table>
</code>```

And inside my JS code:

```<code>$(document).ready(function (e) {
    var iteration = null;
    getSubCat(true, $('[class^=SubCategoryID_CategoryID_initial]').val(), iteration);
    $(document).on("change", 'select[id^=Category]', function (event) {
        iteration = $(this).closest("td").find("#varIteration").val();
        getSubCat(false, $('#Category' + iteration).val(), iteration);
    });
});
function getSubCat(load, changed, iteration) {
    var url = "/auc.accesscontrol/profiles/GetSubCatIDByCatID";

    var initialSubCat = $('[id^="SubCategoryID_CategoryID_initial"]').val();
    var initialCat = $('[id^="SubCategoryID_SubCategoryID_initial"]').val();
    if (load) {

        $('#Category' + iteration + ' option[value="' + initialCat + '"]').prop("selected", true);
    }
    if (initialCat == null) {
        changed = $('#Category' + iteration).val();
    }
    $.getJSON(url, { id: changed }, function (data) {
        $('#SubCategory' + iteration).empty();
        $('#SubCategory' + iteration).append("<option value= '0'>Select Your Subcategory</option>");
        $.each(data, function (index, item) {
            $('#SubCategory' + iteration).append("<option value='" + item.SubCategoryId + "'>" + item.Name + "</option>");
            $('#SubCategory' + iteration + ' option[value="' + initialSubCat + '"]').prop("selected", true);
        });
    });
};
</code>```

Body:
I have a table that has a lot of DropDownList that i had change each of the class name depending on the iteration :

            @Html.DisplayNameFor(model => model.Category)

            @Html.DisplayNameFor(model => model.SubCategory)

        New Category
        New Subcategory

    @if (Model != null) { int i = 1; foreach (var item in Model) {

            @Html.DisplayFor(modelItem => item.Category)

            @Html.DisplayFor(modelItem => item.SubCategory)

            <input type="hidden" class="varIteration" value="@i" /> @Html.DropDownList("CategoryId", null, "Select Your Category", htmlAttributes: new { @class = "form-control Category" + i })

            <input type="hidden" class=@( "SubCategoryID_CategoryID_initial"+@i) value="@i" /> @Html.DropDownList("SubCategoryId", null, "Select Your Subcategory", htmlAttributes: new { @class = "form-control SubCategory" + i })

            <button type="submit" class="btn">
                 Update
            </button>
            @*
            <input type="submit" value="Save" class="fa fa-check" />*@

    i++; } }

I need to change the subcategory values depending on the selected value in the Category using the next script below that doesn't work only on time with the first category drop down list:

$(document).ready(function(e) {
    var iteration = $(".varIteration").val(); // iteration = 1 only
    getSubCat(true, $(".SubCategoryID_CategoryID_initial" + iteration).val(), iteration);
    $(document).on("change", ".Category" + iteration, function(event) {
        getSubCat(false, $(".Category" + iteration).val(), iteration);
    });

    function getSubCat(load, changed, iteration) {
        alert(iteration)
        var url = "/auc.accesscontrol/profiles/GetSubCatIDByCatID";
        var initialSubCat = $(".SubCategoryID_CategoryID_initial").val();
        var initialCat = $(".SubCategoryID_SubCategoryID_initial").val();
        if (load) {
            $('.Category' + iteration + ' option[value="' + initialCat + '"]').prop("selected", true);
        }
        if (initialCat == null) {
            changed = $(".Category" + iteration).val();
        }
        $.getJSON(url, {
            id: changed
        }, function(data) {
            alert(changed);
            $(".SubCategory" + iteration).empty();
            $(".SubCategory" + iteration).append("<option value= '0'>Select Your Subcategory</option>");
            $.each(data, function(index, item) {
                $(".SubCategory" + iteration).append("<option value='" + item.SubCategoryId + "'>" + item.Name + "</option>");
                $('.SubCategory' + iteration + ' option[value="' + initialSubCat + '"]').prop("selected", true);
            });
        });
    };
});

When I check the view class names will find that drop down list for categories like : Category1, Category2 ,...etc
and the Subcategory : SubCategory1, Subcategory2, ....etc
hidden input values : will changed depending on the last i.
Need a help to change the iteration variable depending on the selected category drop down list.

EDIT :
This is the JsonResult function:

public JsonResult GetSubCatIDByCatID(int id)
    {
        db.Configuration.ProxyCreationEnabled = false;
        var subCategoryList = db.SubCategory.Where(m => m.CategoryId == id).ToList();
        return Json(subCategoryList, JsonRequestBehavior.AllowGet);
    }

Body:
I had Solved it using the below code:
HTML View:

        <table id="categoryTable" class="table table-striped table-hover">
        <tr class="header">
            <th>
                @Html.DisplayNameFor(model => model.Category)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.SubCategory)
            </th>
            <th></th>
        </tr>

        @if (Model != null)
        {
            int i = 1;
            foreach (var item in Model)
            {

                <tr>
                    <td>
                        @Html.DisplayFor(modelItem => item.Category)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.SubCategory)
                    </td>
                    <td>
                        <div class="col-md-10">
                            <input type="hidden" id="varIteration" value="@i" />
                            @Html.DropDownListFor(m => item.Category, new SelectList(db.Category.Where(x => !x.IsDeleted), "CategoryId", "Name"), "Select Your Category", htmlAttributes: new { @class = "form-control Category", @id = "Category" + i })
                        </div>
                    </td>
                    <td>
                        <div class="col-md-10">
                            <input type="hidden" id="SubCategoryID_CategoryID_initial" value="@item.SubCategory" />
                            @Html.DropDownListFor(m => item.SubCategory, new SelectList(db.SubCategory.Where(x => !x.IsDeleted), "SubCategoryId", "Name"), "Select Your Subcategory", htmlAttributes: new { @class = "form-control", @id = "SubCategory" + i })
                        </div>
                    </td>

                    <td>
                        @Html.ActionLink("    ", "UnifiedAccessCategoryIndex", new { Category = item.Category, Subcategory = item.SubCategory }, new { @class = "fa fa-edit fa-lg" })
                        @*<button type="submit" class="btn">

                                <i class="fa fa-check"> Update</i>
                            </button>*@
                        @*<input type="submit" value="Save" class="fa fa-check" />*@
                    </td>
                </tr>
                i++;
            }
        }

    </table>

And inside my JS code:

$(document).ready(function (e) {
    var iteration = null;
    getSubCat(true, $('[class^=SubCategoryID_CategoryID_initial]').val(), iteration);
    $(document).on("change", 'select[id^=Category]', function (event) {
        iteration = $(this).closest("td").find("#varIteration").val();
        getSubCat(false, $('#Category' + iteration).val(), iteration);
    });
});
function getSubCat(load, changed, iteration) {
    var url = "/auc.accesscontrol/profiles/GetSubCatIDByCatID";

    var initialSubCat = $('[id^="SubCategoryID_CategoryID_initial"]').val();
    var initialCat = $('[id^="SubCategoryID_SubCategoryID_initial"]').val();
    if (load) {

        $('#Category' + iteration + ' option[value="' + initialCat + '"]').prop("selected", true);
    }
    if (initialCat == null) {
        changed = $('#Category' + iteration).val();
    }
    $.getJSON(url, { id: changed }, function (data) {
        $('#SubCategory' + iteration).empty();
        $('#SubCategory' + iteration).append("<option value= '0'>Select Your Subcategory</option>");
        $.each(data, function (index, item) {
            $('#SubCategory' + iteration).append("<option value='" + item.SubCategoryId + "'>" + item.Name + "</option>");
            $('#SubCategory' + iteration + ' option[value="' + initialSubCat + '"]').prop("selected", true);
        });
    });
};


答:
Something like this should do if you have a matrix:</p>

```<code>x <- matrix(c(9, "District of Columbia", "DC", 59),nrow=1 )
x[x == "District of Columbia"] <- "DC"
</code>```

Title: How to rename a specific cell in R?

Body: I just want to change the "District of Columbia" to "D.C."

Body:
Something like this should do if you have a matrix:

x <- matrix(c(9, "District of Columbia", "DC", 59),nrow=1 )
x[x == "District of Columbia"] <- "DC"


问:
How can D3 read csv from url?
I would like to read a csv file from the given url link. This didn't work. Anyone can help me?... Thank you</p>

```<code>d3.csv("example.abc.csv", function(data){
    console.log(data);
});
</code>```

答:
Without more details, the only thing I can think of is that you are trying to load a file on a different URL / port than your script is running in the browser (e.g. the script is running on http://localhost:3000 and your data file is being loaded from http://localhost:8888).

Basically, the error that you are getting is telling you that the data file can't be loaded because it exists on a different URL / port than the URL / port that the script that is trying to retrieve it.

Title: How can D3 read csv from url?

Body:
I would like to read a csv file from the given url link. This didn't work. Anyone can help me?... Thank you

d3.csv("example.abc.csv", function(data){
    console.log(data);
});


问:
How to send post request to the below post method using postman rest client
I just want to know, how to send JSON object to createTrackInJSON(Track track)  method, with @Post annotation through postman rest client.
here,how to pass JSON object to createTrackInJSON(Track track)  method,with @Post annotation ?

```<code>import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import com.mkyong.Track;

@Path("/json/metallica")
public class JSONService {

    @GET
    @Path("/get")
    @Produces(MediaType.APPLICATION_JSON)
    public Track getTrackInJSON() {

        Track track = new Track();
        track.setTitle("Enter Sandman");
        track.setSinger("Metallica");
        System.out.println("inside get method . . .");
        return track;

    }

    @POST
    @Path("/post")
    @Consumes(MediaType.APPLICATION_JSON)
    public Response createTrackInJSON(Track track) {
        System.out.println("inside post method . .");
        String result = "Track saved : " + track;
        return Response.status(201).entity(result).build();

    }

}

//Track class is:

public class Track {
String title;
String singer;

public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}

public String getSinger() {
    return singer;
}

public void setSinger(String singer) {
    this.singer = singer;
}

@Override
public String toString() {
    return "Track [title=" + title + ", singer=" + singer + "]";
}

}
</code>```

答:
The Interface of Postman is changing acccording to the updates.

So You can get full information about postman can get Here.

https://www.getpostman.com/docs/requests

Body:
I just want to know, how to send JSON object to createTrackInJSON(Track track)  method, with @Post annotation through postman rest client.
here,how to pass JSON object to createTrackInJSON(Track track)  method,with @Post annotation ?

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import com.mkyong.Track;

@Path("/json/metallica")
public class JSONService {

    @GET
    @Path("/get")
    @Produces(MediaType.APPLICATION_JSON)
    public Track getTrackInJSON() {

        Track track = new Track();
        track.setTitle("Enter Sandman");
        track.setSinger("Metallica");
        System.out.println("inside get method . . .");
        return track;

    }

    @POST
    @Path("/post")
    @Consumes(MediaType.APPLICATION_JSON)
    public Response createTrackInJSON(Track track) {
        System.out.println("inside post method . .");
        String result = "Track saved : " + track;
        return Response.status(201).entity(result).build();

    }

}

//Track class is:

public class Track {
String title;
String singer;

public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}

public String getSinger() {
    return singer;
}

public void setSinger(String singer) {
    this.singer = singer;
}

@Override
public String toString() {
    return "Track [title=" + title + ", singer=" + singer + "]";
}

}


问:
Checking for items in tables Lua
I have an input file

```<code>Corn Fiber 17
Beans Protein 12
Milk Protien 15
Butter Fat 201
Eggs Fat 2
Bread Fiber 12
Eggs Cholesterol 4
Eggs Protein 8
Milk Fat 5
</code>```

This is loaded into a table. I can then run commands to check the value of the items. For example >print(foods.Eggs.Fat)
2

What I need to do is be able to search if an item is already in the table. I have a function that checks if the table has a value, but it doesn't seem to be working. My code:

```<code>  file = io.open("food.txt")

    function has_value (tab, val)
    for index, value in ipairs(tab) do
        if value == val then
            return true
        else
            return false
        end
    end
end

    foods = {}
    for line in file:lines()
        do
            local f, n, v = line:match("(%a+) (%a+) (%d+)")
            if foods[f] then
                foods[f][n] = v
            else
                foods[f] = {[n] = v}
            end
        end
    file:close()

    if has_value(foods, "Eggs") then
        print("Yes")
    else
        print("No")
    end
</code>```

Even if the table does contain the item, I still am getting false returned from the function. In the example above, if has_value(names, "Eggs") then is printing "No" even when I know Eggs is in the table. Where is my error?

答:
You're looking for value in this case, when really you should be looking for key.

```<code>function has_key(table, key)
    return table[key]~=nil
end
</code>```

This function should do what you need it to, and much faster than searching for values, too!

Title: Checking for items in tables Lua

Body:
I have an input file

Corn Fiber 17
Beans Protein 12
Milk Protien 15
Butter Fat 201
Eggs Fat 2
Bread Fiber 12
Eggs Cholesterol 4
Eggs Protein 8
Milk Fat 5

This is loaded into a table. I can then run commands to check the value of the items. For example >print(foods.Eggs.Fat)
2

What I need to do is be able to search if an item is already in the table. I have a function that checks if the table has a value, but it doesn't seem to be working. My code:

  file = io.open("food.txt")

    function has_value (tab, val)
    for index, value in ipairs(tab) do
        if value == val then
            return true
        else
            return false
        end
    end
end

    foods = {}
    for line in file:lines()
        do
            local f, n, v = line:match("(%a+) (%a+) (%d+)")
            if foods[f] then
                foods[f][n] = v
            else
                foods[f] = {[n] = v}
            end
        end
    file:close()

    if has_value(foods, "Eggs") then
        print("Yes")
    else
        print("No")
    end

Even if the table does contain the item, I still am getting false returned from the function. In the example above, if has_value(names, "Eggs") then is printing "No" even when I know Eggs is in the table. Where is my error?

Body:
You're looking for value in this case, when really you should be looking for key.

function has_key(table, key)
    return table[key]~=nil
end

This function should do what you need it to, and much faster than searching for values, too!


问:
Splitting user input into strings of specific length
I'm writing a C program that parses user input into a char, and two strings of set length. The user input is stored into a buffer using fgets, and then parsed with sscanf. The trouble is, the three fields have a maximum length. If a string exceeds this length, the remaining characters before the next whitespace should be consumed/discarded.

```<code>#include <stdio.h>
#define IN_BUF_SIZE 256

int main(void) {
    char inputStr[IN_BUF_SIZE];
    char command;
    char firstname[6];
    char surname[6];

    fgets(inputStr, IN_BUF_SIZE, stdin);
    sscanf(inputStr, "%c %5s %5s", &command, firstname, surname);
    printf("%c %s %s\n", command, firstname, surname);
}
</code>```

So, with an input of

a bbbbbbbb cc

the desired output would be

a bbbbb cc

but is instead the output is

a bbbbb bbb

Using a format specifier "%c%*s %5s%*s %5s%*s" runs into the opposite problem, where each substring needs to exceed the set length to get to the desired outcome.

Is there way to achieve this by using format specifiers, or is the only way saving the substrings in buffers of their own before cutting them down to the desired length?

答:
One way to split the input buffer as OP desires is to use multiple calls to sscanf(), and to use the %n conversion specifier to keep track of the number of characters read. In the code below, the input string is scanned in three stages.

First, the pointer strPos is assigned to point to the first character of inputStr. Then the input string is scanned with " %c%n%*[^ ]%n". This format string skips over any initial whitespaces that a user might enter before the first character, and stores the first character in command. The %n directive tells sscanf() to store the number of characters read so far in the variable n; then the *[^ ] directive tells sscanf() to read and ignore any characters until a whitespace character is encountered. This effectively skips over any remaining characters that were entered after the initial command character. The %n directive appears again, and overwrites the previous value with the number of characters read until this point. The reason for using %n twice is that, if the user enters a character followed by a whitespace (as expected), the second directive will find no matches, and sscanf() will exit without ever reaching the final %n directive.

The pointer strPos is moved to the beginning of the remaining string by adding n to it, and sscanf() is called a second time, this time with "%5s%n%*[^ ]%n". Here, up to 5 characters are read into the character array firstname[], the number of characters read is saved by the %n directive, any remaining non-whitespace characters are read and ignored, and finally, if the scan made it this far, the number of characters read is saved again.

strPos is increased by n again, and the final scan only needs "%s" to complete the task.

Note that the return value of fgets() is checked to be sure that it was successful. The call to fgets() was changed slightly to:

```<code>fgets(inputStr, sizeof inputStr, stdin)
</code>```

The sizeof operator is used here instead of IN_BUF_SIZE. This way, if the declaration of inputStr is changed later, this line of code will still be correct. Note that the sizeof operator works here because inputStr is an array, and arrays do not decay to pointers in sizeof expressions. But, if inputStr were passed into a function, sizeof could not be used in this way inside the function, because arrays decay to pointers in most expressions, including function calls. Some, @DavidC.Rankin, prefer constants as OP has used. If this seems confusing, I would suggest sticking with the constant IN_BUF_SIZE.

Also note that the return values for each of the calls to sscanf() are checked to be certain that the input matches expectations. For example, if the user enters a command and a first name, but no surname, the program will print an error message and exit. It is worth pointing out that, if the user enters say, a command character and first name only, after the second sscanf() the match may have failed on \n, and strPtr is then incremented to point to the \0 and so is still in bounds. But this relies on the newline being in the string. With no newline, the match might fail on \0, and then strPtr would be incremented out of bounds before the next call to sscanf(). Fortunately, fgets() retains the newline, unless the input line is larger than the specified size of the buffer. Then there is no \n, only the \0 terminator. A more robust program would check the input string for \n, and add one if needed. It would not hurt to increase the size of IN_BUF_SIZE.

```<code>#include <stdio.h>
#include <stdlib.h>

#define IN_BUF_SIZE 256

int main(void)
{
    char inputStr[IN_BUF_SIZE];
    char command;
    char firstname[6];
    char surname[6];
    char *strPos = inputStr;        // next scan location
    int n = 0;                      // holds number of characters read

    if (fgets(inputStr, sizeof inputStr, stdin) == NULL) {
        fprintf(stderr, "Error in fgets()\n");
        exit(EXIT_FAILURE);
    }

    if (sscanf(strPos, " %c%n%*[^ ]%n", &command, &n, &n) < 1) {
        fprintf(stderr, "Input formatting error: command\n");
        exit(EXIT_FAILURE);
    }

    strPos += n;
    if (sscanf(strPos, "%5s%n%*[^ ]%n", firstname, &n, &n) < 1) {
        fprintf(stderr, "Input formatting error: firstname\n");
        exit(EXIT_FAILURE);
    }

    strPos += n;
    if (sscanf(strPos, "%5s", surname) < 1) {
        fprintf(stderr, "Input formatting error: surname\n");
        exit(EXIT_FAILURE);
    }

    printf("%c %s %s\n", command, firstname, surname);
}
</code>```

Sample interaction:

```<code>a Zaphod Beeblebrox
a Zapho Beebl
</code>```

The fscanf() functions have a reputation for being subtle and error-prone; the format strings used above may seem a little bit tricky. By writing a function to skip to the next word in the input string, the calls to sscanf() can be simplified. In the code below, skipToNext() takes a pointer to a string as input; if the first character of the string is a \0 terminator, the pointer is returned unchanged. All initial non-whitespace characters are skipped over, then any whitespace characters are skipped, up to the next non-whitespace character (which may be a \0). A pointer is returned to this non-whitespace character.

The resulting program is a little bit longer than the previous program, but it may be easier to understand, and it certainly has simpler format strings. This program does differ from the first in that it no longer accepts leading whitespace in the string. If the user enters whitespace before the command character, this is considered erroneous input.

```<code>#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

#define IN_BUF_SIZE 256

char * skipToNext(char *);

int main(void)
{
    char inputStr[IN_BUF_SIZE];
    char command;
    char firstname[6];
    char surname[6];
    char *strPos = inputStr;        // next scan location

    if (fgets(inputStr, sizeof inputStr, stdin) == NULL) {
        fprintf(stderr, "Error in fgets()\n");
        exit(EXIT_FAILURE);
    }

    if (sscanf(strPos, "%c", &command) != 1 || isspace(command)) {
        fprintf(stderr, "Input formatting error: command\n");
        exit(EXIT_FAILURE);
    }

    strPos = skipToNext(strPos);
    if (sscanf(strPos, "%5s", firstname) != 1) {
        fprintf(stderr, "Input formatting error: firstname\n");
        exit(EXIT_FAILURE);
    }

    strPos = skipToNext(strPos);
    if (sscanf(strPos, "%5s", surname) != 1) {
        fprintf(stderr, "Input formatting error: surname\n");
        exit(EXIT_FAILURE);
    }

    printf("%c %s %s\n", command, firstname, surname);
}

char * skipToNext(char *c)
{
    int inWord = isspace(*c) ? 0 : 1;

    if (inWord && *c != '\0') {
        while (!isspace(*c)) {
            ++c;
        }
    }

    inWord = 0;

    while (isspace(*c)) {
        ++c;
    }

    return c;
}
</code>```

Body:
I'm writing a C program that parses user input into a char, and two strings of set length. The user input is stored into a buffer using fgets, and then parsed with sscanf. The trouble is, the three fields have a maximum length. If a string exceeds this length, the remaining characters before the next whitespace should be consumed/discarded.

#include <stdio.h>
#define IN_BUF_SIZE 256

int main(void) {
    char inputStr[IN_BUF_SIZE];
    char command;
    char firstname[6];
    char surname[6];

    fgets(inputStr, IN_BUF_SIZE, stdin);
    sscanf(inputStr, "%c %5s %5s", &command, firstname, surname);
    printf("%c %s %s\n", command, firstname, surname);
}

So, with an input of

a bbbbbbbb cc

the desired output would be

a bbbbb cc

but is instead the output is

a bbbbb bbb

Using a format specifier "%c%*s %5s%*s %5s%*s" runs into the opposite problem, where each substring needs to exceed the set length to get to the desired outcome.

Is there way to achieve this by using format specifiers, or is the only way saving the substrings in buffers of their own before cutting them down to the desired length?

Body:
One way to split the input buffer as OP desires is to use multiple calls to sscanf(), and to use the %n conversion specifier to keep track of the number of characters read. In the code below, the input string is scanned in three stages.

First, the pointer strPos is assigned to point to the first character of inputStr. Then the input string is scanned with " %c%n%*[^ ]%n". This format string skips over any initial whitespaces that a user might enter before the first character, and stores the first character in command. The %n directive tells sscanf() to store the number of characters read so far in the variable n; then the *[^ ] directive tells sscanf() to read and ignore any characters until a whitespace character is encountered. This effectively skips over any remaining characters that were entered after the initial command character. The %n directive appears again, and overwrites the previous value with the number of characters read until this point. The reason for using %n twice is that, if the user enters a character followed by a whitespace (as expected), the second directive will find no matches, and sscanf() will exit without ever reaching the final %n directive.

The pointer strPos is moved to the beginning of the remaining string by adding n to it, and sscanf() is called a second time, this time with "%5s%n%*[^ ]%n". Here, up to 5 characters are read into the character array firstname[], the number of characters read is saved by the %n directive, any remaining non-whitespace characters are read and ignored, and finally, if the scan made it this far, the number of characters read is saved again.

strPos is increased by n again, and the final scan only needs "%s" to complete the task.

Note that the return value of fgets() is checked to be sure that it was successful. The call to fgets() was changed slightly to:

fgets(inputStr, sizeof inputStr, stdin)

The sizeof operator is used here instead of IN_BUF_SIZE. This way, if the declaration of inputStr is changed later, this line of code will still be correct. Note that the sizeof operator works here because inputStr is an array, and arrays do not decay to pointers in sizeof expressions. But, if inputStr were passed into a function, sizeof could not be used in this way inside the function, because arrays decay to pointers in most expressions, including function calls. Some, @DavidC.Rankin, prefer constants as OP has used. If this seems confusing, I would suggest sticking with the constant IN_BUF_SIZE.

Also note that the return values for each of the calls to sscanf() are checked to be certain that the input matches expectations. For example, if the user enters a command and a first name, but no surname, the program will print an error message and exit. It is worth pointing out that, if the user enters say, a command character and first name only, after the second sscanf() the match may have failed on \n, and strPtr is then incremented to point to the \0 and so is still in bounds. But this relies on the newline being in the string. With no newline, the match might fail on \0, and then strPtr would be incremented out of bounds before the next call to sscanf(). Fortunately, fgets() retains the newline, unless the input line is larger than the specified size of the buffer. Then there is no \n, only the \0 terminator. A more robust program would check the input string for \n, and add one if needed. It would not hurt to increase the size of IN_BUF_SIZE.

#include <stdio.h>
#include <stdlib.h>

#define IN_BUF_SIZE 256

int main(void)
{
    char inputStr[IN_BUF_SIZE];
    char command;
    char firstname[6];
    char surname[6];
    char *strPos = inputStr;        // next scan location
    int n = 0;                      // holds number of characters read

    if (fgets(inputStr, sizeof inputStr, stdin) == NULL) {
        fprintf(stderr, "Error in fgets()\n");
        exit(EXIT_FAILURE);
    }

    if (sscanf(strPos, " %c%n%*[^ ]%n", &command, &n, &n) < 1) {
        fprintf(stderr, "Input formatting error: command\n");
        exit(EXIT_FAILURE);
    }

    strPos += n;
    if (sscanf(strPos, "%5s%n%*[^ ]%n", firstname, &n, &n) < 1) {
        fprintf(stderr, "Input formatting error: firstname\n");
        exit(EXIT_FAILURE);
    }

    strPos += n;
    if (sscanf(strPos, "%5s", surname) < 1) {
        fprintf(stderr, "Input formatting error: surname\n");
        exit(EXIT_FAILURE);
    }

    printf("%c %s %s\n", command, firstname, surname);
}

Sample interaction:

a Zaphod Beeblebrox
a Zapho Beebl

The fscanf() functions have a reputation for being subtle and error-prone; the format strings used above may seem a little bit tricky. By writing a function to skip to the next word in the input string, the calls to sscanf() can be simplified. In the code below, skipToNext() takes a pointer to a string as input; if the first character of the string is a \0 terminator, the pointer is returned unchanged. All initial non-whitespace characters are skipped over, then any whitespace characters are skipped, up to the next non-whitespace character (which may be a \0). A pointer is returned to this non-whitespace character.

The resulting program is a little bit longer than the previous program, but it may be easier to understand, and it certainly has simpler format strings. This program does differ from the first in that it no longer accepts leading whitespace in the string. If the user enters whitespace before the command character, this is considered erroneous input.

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

#define IN_BUF_SIZE 256

char * skipToNext(char *);

int main(void)
{
    char inputStr[IN_BUF_SIZE];
    char command;
    char firstname[6];
    char surname[6];
    char *strPos = inputStr;        // next scan location

    if (fgets(inputStr, sizeof inputStr, stdin) == NULL) {
        fprintf(stderr, "Error in fgets()\n");
        exit(EXIT_FAILURE);
    }

    if (sscanf(strPos, "%c", &command) != 1 || isspace(command)) {
        fprintf(stderr, "Input formatting error: command\n");
        exit(EXIT_FAILURE);
    }

    strPos = skipToNext(strPos);
    if (sscanf(strPos, "%5s", firstname) != 1) {
        fprintf(stderr, "Input formatting error: firstname\n");
        exit(EXIT_FAILURE);
    }

    strPos = skipToNext(strPos);
    if (sscanf(strPos, "%5s", surname) != 1) {
        fprintf(stderr, "Input formatting error: surname\n");
        exit(EXIT_FAILURE);
    }

    printf("%c %s %s\n", command, firstname, surname);
}

char * skipToNext(char *c)
{
    int inWord = isspace(*c) ? 0 : 1;

    if (inWord && *c != '\0') {
        while (!isspace(*c)) {
            ++c;
        }
    }

    inWord = 0;

    while (isspace(*c)) {
        ++c;
    }

    return c;
}