问:
Native app OAuth2 authorization
we want to create a native mobile app using OAuth2.
How to protect from stealing clientID (this information can be obtained by anybody)? Someone can create his own app and act as our app by using our clientID? </p>

答:
Yes, if someone retrieves your clientId/clientSecret, he can act as your app and sadly, there is no way to fully remove credentials from your application.

At a higher level, your app needs an identifier and a secret to authenticate to your service. If you remove the secret from your app, you need to get it from somewhere else (it could be your user typing it, this would be the same as having an auth for the user and giving him a token to perform further API calls).

However, you can make it harder for reversers to obtain the credentials, as explained in this article.
To make it even harder, you could force all your API calls to be done in HTTPS and enable SSL Certificate Pinning thus making Proxy Debugging/Man In The Middle difficult to pull off.

Ultimately, you should clearly identify which API calls should be public (with only the OAuth token to access those resources) and which should require a user authentication.

PS: Google's (Android Security Best Practices)[https://developer.android.com/training/best-security.html] could be a good start !

Title: Native app OAuth2 authorization


来源: stackexchange

问:
How to set icons for all TabBarItem
I'm new to iOS, but I will try to explain what is my problem.

So I have, Navigation controller, TabBar Controller, and in TabBar Controller I have three viewcontroller.

So in the tab bar, I have three tabbarIcon.

Programmatically I set icons for tab bar items in their view controllers, in viewdidload method. So yes I know that when I  will start my application, icons will not load because it needs to call viewdidload.
So...

How can I set icons for all tabbarItem automatically, when the application will start?

答:
You can do that when application will start as below:    </p>

```<code>UITabBar *tabBar = self.tabBarController.tabBar;
UITabBarItem *tabBarItem1 = [tabBar.items objectAtIndex:0];
UITabBarItem *tabBarItem2 = [tabBar.items objectAtIndex:1];
UITabBarItem *tabBarItem3 = [tabBar.items objectAtIndex:2];

tabBarItem1.selectedImage = [[UIImage imageNamed:@"icon1_selected"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
tabBarItem1.image = [[UIImage imageNamed:@"icon1"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];

tabBarItem2.selectedImage = [[UIImage imageNamed:@"icon2_selected"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
tabBarItem2.image = [[UIImage imageNamed:@"icon2"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];

tabBarItem3.selectedImage = [[UIImage imageNamed:@"icon3_selected"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
tabBarItem3.image = [[UIImage imageNamed:@"icon3"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to set icons for all TabBarItem

Body:
You can do that when application will start as below:

UITabBar *tabBar = self.tabBarController.tabBar;
UITabBarItem *tabBarItem1 = [tabBar.items objectAtIndex:0];
UITabBarItem *tabBarItem2 = [tabBar.items objectAtIndex:1];
UITabBarItem *tabBarItem3 = [tabBar.items objectAtIndex:2];

tabBarItem1.selectedImage = [[UIImage imageNamed:@"icon1_selected"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
tabBarItem1.image = [[UIImage imageNamed:@"icon1"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];

tabBarItem2.selectedImage = [[UIImage imageNamed:@"icon2_selected"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
tabBarItem2.image = [[UIImage imageNamed:@"icon2"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];

tabBarItem3.selectedImage = [[UIImage imageNamed:@"icon3_selected"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
tabBarItem3.image = [[UIImage imageNamed:@"icon3"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];


问:
Newtonsoft.Json serialize using property value as root name
I have to serialize a list of objects in Json in C#, I'm using Newtonsoft.Json
I need to use the name value of the objects as the root name, like this:

```<code>"employees"  :
  {
    "John" :
      {
        "id" : 18,
        "email" : "john@email.com"
       },
    "Jack" :
       {
         "id" : 21,
         "email" : "jack@email.com"
        }
   }
</code>```

Where John and Jack are the values of the name property for my employees

答:
Not the best solution but quick
You can use dictionary before serialization like this

```<code>class Example
{
    static void Main()
    {
        var l = new[]
        {
            new Employee {Id = 1, Name = "1", Email = "1"},
            new Employee {Id = 2, Name = "2", Email = "2"},
            new Employee {Id = 2, Name = "3", Email = "3"}
        };

        var s = JsonConvert.SerializeObject(new { employees = l.ToDictionary(x => x.Name, x => x) });
    }

    class Employee
    {
        public int Id { get; set; }

        [JsonIgnore]
        public string Name { get; set; }
        public string Email { get; set; }
    }
}
</code>```

Output:

```<code>{"employees":{"1":{"Id":1,"Email":"1"},"2":{"Id":2,"Email":"2"},"3":{"Id":2,"Email":"3"}}}
</code>```

You can find more information here https://www.newtonsoft.com/json/help/html/SerializationAttributes.htm I think you can solve this in more elegant way  using JsonConverterAttribute but it can be not easy

Body:
I have to serialize a list of objects in Json in C#, I'm using Newtonsoft.Json
I need to use the name value of the objects as the root name, like this:

"employees"  :
  {
    "John" :
      {
        "id" : 18,
        "email" : "john@email.com"
       },
    "Jack" :
       {
         "id" : 21,
         "email" : "jack@email.com"
        }
   }

Where John and Jack are the values of the name property for my employees

Body:
Not the best solution but quick
You can use dictionary before serialization like this

class Example
{
    static void Main()
    {
        var l = new[]
        {
            new Employee {Id = 1, Name = "1", Email = "1"},
            new Employee {Id = 2, Name = "2", Email = "2"},
            new Employee {Id = 2, Name = "3", Email = "3"}
        };

        var s = JsonConvert.SerializeObject(new { employees = l.ToDictionary(x => x.Name, x => x) });
    }

    class Employee
    {
        public int Id { get; set; }

        [JsonIgnore]
        public string Name { get; set; }
        public string Email { get; set; }
    }
}

Output:

{"employees":{"1":{"Id":1,"Email":"1"},"2":{"Id":2,"Email":"2"},"3":{"Id":2,"Email":"3"}}}

You can find more information here https://www.newtonsoft.com/json/help/html/SerializationAttributes.htm I think you can solve this in more elegant way  using JsonConverterAttribute but it can be not easy


问:
java mongodb driver how do you catch exceptions?
I want to be able to detect if a mongo server is available from the java driver for the purpose of reacting to any abnormal events as one would in JDBC land etc. It all works fine when the server is up but I am struggling to understand why it is so difficult to detect errors. I have a feeling its because the mongo client runs in a different thread and it doesn't re throw to me or something?

```<code>try {
        MongoClient mongoClient = new MongoClient("localhost", 27017);
        MongoDatabase db = mongoClient.getDatabase("mydb");
        // if db is down or error getting people collection handle it in catch block
        MongoCollection<Document> people = commentarr.getCollection("people");
    } catch (Exception e) {
        // handle server down or failed query here.
    }
</code>```

The result is

```<code>INFO: Exception in monitor thread while connecting to server localhost:27017
</code>```

With the resulting stack trace containing a few different exceptions which I have tried to catch but my catch blocks still didn't do anything.

```<code>com.mongodb.MongoSocketOpenException: Exception opening socket
Caused by: java.net.ConnectException: Connection refused
</code>```

I am using the java mongodb driver 3.0.4, most posts I read are from an older API with hacks like MongoClient.getDatabaseNames() which throws a MongoException if errors, except this is deprecated now and replaced with MongoClient.listDatabaseNames() which doesn't have the same error throwing semantics.

Is there a way to just execute a mongo query from the java driver in a try catch block and actually have the exception caught?

答:
You can redirect System.err to a ByteArrayOutputStream buffer. If a runtime exception is thrown, it will be collected into the buffer.
See an answer to a similar problem at: https://stackoverflow.com/a/47699292/7388679

Body:
I want to be able to detect if a mongo server is available from the java driver for the purpose of reacting to any abnormal events as one would in JDBC land etc. It all works fine when the server is up but I am struggling to understand why it is so difficult to detect errors. I have a feeling its because the mongo client runs in a different thread and it doesn't re throw to me or something?

try {
        MongoClient mongoClient = new MongoClient("localhost", 27017);
        MongoDatabase db = mongoClient.getDatabase("mydb");
        // if db is down or error getting people collection handle it in catch block
        MongoCollection<Document> people = commentarr.getCollection("people");
    } catch (Exception e) {
        // handle server down or failed query here.
    }

The result is

INFO: Exception in monitor thread while connecting to server localhost:27017

With the resulting stack trace containing a few different exceptions which I have tried to catch but my catch blocks still didn't do anything.

com.mongodb.MongoSocketOpenException: Exception opening socket
Caused by: java.net.ConnectException: Connection refused

I am using the java mongodb driver 3.0.4, most posts I read are from an older API with hacks like MongoClient.getDatabaseNames() which throws a MongoException if errors, except this is deprecated now and replaced with MongoClient.listDatabaseNames() which doesn't have the same error throwing semantics.

Is there a way to just execute a mongo query from the java driver in a try catch block and actually have the exception caught?


问:
Unable to pull from GCR registry using docker engine-api and long lived JSON file
In the advanced authentication methods documentation for google cloud container registry explains a method for login to the registry using a JSON Key file with the docker cli, this just works fine

$ docker login -u _json_key -p "$(cat keyfile.json)" https://gcr.io

However I'm trying to use that same keyfile.json file to login to the registry using the golang docker/engine-api libraries, I have some working code that this seems to be authenticating fine into other registryies, but always providing a file with the following structure

```<code>{
  "auths": {
    "cr.whatever.com": {
      "password": "PASSWORD",
      "username": "registry"
    }
  }
}
</code>```

By passing that Unmarshal file into ImageBuildOptions function here to then be consumed here

However is not working when using the keyfile.json or a working config.json ...

The docker documentation states that a JSON base64 encoded object with username and password should be used as described here into the Header Parameters section.

I've tried multiple option to produce a file that can be successfully consumed into the docker X-Registry-Config header without much luck...

Any help/hint would be much appreciated.

Thanks!

答:
Thank you for your help jsand, I finally draft a working code function as below</p>

```<code>func (d *DockerEngineClient) BuildImage(archive, modelId string, authConfigs map[string]types.AuthConfig) (types.ImageBuildResponse, error) {
    buildContext, err := os.Open(archive)
    defer buildContext.Close()

    c, err := ioutil.ReadFile(os.Getenv("GOOGLE_APPLICATION_CREDENTIALS_FILE"))
    if err != nil {
        return err
    }

    var authConfigs2 map[string]types.AuthConfig
    authConfigs2 = make(map[string]types.AuthConfig)

    authConfigs2["gcr.io"] = types.AuthConfig{
        Username: "_json_key",
        Password: string(c),
        ServerAddress: fmt.Sprintf("https://%s", d.remoteRegistryPrefix),
    }

    buildOptions := types.ImageBuildOptions{
        Tags:        []string{fmt.Sprintf("%s/%s", d.remoteRegistryPrefix, modelId)},
        AuthConfigs: authConfigs2,
    }

    var buildResponse types.ImageBuildResponse

    buildResponse, err = d.client.ImageBuild(context.TODO(), buildContext, buildOptions)
    if err != nil {
        return buildResponse, err
    }

    b, _ := ioutil.ReadAll(buildResponse.Body)
    fmt.Printf("%s\n", b)
    buildResponse.Body.Close()

    return buildResponse, err
}
</code>```

Body:
In the advanced authentication methods documentation for google cloud container registry explains a method for login to the registry using a JSON Key file with the docker cli, this just works fine

$ docker login -u _json_key -p "$(cat keyfile.json)" https://gcr.io

However I'm trying to use that same keyfile.json file to login to the registry using the golang docker/engine-api libraries, I have some working code that this seems to be authenticating fine into other registryies, but always providing a file with the following structure

{
  "auths": {
    "cr.whatever.com": {
      "password": "PASSWORD",
      "username": "registry"
    }
  }
}

By passing that Unmarshal file into ImageBuildOptions function here to then be consumed here

However is not working when using the keyfile.json or a working config.json ...

The docker documentation states that a JSON base64 encoded object with username and password should be used as described here into the Header Parameters section.

I've tried multiple option to produce a file that can be successfully consumed into the docker X-Registry-Config header without much luck...

Any help/hint would be much appreciated.

Thanks!

Body:
Thank you for your help jsand, I finally draft a working code function as below

func (d *DockerEngineClient) BuildImage(archive, modelId string, authConfigs map[string]types.AuthConfig) (types.ImageBuildResponse, error) {
    buildContext, err := os.Open(archive)
    defer buildContext.Close()

    c, err := ioutil.ReadFile(os.Getenv("GOOGLE_APPLICATION_CREDENTIALS_FILE"))
    if err != nil {
        return err
    }

    var authConfigs2 map[string]types.AuthConfig
    authConfigs2 = make(map[string]types.AuthConfig)

    authConfigs2["gcr.io"] = types.AuthConfig{
        Username: "_json_key",
        Password: string(c),
        ServerAddress: fmt.Sprintf("https://%s", d.remoteRegistryPrefix),
    }

    buildOptions := types.ImageBuildOptions{
        Tags:        []string{fmt.Sprintf("%s/%s", d.remoteRegistryPrefix, modelId)},
        AuthConfigs: authConfigs2,
    }

    var buildResponse types.ImageBuildResponse

    buildResponse, err = d.client.ImageBuild(context.TODO(), buildContext, buildOptions)
    if err != nil {
        return buildResponse, err
    }

    b, _ := ioutil.ReadAll(buildResponse.Body)
    fmt.Printf("%s\n", b)
    buildResponse.Body.Close()

    return buildResponse, err
}


问:
Adding custom tag in message node in Android Smack 4.2
I have implemented the Smack for one to one chat in my Android App.

Now i have a requirement to send the message in the following format:

```<code><message id="783475-35345-35-345-353" from="xyz@x.com" type="chat" to="abc@x.com" nick="james"><body>Hello</body></message>
</code>```

But so far my message looks like below:

```<code><message id="783475-35345-35-345-353" from="xyz@x.com" type="chat" to="abc@x.com" ><body>Hello</body></message>
</code>```

Below is my code:

```<code>Message message = new Message();
message.setStanzaId(UUID.randomUUID().toString());
message.setType(Message.Type.chat);
message.setBody(textToSend.getText().toString());
message.setTo(chat.getXmppAddressOfChatPartner());
message.setFrom(ownJid);
</code>```

I could not find a way to add the custom tag "nick" in the "message" node. Can someone please help me with it. I tried the extension provided by the Smack but they all add an extra node but not a tag in the existing node.

答: I wouldn't recommend using custom top level stanza attributes. And Smack does not support it. There is an incomplete PR at https://github.com/igniterealtime/Smack/pull/69 which would add support thought.</p>

Body:
I have implemented the Smack for one to one chat in my Android App.

Now i have a requirement to send the message in the following format:

<message id="783475-35345-35-345-353" from="xyz@x.com" type="chat" to="abc@x.com" nick="james">Hello</message>

But so far my message looks like below:

<message id="783475-35345-35-345-353" from="xyz@x.com" type="chat" to="abc@x.com" >Hello</message>

Below is my code:

Message message = new Message();
message.setStanzaId(UUID.randomUUID().toString());
message.setType(Message.Type.chat);
message.setBody(textToSend.getText().toString());
message.setTo(chat.getXmppAddressOfChatPartner());
message.setFrom(ownJid);

I could not find a way to add the custom tag "nick" in the "message" node. Can someone please help me with it. I tried the extension provided by the Smack but they all add an extra node but not a tag in the existing node.


问:
Execute Shell/Bash in Go
I am trying to start a shell process in Go. This is my code:

```<code>func StartShell() (*Shell, error) {
    cmd := exec.Command("sh")

    stderr, err := cmd.StderrPipe()
    if err != nil {
        return nil, err
    }

    stdin, err := cmd.StdinPipe()
    if err != nil {
        return nil, err
    }

    stdout, err := cmd.StdoutPipe()
    if err != nil {
        return nil, err
    }

    if err := cmd.Start(); err != nil {
        return nil, err
    }

    sh := &Shell{
        cmd:       cmd,
        stderr:    stderr,
        stdin:     stdin,
        stdout:    stdout,
    }

    // this will read forever, but it is only for illustrative purposes
    for {
        b := make([]byte, 2048)
        fmt.Println(stdout.Read(b))
    }

    return sh, nil
}
</code>```

If I execute above function as it is, I will not get any output, however if I change sh to cmd and execute it on Windows, it prints some data at the beginning and waits forever (that is OK). Example output:

```<code>36 <nil>
129 <nil>
</code>```

This led me to thinking that it may be Linux way. So I changed the command to ls and executed it on Linux. In short: it works as expected.

Next, I redirected stdout, stderr and stdin to the process ones. I've added following snippet just above cmd.Start():

```<code>// without those three below, `sh` would not print anything to stdout
cmd.Stdout = os.Stdout
cmd.Stdin = os.Stdin
cmd.Stderr = os.Stderr
</code>```

When executed now, I have fully operational sh process redirected to my terminal. It only works when all three streams are redirected.

Why does this happen? Ideally, I'd like to start shell process in a background and run commands from within that shell without printing it to terminal. (I am aware that this is not optimal solution.)

答:
On some systems a process will not terminate until it can flush its data to stdout/stderr so it's necessary to drain those streams entirely before the process will exit. Similarly, some processes will try to read stdin entirely, so they nead a stream to read before the process will exit.

If you don't want to print the subprocess output to the standard streams then consider redirecting them to another stream that will consume their data (e.g. a byte buffer or a discard writer).

```<code>cmd.Stdin = strings.NewReader("") // Empty string goes to stdin

out := bytes.NewBuffer([]byte{})
cmd.Stdout = out // Put stdout into a new byte buffer

cmd.Stderr = ioutil.Discard // Discard stderr
</code>```

ContentLicense: CC BY-SA 4.0

Title: Execute Shell/Bash in Go

Body:
I am trying to start a shell process in Go. This is my code:

func StartShell() (*Shell, error) {
    cmd := exec.Command("sh")

    stderr, err := cmd.StderrPipe()
    if err != nil {
        return nil, err
    }

    stdin, err := cmd.StdinPipe()
    if err != nil {
        return nil, err
    }

    stdout, err := cmd.StdoutPipe()
    if err != nil {
        return nil, err
    }

    if err := cmd.Start(); err != nil {
        return nil, err
    }

    sh := &Shell{
        cmd:       cmd,
        stderr:    stderr,
        stdin:     stdin,
        stdout:    stdout,
    }

    // this will read forever, but it is only for illustrative purposes
    for {
        b := make([]byte, 2048)
        fmt.Println(stdout.Read(b))
    }

    return sh, nil
}

If I execute above function as it is, I will not get any output, however if I change sh to cmd and execute it on Windows, it prints some data at the beginning and waits forever (that is OK). Example output:

36 <nil>
129 <nil>

This led me to thinking that it may be Linux way. So I changed the command to ls and executed it on Linux. In short: it works as expected.

Next, I redirected stdout, stderr and stdin to the process ones. I've added following snippet just above cmd.Start():

// without those three below, `sh` would not print anything to stdout
cmd.Stdout = os.Stdout
cmd.Stdin = os.Stdin
cmd.Stderr = os.Stderr

When executed now, I have fully operational sh process redirected to my terminal. It only works when all three streams are redirected.

Why does this happen? Ideally, I'd like to start shell process in a background and run commands from within that shell without printing it to terminal. (I am aware that this is not optimal solution.)

Body:
On some systems a process will not terminate until it can flush its data to stdout/stderr so it's necessary to drain those streams entirely before the process will exit. Similarly, some processes will try to read stdin entirely, so they nead a stream to read before the process will exit.

If you don't want to print the subprocess output to the standard streams then consider redirecting them to another stream that will consume their data (e.g. a byte buffer or a discard writer).

cmd.Stdin = strings.NewReader("") // Empty string goes to stdin

out := bytes.NewBuffer([]byte{})
cmd.Stdout = out // Put stdout into a new byte buffer

cmd.Stderr = ioutil.Discard // Discard stderr


问:
Pandas agg function gives different results for numpy std vs nanstd
I'm converting some numpy code to use pandas DataFrame. The data potentially contains NaN values, so I make use of numpy's nan functions such as nanstd in the original code. I was of the impression that pandas skips NaN values by default, so I switched to using the regular versions of the same functions.

I want to group the data and compute some statistics on it using agg(), however when I use np.std() I am getting different results to the original code, even in cases where the data doesn't contain any NaNs

Here's a small example demonstrating the problem

```<code>>>> arr = np.array([[1.17136, 1.11816],
                    [1.13096, 1.04134],
                    [1.13865, 1.03414],
                    [1.09053, 0.96330],
                    [1.02455, 0.94728],
                    [1.18182, 1.04950],
                    [1.09620, 1.06686]])

>>> df = pd.DataFrame(arr,
                      index=['foo']*3 + ['bar']*4,
                      columns=['A', 'B'])

>>> df
           A        B
foo  1.17136  1.11816
foo  1.13096  1.04134
foo  1.13865  1.03414
bar  1.09053  0.96330
bar  1.02455  0.94728
bar  1.18182  1.04950
bar  1.09620  1.06686

>>> g = df.groupby(df.index)

>>> g['A'].agg([np.mean, np.median, np.std])
         mean    median       std
bar  1.098275  1.093365  0.064497
foo  1.146990  1.138650  0.021452

>>> g['A'].agg([np.mean, np.median, np.nanstd])
         mean    median    nanstd
bar  1.098275  1.093365  0.055856
foo  1.146990  1.138650  0.017516
</code>```

If I compute the std values with the numpy functions, I get the expected result in both cases. What's going on inside the agg() function?

```<code>>>> np.std(df.loc['foo', 'A'])
0.01751583474079002
>>> np.nanstd(df.loc['foo', 'A'])
0.017515834740790021
</code>```

Edit:

As mentioned in the answer linked by Vivek Harikrishnan, pandas uses a different method to compute the std. This seems to match my results

```<code>>>> g['A'].agg(['mean', 'median', 'std'])
         mean    median       std
bar  1.098275  1.093365  0.064497
foo  1.146990  1.138650  0.021452
</code>```

And if I specify a lambda that calls np.std() I get the expected result

```<code>>>> g['A'].agg([np.mean, np.median, lambda x: np.std(x)])
         mean    median  <lambda>
bar  1.098275  1.093365  0.055856
foo  1.146990  1.138650  0.017516
</code>```

This suggests that the pandas functions are being called instead when I write g['A'].agg([np.mean, np.median, np.std]). The question is why does this happen when I explicitly tell it to use the numpy functions?

答:
It seems that Pandas either replaces np.std in the .agg([np.mean, np.median, np.std]) call with the built-in Pandas Series.std() method or calls np.std(series, ddof=1):

```<code>In [337]: g['A'].agg([np.mean, np.median, np.std, lambda x: np.std(x)])
Out[337]:
         mean    median       std  <lambda>
bar  1.098275  1.093365  0.064497  0.055856
foo  1.146990  1.138650  0.021452  0.017516
</code>```

NOTE: pay attention that np.std and lambda x: np.std(x) producing different results.

if we specify ddof=1 (Pandas default) explicitly, then we will have the same result:

```<code>In [338]: g['A'].agg([np.mean, np.median, np.std, lambda x: np.std(x, ddof=1)])
Out[338]:
         mean    median       std  <lambda>
bar  1.098275  1.093365  0.064497  0.064497
foo  1.146990  1.138650  0.021452  0.021452
</code>```

using built-in 'std' produces the same result:

```<code>In [341]: g['A'].agg([np.mean, np.median, 'std', lambda x: np.std(x, ddof=1)])
Out[341]:
         mean    median       std  <lambda>
bar  1.098275  1.093365  0.064497  0.064497
foo  1.146990  1.138650  0.021452  0.021452
</code>```

The second rule of Python Zen says it all:

```<code>In [340]: import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.  # <----------- NOTE !!!
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
</code>```

Body:
I'm converting some numpy code to use pandas DataFrame. The data potentially contains NaN values, so I make use of numpy's nan functions such as nanstd in the original code. I was of the impression that pandas skips NaN values by default, so I switched to using the regular versions of the same functions.

I want to group the data and compute some statistics on it using agg(), however when I use np.std() I am getting different results to the original code, even in cases where the data doesn't contain any NaNs

Here's a small example demonstrating the problem

>>> arr = np.array([[1.17136, 1.11816],
                    [1.13096, 1.04134],
                    [1.13865, 1.03414],
                    [1.09053, 0.96330],
                    [1.02455, 0.94728],
                    [1.18182, 1.04950],
                    [1.09620, 1.06686]])

>>> df = pd.DataFrame(arr,
                      index=['foo']*3 + ['bar']*4,
                      columns=['A', 'B'])

>>> df
           A        B
foo  1.17136  1.11816
foo  1.13096  1.04134
foo  1.13865  1.03414
bar  1.09053  0.96330
bar  1.02455  0.94728
bar  1.18182  1.04950
bar  1.09620  1.06686

>>> g = df.groupby(df.index)

>>> g['A'].agg([np.mean, np.median, np.std])
         mean    median       std
bar  1.098275  1.093365  0.064497
foo  1.146990  1.138650  0.021452

>>> g['A'].agg([np.mean, np.median, np.nanstd])
         mean    median    nanstd
bar  1.098275  1.093365  0.055856
foo  1.146990  1.138650  0.017516

If I compute the std values with the numpy functions, I get the expected result in both cases. What's going on inside the agg() function?

>>> np.std(df.loc['foo', 'A'])
0.01751583474079002
>>> np.nanstd(df.loc['foo', 'A'])
0.017515834740790021

Edit:

As mentioned in the answer linked by Vivek Harikrishnan, pandas uses a different method to compute the std. This seems to match my results

>>> g['A'].agg(['mean', 'median', 'std'])
         mean    median       std
bar  1.098275  1.093365  0.064497
foo  1.146990  1.138650  0.021452

And if I specify a lambda that calls np.std() I get the expected result

>>> g['A'].agg([np.mean, np.median, lambda x: np.std(x)])
         mean    median  <lambda>
bar  1.098275  1.093365  0.055856
foo  1.146990  1.138650  0.017516

This suggests that the pandas functions are being called instead when I write g['A'].agg([np.mean, np.median, np.std]). The question is why does this happen when I explicitly tell it to use the numpy functions?

Body:
It seems that Pandas either replaces np.std in the .agg([np.mean, np.median, np.std]) call with the built-in Pandas Series.std() method or calls np.std(series, ddof=1):

In [337]: g['A'].agg([np.mean, np.median, np.std, lambda x: np.std(x)])
Out[337]:
         mean    median       std  <lambda>
bar  1.098275  1.093365  0.064497  0.055856
foo  1.146990  1.138650  0.021452  0.017516

NOTE: pay attention that np.std and lambda x: np.std(x) producing different results.

if we specify ddof=1 (Pandas default) explicitly, then we will have the same result:

In [338]: g['A'].agg([np.mean, np.median, np.std, lambda x: np.std(x, ddof=1)])
Out[338]:
         mean    median       std  <lambda>
bar  1.098275  1.093365  0.064497  0.064497
foo  1.146990  1.138650  0.021452  0.021452

using built-in 'std' produces the same result:

In [341]: g['A'].agg([np.mean, np.median, 'std', lambda x: np.std(x, ddof=1)])
Out[341]:
         mean    median       std  <lambda>
bar  1.098275  1.093365  0.064497  0.064497
foo  1.146990  1.138650  0.021452  0.021452

The second rule of Python Zen says it all:

In [340]: import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.  # <----------- NOTE !!!
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!


问:
Why isn't my date formatting as expected?
My date from the database table looks like this:

"2017-12-07 14:42:38.0611177 +00:00"

I'm trying to format it in my HTML like this:

{{ note.CreatedAt | date : "MMM d, y" }}

I was expecting the date to look like this:

Dec 7, 2017

But, the result looks like this:

Can someone show me what I'm doing wrong?

答:
You have to convert your date as a timestamp before filter it.

Aleksey remark is a good point, you can get timestamp from controller:

```<code>angular.module('app').controller('dateCtrl', ['$scope', function($scope){
  var date = "2017-12-07 14:42:38.0611177 +00:00";
  $scope.createdAt = new Date(date).valueOf();
}]);
</code>```

And use it in your view:

```<code><span>{{createdAt |  date : "MMM d, y"}}</span>
</code>```

Top example will output: Dec 7, 2017

Plunker Demo

For more informations, refer to AngularJS documentation concerning [date filter].2

Body:
You have to convert your date as a timestamp before filter it.

Aleksey remark is a good point, you can get timestamp from controller:

angular.module('app').controller('dateCtrl', ['$scope', function($scope){
  var date = "2017-12-07 14:42:38.0611177 +00:00";
  $scope.createdAt = new Date(date).valueOf();
}]);

And use it in your view:

<span>{{createdAt |  date : "MMM d, y"}}</span>

Top example will output: Dec 7, 2017

Plunker Demo

For more informations, refer to AngularJS documentation concerning [date filter].2


问:
reset selectizeInputs each time I modify a numericInput in RShiny
I'm learning shiny and working with a numericInput connected to many selectizeInputs.

if the numeric input equals to 1 or 2, I would like to create respectively 1 and 2  selectizeInputs and select the "i"th modality of a vector called "modalities" for each selectizeInput EDIT : and that choices = modalities[i] only (and not modalities)

if the numeric input equals to 3 or 4, I would like to create respectively 3 and 4  selectizeInputs which are connected with each other (with choices = modalities). In other words : if an item is selected in one of the selectizeinputs i would like that it disappears from the other selectizeinputs' choices.

In addition (and this is what I have trouble with) I would like to "reset" all the selected SelectizeInputs each time I modify the numericInput. I tried with the observeEvent below and I tried to use an isolate(input$ui_number) but I did not find any solution to my question because i don't understand how to do it... !

Thank you for your help !

```<code>      library(shiny)

      modalities <- LETTERS[1:10]

      ui = tabPanel("Change modalities",
                    numericInput("ui_number", label = "Number of modalities",
                                 min = 1, max = 4, value = 3),
                    uiOutput("renderui")
      )

      server = function(input, output, session) {

        # Generate modalities select lists
        output$renderui <- renderUI({
          output = tagList()
          for (i in seq_len(input$ui_number)) {
            output[[i]] = selectizeInput(paste0("ui_mod_choose", i),
                                         label = paste0("Modality ", i),
                                         choices = modalities, multiple = TRUE)
          }
          return(output)
        })

        # if input$ui_number is modified to 3 or 4 : set selected to NULL ##### NOT WORKING
        observeEvent({input$ui_number},
                     {
                       n <- input$ui_number
                       if(n%in%c(3,4)){
                         for (i in seq_len(n)) {
                           updateSelectizeInput(session, paste0("ui_mod_choose",i),selected=NULL)
                         }
                       }

                     }

        )

        observe({

          n <- input$ui_number

          if(n%in%c(1,2)){ #if n=1 or 2 =>  Select the "i"th modality for each selectizeInput
            for (i in seq_len(n)) {
              updateSelectizeInput(session, paste0("ui_mod_choose",i),
                                   choices = modalities[i],
                                   selected = modalities[i]
              )
            }

          } else{   # if n=3 or 4 => Remove selected modalities from other select lists
            for (i in seq_len(n)) {
              vecteur <- unlist(lapply((1:n)[-i], function(i)
                input[[paste0("ui_mod_choose",i)]]))
              updateSelectizeInput(session, paste0("ui_mod_choose",i),
                                   choices = setdiff(modalities, vecteur),
                                   selected = input[[paste0("ui_mod_choose",i)]])
            }

          }

        })

      }

      runApp(shinyApp(ui, server))
</code>```

This issue corresponds to the following of this one :

lapply function using a numericInput parameter around an observeEvent in RShiny

EDIT2 : new try thanks to @Aurèle 's tip.
The only problem which remains is the 1:100 in lapply which can take time to load (did not find a solution to add a reactive content such as 1:input&ui_number around a conditional panel)

```<code>      library(shiny)

      modalities <- LETTERS[1:10]

      make_conditional_selectizeInputs <- function() {
        do.call(
          div,
          lapply(1:100, function(i)
            conditionalPanel(
              condition = sprintf("%d <= input.ui_number", i),
              selectizeInput(sprintf("ui_mod_choose%d", i),
                             label = sprintf("Modality %d", i),
                             choices = character(0), multiple = TRUE, selected = NULL)
            )
          )
        )
      }

      ui <- tabPanel(
        "Change modalities",
        uiOutput("rendernumeric"),
        #numericInput("ui_number", label = "Number of modalities", min = 1L, max = max, value = 1L),
        make_conditional_selectizeInputs()
      )

      server <- function(input, output, session) {

        max <- 4

        output$rendernumeric <- renderUI({
          numericInput("ui_number", label = "Number of modalities", min = 1L, max = max, value = 1L)
        })

        n <- reactive({
          n <- input$ui_number
          if (is.null(n) || is.na(n) || !n >= 0) 0 else n
        })

        # Reset all
        observeEvent(
          eventExpr = n(),
          handlerExpr = for (i in seq_len(max))
            updateSelectizeInput(
              session, sprintf("ui_mod_choose%d", i),
              choices = if (n() %in% 1:2 && i <= n()) modalities[i] else modalities,
              selected = if (n() %in% 1:2 && i <= n()) modalities[i] else NULL
            )
        )

        all_selected <- reactive({
          unlist(lapply(seq_len(max), function(i)
            input[[sprintf("ui_mod_choose%d", i)]]))
        })

        # Update available modalities
        observeEvent(
          eventExpr = all_selected(),
          handlerExpr = if (!n() %in% 1:2) for (i in seq_len(n())) {
            x <- input[[sprintf("ui_mod_choose%d", i)]]
            other_selected <- setdiff(all_selected(), x)
            updateSelectizeInput(session, sprintf("ui_mod_choose%d", i),
                                 choices = setdiff(modalities, other_selected),
                                 selected = x)
          }
        )

      }

      runApp(shinyApp(ui, server))
</code>```

答:
(This is different enough to be a separate answer).

In https://shiny.rstudio.com/articles/dynamic-ui.html, four different approaches to a dynamic UI in Shiny are suggested, ordered by difficulty:

The conditionalPanel function, which is used in ui.R and wraps a set of UI elements that need to be dynamically shown/hidden.

The renderUI function, which is used in server.R in conjunction with the uiOutput function in ui.R, lets you generate calls to UI functions and make the results appear in a predetermined place in the UI.

The insertUI and removeUI functions, which are used in server.R and allow you to add and remove arbitrary chunks of UI code (all independent from one another), as many times as you want, whenever you want, wherever you want.

Use JavaScript to modify the webpage

Your attempts use the second approach, this answer uses the first one (though it should be doable with any of them):

```<code>library(shiny)

modalities <- LETTERS[1:10]
max <- 4L
</code>```

First, a helper function to build the UI. The number of selectizeInputs is no longer dynamic but fixed to max, and they're alternatively shown/hidden based on input$ui_number:

```<code>make_conditional_selectizeInputs <- function(max) {
  do.call(
    div,
    lapply(seq_len(max), function(i)
      conditionalPanel(
        condition = sprintf("%d <= input.ui_number", i),
        selectizeInput(sprintf("ui_mod_choose%d", i),
                       label = sprintf("Modality %d", i),
                       choices = character(0), multiple = TRUE, selected = NULL)
      )
    )
  )
}

ui <- tabPanel(
  "Change modalities",
  numericInput("ui_number", label = "Number of modalities",
               min = 1L, max = max, value = 1L),
  make_conditional_selectizeInputs(max)
)
</code>```

The server function has two reactive expressions that help modularize code but are not essential to its logic (n() and all_expected()).

There is no longer a renderUI() (the selectizeInputs are already generated once and for all).

There is an observeEvent() that takes a dependency on input$ui_number and resets all selections and choices when it changes.

The last observeEvent() takes a dependency on all input$ui_mod_choose[i] and updates all the choices whenever there is a new selection.

```<code>server <- function(input, output, session) {

  n <- reactive({
    n <- input$ui_number
    if (is.null(n) || is.na(n) || !n >= 0) 0 else n
  })

  # Reset all
  observeEvent(
    eventExpr = n(),
    handlerExpr = for (i in seq_len(max))
      updateSelectizeInput(
        session, sprintf("ui_mod_choose%d", i),
        choices = if (n() %in% 1:2 && i <= n()) modalities[i] else modalities,
        selected = if (n() %in% 1:2 && i <= n()) modalities[i] else NULL
      )
  )

  all_selected <- reactive({
    unlist(lapply(seq_len(max), function(i)
      input[[sprintf("ui_mod_choose%d", i)]]))
  })

  # Update available modalities
  observeEvent(
    eventExpr = all_selected(),
    handlerExpr = if (!n() %in% 1:2) for (i in seq_len(n())) {
      x <- input[[sprintf("ui_mod_choose%d", i)]]
      other_selected <- setdiff(all_selected(), x)
      updateSelectizeInput(session, sprintf("ui_mod_choose%d", i),
                           choices = setdiff(modalities, other_selected),
                           selected = x)
    }
  )

}
</code>```

Essentially it differs from the second approach (with renderUI) in that it removes part of the dependency between input$ui_number and the input$ui_mod_choose[i], at least when they're generated (but there's a residual dependency when they're reset because of updateSelectizeInput. I'm not completely clear why I could make it work with this approach and not with renderUI though).

```<code>runApp(shinyApp(ui, server))
</code>```

This is a screenshot of the reactlog, though it doesn't show the whole picture, because of the necessary impurity of updateSelectizeInput() that mixes the UI and server logics, and creates circular dependencies that can be tricky to reason about:

Body:
I'm learning shiny and working with a numericInput connected to many selectizeInputs.

if the numeric input equals to 1 or 2, I would like to create respectively 1 and 2  selectizeInputs and select the "i"th modality of a vector called "modalities" for each selectizeInput EDIT : and that choices = modalities[i] only (and not modalities)

if the numeric input equals to 3 or 4, I would like to create respectively 3 and 4  selectizeInputs which are connected with each other (with choices = modalities). In other words : if an item is selected in one of the selectizeinputs i would like that it disappears from the other selectizeinputs' choices.

In addition (and this is what I have trouble with) I would like to "reset" all the selected SelectizeInputs each time I modify the numericInput. I tried with the observeEvent below and I tried to use an isolate(input$ui_number) but I did not find any solution to my question because i don't understand how to do it... !

Thank you for your help !

      library(shiny)

      modalities <- LETTERS[1:10]

      ui = tabPanel("Change modalities",
                    numericInput("ui_number", label = "Number of modalities",
                                 min = 1, max = 4, value = 3),
                    uiOutput("renderui")
      )

      server = function(input, output, session) {

        # Generate modalities select lists
        output$renderui <- renderUI({
          output = tagList()
          for (i in seq_len(input$ui_number)) {
            output[[i]] = selectizeInput(paste0("ui_mod_choose", i),
                                         label = paste0("Modality ", i),
                                         choices = modalities, multiple = TRUE)
          }
          return(output)
        })

        # if input$ui_number is modified to 3 or 4 : set selected to NULL ##### NOT WORKING
        observeEvent({input$ui_number},
                     {
                       n <- input$ui_number
                       if(n%in%c(3,4)){
                         for (i in seq_len(n)) {
                           updateSelectizeInput(session, paste0("ui_mod_choose",i),selected=NULL)
                         }
                       }

                     }

        )

        observe({

          n <- input$ui_number

          if(n%in%c(1,2)){ #if n=1 or 2 =>  Select the "i"th modality for each selectizeInput
            for (i in seq_len(n)) {
              updateSelectizeInput(session, paste0("ui_mod_choose",i),
                                   choices = modalities[i],
                                   selected = modalities[i]
              )
            }

          } else{   # if n=3 or 4 => Remove selected modalities from other select lists
            for (i in seq_len(n)) {
              vecteur <- unlist(lapply((1:n)[-i], function(i)
                input[[paste0("ui_mod_choose",i)]]))
              updateSelectizeInput(session, paste0("ui_mod_choose",i),
                                   choices = setdiff(modalities, vecteur),
                                   selected = input[[paste0("ui_mod_choose",i)]])
            }

          }

        })

      }

      runApp(shinyApp(ui, server))

This issue corresponds to the following of this one :

lapply function using a numericInput parameter around an observeEvent in RShiny

EDIT2 : new try thanks to @Aurèle 's tip.
The only problem which remains is the 1:100 in lapply which can take time to load (did not find a solution to add a reactive content such as 1:input&ui_number around a conditional panel)

      library(shiny)

      modalities <- LETTERS[1:10]

      make_conditional_selectizeInputs <- function() {
        do.call(
          div,
          lapply(1:100, function(i)
            conditionalPanel(
              condition = sprintf("%d <= input.ui_number", i),
              selectizeInput(sprintf("ui_mod_choose%d", i),
                             label = sprintf("Modality %d", i),
                             choices = character(0), multiple = TRUE, selected = NULL)
            )
          )
        )
      }

      ui <- tabPanel(
        "Change modalities",
        uiOutput("rendernumeric"),
        #numericInput("ui_number", label = "Number of modalities", min = 1L, max = max, value = 1L),
        make_conditional_selectizeInputs()
      )

      server <- function(input, output, session) {

        max <- 4

        output$rendernumeric <- renderUI({
          numericInput("ui_number", label = "Number of modalities", min = 1L, max = max, value = 1L)
        })

        n <- reactive({
          n <- input$ui_number
          if (is.null(n) || is.na(n) || !n >= 0) 0 else n
        })

        # Reset all
        observeEvent(
          eventExpr = n(),
          handlerExpr = for (i in seq_len(max))
            updateSelectizeInput(
              session, sprintf("ui_mod_choose%d", i),
              choices = if (n() %in% 1:2 && i <= n()) modalities[i] else modalities,
              selected = if (n() %in% 1:2 && i <= n()) modalities[i] else NULL
            )
        )

        all_selected <- reactive({
          unlist(lapply(seq_len(max), function(i)
            input[[sprintf("ui_mod_choose%d", i)]]))
        })

        # Update available modalities
        observeEvent(
          eventExpr = all_selected(),
          handlerExpr = if (!n() %in% 1:2) for (i in seq_len(n())) {
            x <- input[[sprintf("ui_mod_choose%d", i)]]
            other_selected <- setdiff(all_selected(), x)
            updateSelectizeInput(session, sprintf("ui_mod_choose%d", i),
                                 choices = setdiff(modalities, other_selected),
                                 selected = x)
          }
        )

      }

      runApp(shinyApp(ui, server))

Body:
(This is different enough to be a separate answer).

In https://shiny.rstudio.com/articles/dynamic-ui.html, four different approaches to a dynamic UI in Shiny are suggested, ordered by difficulty:

The conditionalPanel function, which is used in ui.R and wraps a set of UI elements that need to be dynamically shown/hidden.

The renderUI function, which is used in server.R in conjunction with the uiOutput function in ui.R, lets you generate calls to UI functions and make the results appear in a predetermined place in the UI.

The insertUI and removeUI functions, which are used in server.R and allow you to add and remove arbitrary chunks of UI code (all independent from one another), as many times as you want, whenever you want, wherever you want.

Use JavaScript to modify the webpage

Your attempts use the second approach, this answer uses the first one (though it should be doable with any of them):

library(shiny)

modalities <- LETTERS[1:10]
max <- 4L

First, a helper function to build the UI. The number of selectizeInputs is no longer dynamic but fixed to max, and they're alternatively shown/hidden based on input$ui_number:

make_conditional_selectizeInputs <- function(max) {
  do.call(
    div,
    lapply(seq_len(max), function(i)
      conditionalPanel(
        condition = sprintf("%d <= input.ui_number", i),
        selectizeInput(sprintf("ui_mod_choose%d", i),
                       label = sprintf("Modality %d", i),
                       choices = character(0), multiple = TRUE, selected = NULL)
      )
    )
  )
}

ui <- tabPanel(
  "Change modalities",
  numericInput("ui_number", label = "Number of modalities",
               min = 1L, max = max, value = 1L),
  make_conditional_selectizeInputs(max)
)

The server function has two reactive expressions that help modularize code but are not essential to its logic (n() and all_expected()).

There is no longer a renderUI() (the selectizeInputs are already generated once and for all).

There is an observeEvent() that takes a dependency on input$ui_number and resets all selections and choices when it changes.

The last observeEvent() takes a dependency on all input$ui_mod_choose[i] and updates all the choices whenever there is a new selection.

server <- function(input, output, session) {

  n <- reactive({
    n <- input$ui_number
    if (is.null(n) || is.na(n) || !n >= 0) 0 else n
  })

  # Reset all
  observeEvent(
    eventExpr = n(),
    handlerExpr = for (i in seq_len(max))
      updateSelectizeInput(
        session, sprintf("ui_mod_choose%d", i),
        choices = if (n() %in% 1:2 && i <= n()) modalities[i] else modalities,
        selected = if (n() %in% 1:2 && i <= n()) modalities[i] else NULL
      )
  )

  all_selected <- reactive({
    unlist(lapply(seq_len(max), function(i)
      input[[sprintf("ui_mod_choose%d", i)]]))
  })

  # Update available modalities
  observeEvent(
    eventExpr = all_selected(),
    handlerExpr = if (!n() %in% 1:2) for (i in seq_len(n())) {
      x <- input[[sprintf("ui_mod_choose%d", i)]]
      other_selected <- setdiff(all_selected(), x)
      updateSelectizeInput(session, sprintf("ui_mod_choose%d", i),
                           choices = setdiff(modalities, other_selected),
                           selected = x)
    }
  )

}

Essentially it differs from the second approach (with renderUI) in that it removes part of the dependency between input$ui_number and the input$ui_mod_choose[i], at least when they're generated (but there's a residual dependency when they're reset because of updateSelectizeInput. I'm not completely clear why I could make it work with this approach and not with renderUI though).

runApp(shinyApp(ui, server))

This is a screenshot of the reactlog, though it doesn't show the whole picture, because of the necessary impurity of updateSelectizeInput() that mixes the UI and server logics, and creates circular dependencies that can be tricky to reason about:


问:
Can iOS Frameworks Be Shared Without Sharing the Source Code?
When Xcode is used to build an iOS framework, the end result is a package on the disk similar to the following:

Is it possible for me to give that package to another developer and have him/her include it in their own Xcode projects?

[I am having trouble doing that. Hence this question. The lack of an answer lead me to distill it to its essence and post a new, simpler question.]

答:
So, the answer to my question is a definite Yes. I now know this because Carthage can do it. Upon remembering that Carthage does exactly what I am trying to do, I used Carthage to build my framework and Voila! - I can drag/drop the Carthage build of my framework into an Xcode project and successfully use it. So now my inquiry has become: What does Carthage know that I do not?

Update

Mystery solved! The framework and application architectures were mismatched. See this question for a bit more info.


问:
C - Matrix Main and Anti Diagonals (Replace)
I have a task and i need help from pros.

My task is: User inputs number of rows and columns for matrix[8][8], with some prohibitions using IF. Later user enters all the elements for this matrix, using loops and outputting this matrix.

Here is the code :

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

int main ()
{
    int matrix[10][10];
    int nrows, ncols, i, j;

    printf("Enter number of rows: "); //user enters number of rows
    scanf("%d", &nrows);
    if(nrows < 4){
        printf("\n Out of range, please try again");
        exit(5);
    }
    printf("Enter number of columns: "); //user enters number of columns
    scanf("%d", &ncols);
    if(ncols < 4){
        printf("\n Out of range, please try again");
        exit(5);
    }
    printf("Enter matrix elements: "); //user enters all the elements for Matrix

    for(i = 0; i < nrows; i++){
        for(j = 0; j < ncols; j++){
            scanf("%d",&matrix[i][j]);
    }

    printf("\n");
}
    printf("This is your matrix: \n");
    for(i = 0; i < nrows; i++){
        for(j = 0; j < ncols; j++){
            printf("%d \t",matrix[i][j]);}

    printf("\n");}

    return 0;
}
</code>```

Now i need to add one thing, i want to take diagonal and anti-diagonal of this matrix and replace all the elements there with capital X.
As i don't know, what kind of matrix it will be, like it can be matrix[4][6] or matrix[7][4], so i need to do something that will work with any kind of matrix that user can enter in this program.

Example of this task (In this program i can't enter less than [4][4], but for the example i'll do it):

```<code>User enters rows - 3
User enters columns - 3
User enters elements : 1 2 3 4 5 6 7 8 9
Output :

    1 2 3
    4 5 6
    7 8 9
</code>```

Here i need to do something like this :

```<code>X 2 X
4 X 6
X 8 X
</code>```

If user enters not square matrix, for example:

```<code>User enters rows: 3
User enters rows: 4
User enters elements: 1 2 3 4 5 6 7 8 9

Out matrix:

1 2 3 4
5 6 7 8
9 0 1 2

After replacing with X:

X 2 3 X
5 X X 8
9 X X 2
</code>```

Replaced diagonal and anti-diagonal with capital Xs.

Please any help ?

答:
Complete code and its working on both of the examples you provided in your quesetion, just tell me if anything missing here</p>

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

int main ()
{
    int matrix[10][10];
    int nrows, ncols, i, j;

    printf("Enter number of rows: "); //user enters number of rows
    scanf("%d", &nrows);
    if(nrows < 4){
        printf("\n Out of range, please try again");
        exit(5);
    }
    printf("Enter number of columns: "); //user enters number of columns
    scanf("%d", &ncols);
    if(ncols < 4){
        printf("\n Out of range, please try again");
        exit(5);
    }
    printf("Enter matrix elements: "); //user enters all the elements for Matrix

    for(i = 0; i < nrows; i++){
        for(j = 0; j < ncols; j++){
            scanf("%d",&matrix[i][j]);
    }

    printf("\n");
}
    printf("This is your matrix: \n");
    for(i = 0; i < nrows; i++){
        for(j = 0; j < ncols; j++){
            printf("%d \t",matrix[i][j]);}

    printf("\n");}
//When square matrix
    if(nrows==ncols)
    {
        for(i = 0; i < nrows; i++){
           matrix[i][i]='X';
            }
            int count=0;
            for(i=nrows-1;i>=0;i--)
            {
                matrix[count][i]='X';
                count++;

            }
 for(i = 0; i < nrows; i++){
        for(j = 0; j < ncols; j++){
                if(i==j||(i+j==nrows-1))
            printf("%c \t",matrix[i][j]);
        else
                        printf("%d \t",matrix[i][j]);

            }

    printf("\n");}
    }
else
{
    if(nrows<ncols)
    {
        int count=ncols-1;
        for(i = 0; i < nrows; i++){
           matrix[i][i]='X';
            }
            for(i = 0; i < nrows; i++){
           matrix[i][count]='X';
           count--;
            }
          for(i = 0; i < nrows; i++){
        for(j = 0; j < ncols; j++){
                if(i==j||(i+j==nrows))
                printf("%c \t",matrix[i][j]);
        else
                                    printf("%d \t",matrix[i][j]);

            }

    printf("\n");}
    }

}

    return 0;
}
</code>```

Body:
I have a task and i need help from pros.

My task is: User inputs number of rows and columns for matrix[8][8], with some prohibitions using IF. Later user enters all the elements for this matrix, using loops and outputting this matrix.

Here is the code :

#include <stdio.h>

int main ()
{
    int matrix[10][10];
    int nrows, ncols, i, j;

    printf("Enter number of rows: "); //user enters number of rows
    scanf("%d", &nrows);
    if(nrows < 4){
        printf("\n Out of range, please try again");
        exit(5);
    }
    printf("Enter number of columns: "); //user enters number of columns
    scanf("%d", &ncols);
    if(ncols < 4){
        printf("\n Out of range, please try again");
        exit(5);
    }
    printf("Enter matrix elements: "); //user enters all the elements for Matrix

    for(i = 0; i < nrows; i++){
        for(j = 0; j < ncols; j++){
            scanf("%d",&matrix[i][j]);
    }

    printf("\n");
}
    printf("This is your matrix: \n");
    for(i = 0; i < nrows; i++){
        for(j = 0; j < ncols; j++){
            printf("%d \t",matrix[i][j]);}

    printf("\n");}

    return 0;
}

Now i need to add one thing, i want to take diagonal and anti-diagonal of this matrix and replace all the elements there with capital X.
As i don't know, what kind of matrix it will be, like it can be matrix[4][6] or matrix[7][4], so i need to do something that will work with any kind of matrix that user can enter in this program.

Example of this task (In this program i can't enter less than [4][4], but for the example i'll do it):

User enters rows - 3
User enters columns - 3
User enters elements : 1 2 3 4 5 6 7 8 9
Output :

    1 2 3
    4 5 6
    7 8 9

Here i need to do something like this :

X 2 X
4 X 6
X 8 X

If user enters not square matrix, for example:

User enters rows: 3
User enters rows: 4
User enters elements: 1 2 3 4 5 6 7 8 9

Out matrix:

1 2 3 4
5 6 7 8
9 0 1 2

After replacing with X:

X 2 3 X
5 X X 8
9 X X 2

Replaced diagonal and anti-diagonal with capital Xs.

Please any help ?

Body:
Complete code and its working on both of the examples you provided in your quesetion, just tell me if anything missing here

#include <stdio.h>

int main ()
{
    int matrix[10][10];
    int nrows, ncols, i, j;

    printf("Enter number of rows: "); //user enters number of rows
    scanf("%d", &nrows);
    if(nrows < 4){
        printf("\n Out of range, please try again");
        exit(5);
    }
    printf("Enter number of columns: "); //user enters number of columns
    scanf("%d", &ncols);
    if(ncols < 4){
        printf("\n Out of range, please try again");
        exit(5);
    }
    printf("Enter matrix elements: "); //user enters all the elements for Matrix

    for(i = 0; i < nrows; i++){
        for(j = 0; j < ncols; j++){
            scanf("%d",&matrix[i][j]);
    }

    printf("\n");
}
    printf("This is your matrix: \n");
    for(i = 0; i < nrows; i++){
        for(j = 0; j < ncols; j++){
            printf("%d \t",matrix[i][j]);}

    printf("\n");}
//When square matrix
    if(nrows==ncols)
    {
        for(i = 0; i < nrows; i++){
           matrix[i][i]='X';
            }
            int count=0;
            for(i=nrows-1;i>=0;i--)
            {
                matrix[count][i]='X';
                count++;

            }
 for(i = 0; i < nrows; i++){
        for(j = 0; j < ncols; j++){
                if(i==j||(i+j==nrows-1))
            printf("%c \t",matrix[i][j]);
        else
                        printf("%d \t",matrix[i][j]);

            }

    printf("\n");}
    }
else
{
    if(nrows<ncols)
    {
        int count=ncols-1;
        for(i = 0; i < nrows; i++){
           matrix[i][i]='X';
            }
            for(i = 0; i < nrows; i++){
           matrix[i][count]='X';
           count--;
            }
          for(i = 0; i < nrows; i++){
        for(j = 0; j < ncols; j++){
                if(i==j||(i+j==nrows))
                printf("%c \t",matrix[i][j]);
        else
                                    printf("%d \t",matrix[i][j]);

            }

    printf("\n");}
    }

}

    return 0;
}


问:
android - ndk not copy prebuild library to my apk
I can build hello-libs google example code and the prebuild library has been copied to target apk correctly.

But in my app, compile has passed but apk DO not include the prebuild libraries.

Two issues:

The build output apk lib directory only contains arm64 version, but I have defined armeabi,armeabi-v7a and arm64 in build.gradle. not sure why it doesn't take effect.

    lib/
    └── arm64-v8a
        └── libFFmpegWrapper.so

The prebuild libraries not been included in apk lib directory at all, but I have the jniLibs line in my build.gradle, I checked hell-libs, it looks like the same.

Detail information as below:

Android studio version: 3.0.1
OS: macosx 10.13.1

My file directory structure as below:

```<code>├── app
│   ├── libs
│   └── src
│       ├── main
│       │   ├── cpp
│       │   │   └── ffmpeg
│       │   │       ├── arm64-v8a
│       │   │       │   ├── bin
│       │   │       │   ├── include
│       │   │       │   ├── lib
│       │   │       ├── armeabi
│       │   │       │   ├── include
│       │   │       │   ├── lib
│       │   │       └── armeabi-v7a
│       │   │           ├── include
│       │   │           ├── lib
│       │   ├── java
│       │   │   └── com
│       │   │       └── example
│       │   │           └── ffmpegtest
│       │   │               └── recorder
</code>```

build.gradle

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.example.ffmpegtest"
        minSdkVersion 23
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        ndk {
            abiFilters 'armeabi', 'armeabi-v7a', 'arm64-v8a'
        }
        externalNativeBuild {
            cmake {
                cmake {
                    arguments '-DANDROID_PLATFORM=android-26',
                            '-DANDROID_TOOLCHAIN=clang', '-DANDROID_STL=gnustl_static'
                }
            }
        }
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    sourceSets {
        main {
            // let gradle pack the shared library into apk
            jniLibs.srcDirs = ['src/main/cpp/ffmpeg']
        }
    }
    externalNativeBuild {
        cmake {
            path "CMakeLists.txt"
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}
</code>```

CMakeList.txt

```<code>cmake_minimum_required(VERSION 3.4.1)

set(FFMPEG_DIR ${CMAKE_SOURCE_DIR}/src/main/cpp/ffmpeg)

add_library(avutil-55 SHARED IMPORTED)
set_target_properties(avutil-55
    PROPERTIES IMPORTED_LOCATION
    ${FFMPEG_DIR}/${ANDROID_ABI}/lib/libavutil-55.so)

add_library(avformat-57 SHARED IMPORTED)
set_target_properties(avformat-57
    PROPERTIES IMPORTED_LOCATION
    ${FFMPEG_DIR}/${ANDROID_ABI}/lib/libavformat-57.so)

add_library(avcodec-57 SHARED IMPORTED)
set_target_properties(avcodec-57
    PROPERTIES IMPORTED_LOCATION
    ${FFMPEG_DIR}/${ANDROID_ABI}/lib/libavcodec-57.so)

add_library(avfilter-6 SHARED IMPORTED)
set_target_properties(avfilter-6
    PROPERTIES IMPORTED_LOCATION
    ${FFMPEG_DIR}/${ANDROID_ABI}/lib/libavfilter-6.so)

add_library(swresample-2 SHARED IMPORTED)
set_target_properties(swresample-2
    PROPERTIES IMPORTED_LOCATION
    ${FFMPEG_DIR}/${ANDROID_ABI}/lib/libswresample-2.so)

add_library(swscale-4 SHARED IMPORTED)
set_target_properties(swscale-4
    PROPERTIES IMPORTED_LOCATION
    ${FFMPEG_DIR}/${ANDROID_ABI}/lib/libswscale-4.so)

set(FFMPEG_LIBS
    avutil-55
    avformat-57
    avcodec-57
    avfilter-6
    swresample-2
    swscale-4)

include_directories(${FFMPEG_DIR}/${ANDROID_ABI}/include)

set(CMAKE_C_FLAGS "${CMAKE_CXX_FLAGS} -mfloat-abi=softfp -mfpu=neon -g -O0")

add_library( # Sets the name of the library.
             FFmpegWrapper

             # Sets the library as a shared library.
             SHARED

             # Provides a relative path to your source file(s).
             src/main/cpp/FFmpegWrapper.c
             )

find_library( # Sets the name of the path variable.
              log-lib

              # Specifies the name of the NDK library that
              # you want CMake to locate.
              log
              )

target_link_libraries( # Specifies the target library.

                       FFmpegWrapper

                       # Links the target library to the log library
                       # included in the NDK.
                       ${log-lib}

                        # ffmpeg library
                        ${FFMPEG_LIBS}
                       )
</code>```

答:
The share library directory structure should be changed as below:

```<code>src/main/cpp/
└── ffmpeg
    ├── include
    └── lib
        ├── arm64-v8a
        ├── armeabi
        └── armeabi-v7a
</code>```

And change the other code line to right location. The CMakeList.txt maybe looks like below:

```<code>cmake_minimum_required(VERSION 3.4.1)

set(FFMPEG_DIR ${CMAKE_SOURCE_DIR}/src/main/cpp/ffmpeg)

# library directory structure
# src/main/cpp/
# └── ffmpeg
#     ├── include
#     └── lib
#         ├── arm64-v8a
#         ├── armeabi
#         └── armeabi-v7a
include_directories(${FFMPEG_DIR}/include)
set(FFMPEG_LIBS
    avutil-55
    avformat-57
    avcodec-57
    avfilter-6
    swresample-2
    swscale-4)

foreach(libname ${FFMPEG_LIBS})
    message(add lib ${libname})
    add_library(${libname} SHARED IMPORTED)
    set_target_properties(${libname} PROPERTIES IMPORTED_LOCATION
        ${FFMPEG_DIR}/lib/${ANDROID_ABI}/lib${libname}.so)
endforeach()

set(CMAKE_C_FLAGS "${CMAKE_CXX_FLAGS} -mfloat-abi=softfp -mfpu=neon -g -O0")
add_library(FFmpegWrapper SHARED src/main/cpp/FFmpegWrapper.c)
find_library(log-lib log)
target_link_libraries(FFmpegWrapper ${log-lib} ${FFMPEG_LIBS})
</code>```

The build.gradle:

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        ...
        ndk {
            abiFilters 'armeabi', 'armeabi-v7a', 'arm64-v8a'
        }
        ...
    }
    ...
    sourceSets {
        main {
            // let gradle pack the shared library into apk
            jniLibs.srcDirs = ['src/main/cpp/ffmpeg/lib']
        }
    }
    externalNativeBuild {
        cmake {
            path "CMakeLists.txt"
        }
    }
}

dependencies {
   ...
}
</code>```

Body:
I can build hello-libs google example code and the prebuild library has been copied to target apk correctly.

But in my app, compile has passed but apk DO not include the prebuild libraries.

Two issues:

The build output apk lib directory only contains arm64 version, but I have defined armeabi,armeabi-v7a and arm64 in build.gradle. not sure why it doesn't take effect.

    lib/
    └── arm64-v8a
        └── libFFmpegWrapper.so

The prebuild libraries not been included in apk lib directory at all, but I have the jniLibs line in my build.gradle, I checked hell-libs, it looks like the same.

Detail information as below:

Android studio version: 3.0.1
OS: macosx 10.13.1

My file directory structure as below:

├── app
│   ├── libs
│   └── src
│       ├── main
│       │   ├── cpp
│       │   │   └── ffmpeg
│       │   │       ├── arm64-v8a
│       │   │       │   ├── bin
│       │   │       │   ├── include
│       │   │       │   ├── lib
│       │   │       ├── armeabi
│       │   │       │   ├── include
│       │   │       │   ├── lib
│       │   │       └── armeabi-v7a
│       │   │           ├── include
│       │   │           ├── lib
│       │   ├── java
│       │   │   └── com
│       │   │       └── example
│       │   │           └── ffmpegtest
│       │   │               └── recorder

build.gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.example.ffmpegtest"
        minSdkVersion 23
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        ndk {
            abiFilters 'armeabi', 'armeabi-v7a', 'arm64-v8a'
        }
        externalNativeBuild {
            cmake {
                cmake {
                    arguments '-DANDROID_PLATFORM=android-26',
                            '-DANDROID_TOOLCHAIN=clang', '-DANDROID_STL=gnustl_static'
                }
            }
        }
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    sourceSets {
        main {
            // let gradle pack the shared library into apk
            jniLibs.srcDirs = ['src/main/cpp/ffmpeg']
        }
    }
    externalNativeBuild {
        cmake {
            path "CMakeLists.txt"
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}

CMakeList.txt

cmake_minimum_required(VERSION 3.4.1)

set(FFMPEG_DIR ${CMAKE_SOURCE_DIR}/src/main/cpp/ffmpeg)

add_library(avutil-55 SHARED IMPORTED)
set_target_properties(avutil-55
    PROPERTIES IMPORTED_LOCATION
    ${FFMPEG_DIR}/${ANDROID_ABI}/lib/libavutil-55.so)

add_library(avformat-57 SHARED IMPORTED)
set_target_properties(avformat-57
    PROPERTIES IMPORTED_LOCATION
    ${FFMPEG_DIR}/${ANDROID_ABI}/lib/libavformat-57.so)

add_library(avcodec-57 SHARED IMPORTED)
set_target_properties(avcodec-57
    PROPERTIES IMPORTED_LOCATION
    ${FFMPEG_DIR}/${ANDROID_ABI}/lib/libavcodec-57.so)

add_library(avfilter-6 SHARED IMPORTED)
set_target_properties(avfilter-6
    PROPERTIES IMPORTED_LOCATION
    ${FFMPEG_DIR}/${ANDROID_ABI}/lib/libavfilter-6.so)

add_library(swresample-2 SHARED IMPORTED)
set_target_properties(swresample-2
    PROPERTIES IMPORTED_LOCATION
    ${FFMPEG_DIR}/${ANDROID_ABI}/lib/libswresample-2.so)

add_library(swscale-4 SHARED IMPORTED)
set_target_properties(swscale-4
    PROPERTIES IMPORTED_LOCATION
    ${FFMPEG_DIR}/${ANDROID_ABI}/lib/libswscale-4.so)

set(FFMPEG_LIBS
    avutil-55
    avformat-57
    avcodec-57
    avfilter-6
    swresample-2
    swscale-4)

include_directories(${FFMPEG_DIR}/${ANDROID_ABI}/include)

set(CMAKE_C_FLAGS "${CMAKE_CXX_FLAGS} -mfloat-abi=softfp -mfpu=neon -g -O0")

add_library( # Sets the name of the library.
             FFmpegWrapper

             # Sets the library as a shared library.
             SHARED

             # Provides a relative path to your source file(s).
             src/main/cpp/FFmpegWrapper.c
             )

find_library( # Sets the name of the path variable.
              log-lib

              # Specifies the name of the NDK library that
              # you want CMake to locate.
              log
              )

target_link_libraries( # Specifies the target library.

                       FFmpegWrapper

                       # Links the target library to the log library
                       # included in the NDK.
                       ${log-lib}

                        # ffmpeg library
                        ${FFMPEG_LIBS}
                       )

Body:
The share library directory structure should be changed as below:

src/main/cpp/
└── ffmpeg
    ├── include
    └── lib
        ├── arm64-v8a
        ├── armeabi
        └── armeabi-v7a

And change the other code line to right location. The CMakeList.txt maybe looks like below:

cmake_minimum_required(VERSION 3.4.1)

set(FFMPEG_DIR ${CMAKE_SOURCE_DIR}/src/main/cpp/ffmpeg)

# library directory structure
# src/main/cpp/
# └── ffmpeg
#     ├── include
#     └── lib
#         ├── arm64-v8a
#         ├── armeabi
#         └── armeabi-v7a
include_directories(${FFMPEG_DIR}/include)
set(FFMPEG_LIBS
    avutil-55
    avformat-57
    avcodec-57
    avfilter-6
    swresample-2
    swscale-4)

foreach(libname ${FFMPEG_LIBS})
    message(add lib ${libname})
    add_library(${libname} SHARED IMPORTED)
    set_target_properties(${libname} PROPERTIES IMPORTED_LOCATION
        ${FFMPEG_DIR}/lib/${ANDROID_ABI}/lib${libname}.so)
endforeach()

set(CMAKE_C_FLAGS "${CMAKE_CXX_FLAGS} -mfloat-abi=softfp -mfpu=neon -g -O0")
add_library(FFmpegWrapper SHARED src/main/cpp/FFmpegWrapper.c)
find_library(log-lib log)
target_link_libraries(FFmpegWrapper ${log-lib} ${FFMPEG_LIBS})

The build.gradle:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        ...
        ndk {
            abiFilters 'armeabi', 'armeabi-v7a', 'arm64-v8a'
        }
        ...
    }
    ...
    sourceSets {
        main {
            // let gradle pack the shared library into apk
            jniLibs.srcDirs = ['src/main/cpp/ffmpeg/lib']
        }
    }
    externalNativeBuild {
        cmake {
            path "CMakeLists.txt"
        }
    }
}

dependencies {
   ...
}


问:
How can I serve SSH and HTTP(S) traffic from the same listener in Go?
I want to be able to serve both SSH and HTTPS connections on the same port. To do so, I need to examine the first few bytes sent by the client, and if it starts with "SSH", serve the connection one way, but let the Go HTTP server handle it if it isn't SSH.

But the http package will only work with a net.Listener. Once I accept a connection from the listener and examine the first bytes, it's too late to send the net.Conn to http.

How can I accomplish this?

答:
Make two custom listeners, one for SSH connections, and one for all other connections. Then accept connections from the raw listener, peek at the first bytes, and send the connection to the appropriate listener.

```<code>l := net.Listen("tcp", ":443")
sshListener, httpListener := MuxListener(l)
go sshServer.Serve(sshListener)
go httpServer.Serve(httpListener)
</code>```

MuxListener:

```<code>// MuxListener takes a net.Listener and returns two listeners, one that
// accepts connections that start with "SSH", and another that accepts
// all others. This allows SSH and HTTPS to be served from the same port.
func MuxListener(l net.Listener) (ssh net.Listener, other net.Listener) {
    sshListener, otherListener := newListener(l), newListener(l)
    go func() {
        for {
            conn, err := l.Accept()
            if err != nil {
                log.Println("Error accepting conn:", err)
                continue
            }
            conn.SetReadDeadline(time.Now().Add(time.Second * 10))
            bconn := bufferedConn{conn, bufio.NewReaderSize(conn, 3)}
            p, err := bconn.Peek(3)
            conn.SetReadDeadline(time.Time{})
            if err != nil {
                log.Println("Error peeking into conn:", err)
                continue
            }
            prefix := string(p)
            selectedListener := otherListener
            if prefix == "SSH" {
                selectedListener = sshListener
            }
            if selectedListener.accept != nil {
                selectedListener.accept <- bconn
            }
        }
    }()
    return sshListener, otherListener
}
</code>```

listener:

```<code>type listener struct {
    accept chan net.Conn
    net.Listener
}

func newListener(l net.Listener) *listener {
    return &listener{
        make(chan net.Conn),
        l,
    }
}

func (l *listener) Accept() (net.Conn, error) {
    if l.accept == nil {
        return nil, errors.New("Listener closed")
    }
    return <-l.accept, nil
}

func (l *listener) Close() error {
    close(l.accept)
    l.accept = nil
    return nil
}
</code>```

bufferedConn:

```<code>type bufferedConn struct {
    net.Conn
    r *bufio.Reader
}

func (b bufferedConn) Peek(n int) ([]byte, error) {
    return b.r.Peek(n)
}

func (b bufferedConn) Read(p []byte) (int, error) {
    return b.r.Read(p)
}
</code>```

Body:
Make two custom listeners, one for SSH connections, and one for all other connections. Then accept connections from the raw listener, peek at the first bytes, and send the connection to the appropriate listener.

l := net.Listen("tcp", ":443")
sshListener, httpListener := MuxListener(l)
go sshServer.Serve(sshListener)
go httpServer.Serve(httpListener)

MuxListener:

// MuxListener takes a net.Listener and returns two listeners, one that
// accepts connections that start with "SSH", and another that accepts
// all others. This allows SSH and HTTPS to be served from the same port.
func MuxListener(l net.Listener) (ssh net.Listener, other net.Listener) {
    sshListener, otherListener := newListener(l), newListener(l)
    go func() {
        for {
            conn, err := l.Accept()
            if err != nil {
                log.Println("Error accepting conn:", err)
                continue
            }
            conn.SetReadDeadline(time.Now().Add(time.Second * 10))
            bconn := bufferedConn{conn, bufio.NewReaderSize(conn, 3)}
            p, err := bconn.Peek(3)
            conn.SetReadDeadline(time.Time{})
            if err != nil {
                log.Println("Error peeking into conn:", err)
                continue
            }
            prefix := string(p)
            selectedListener := otherListener
            if prefix == "SSH" {
                selectedListener = sshListener
            }
            if selectedListener.accept != nil {
                selectedListener.accept <- bconn
            }
        }
    }()
    return sshListener, otherListener
}

listener:

type listener struct {
    accept chan net.Conn
    net.Listener
}

func newListener(l net.Listener) *listener {
    return &listener{
        make(chan net.Conn),
        l,
    }
}

func (l *listener) Accept() (net.Conn, error) {
    if l.accept == nil {
        return nil, errors.New("Listener closed")
    }
    return <-l.accept, nil
}

func (l *listener) Close() error {
    close(l.accept)
    l.accept = nil
    return nil
}

bufferedConn:

type bufferedConn struct {
    net.Conn
    r *bufio.Reader
}

func (b bufferedConn) Peek(n int) ([]byte, error) {
    return b.r.Peek(n)
}

func (b bufferedConn) Read(p []byte) (int, error) {
    return b.r.Read(p)
}


问:
Why the type cannot be inferred if a parameterless method group is passed to LINQ methods?
Can someone explain me(or show the specification/documentation) why following is not allowed:

```<code>string[] fiveFoos = Enumerable.Range(1, 5).Select(GetFoo).ToArray();
</code>```

...

```<code>static string GetFoo()
{
    return "Foo";
}
</code>```

Only this will compile:

```<code>string[] fiveFoos = Enumerable.Range(1, 5).Select(i => GetFoo()).ToArray();
</code>```

The integer projected from Enumerable.Range is not relevant and the method GetFoo is parameterless and clearly returns String, so why do i get following compiler error anyway:

Error CS0411  The type arguments for method 'Enumerable.Select(IEnumerable, Func)' cannot be
  inferred from the usage. Try specifying the type arguments
  explicitly.

答:
The integer projected from Enumerable.Range is not relevant and the method GetFoo is parameterless and clearly returns String

The difference is exactly that GetFoo method is parameterless, while i => GetFoo() lambda is not. Adding a lambda that ignores its parameters matches the signature of GetFoo() method to the signature of Func<int,T> method expected by Enumerable.Select.

Defining a simple method for making sequences from parameterless generators fixes this problem:

```<code>static class MyEnumerable {
    public static IEnumerable<T> Generate<T>(Func<T> f, int n) {
        while (n > 0) {
            n--;
            yield return f();
        }
    }
}
</code>```

Now you can write

```<code>string[] fiveFoos = MyEnumerable.Generate(GetFoo, 15).ToArray();
</code>```

Demo.

Body:
Can someone explain me(or show the specification/documentation) why following is not allowed:

string[] fiveFoos = Enumerable.Range(1, 5).Select(GetFoo).ToArray();

...

static string GetFoo()
{
    return "Foo";
}

Only this will compile:

string[] fiveFoos = Enumerable.Range(1, 5).Select(i => GetFoo()).ToArray();

The integer projected from Enumerable.Range is not relevant and the method GetFoo is parameterless and clearly returns String, so why do i get following compiler error anyway:

Error CS0411  The type arguments for method 'Enumerable.Select(IEnumerable, Func)' cannot be
  inferred from the usage. Try specifying the type arguments
  explicitly.

Body:
The integer projected from Enumerable.Range is not relevant and the method GetFoo is parameterless and clearly returns String

The difference is exactly that GetFoo method is parameterless, while i => GetFoo() lambda is not. Adding a lambda that ignores its parameters matches the signature of GetFoo() method to the signature of Func<int,T> method expected by Enumerable.Select.

Defining a simple method for making sequences from parameterless generators fixes this problem:

static class MyEnumerable {
    public static IEnumerable<T> Generate<T>(Func<T> f, int n) {
        while (n > 0) {
            n--;
            yield return f();
        }
    }
}

Now you can write

string[] fiveFoos = MyEnumerable.Generate(GetFoo, 15).ToArray();

Demo.


问:
Generating random arrivals via Poisson process c++
There is something I didn't understand. I use the sample given from the cpp reference to generate numbers:

```<code>const int nrolls = 10; // number of experiments

std::default_random_engine generator;
std::poisson_distribution<int> distribution(4.1);

for (int i=0; i<nrolls; ++i){
int number = distribution(generator);
cout<<number<<" "<<endl;
}
</code>```

(original code: http://www.cplusplus.com/reference/random/poisson_distribution/ )

This outputs: 2 3 1 4 3 4 4 3 2 3 and so on...
First of all what those numbers mean? I mean do I have to sum them to create timing? For example:
2, (2+3)=5, (5+1)=6, (6+4)=10,..., and so on..

Secondly, my real question is, I need to produce both random arrivals for network packets and the size of packets. I mean, when the packets come and if packets come, what are the size of packets? How can I do that? I need something like that:
http://i.hizliresim.com/dWmaGX.png

答:
I'm afraid that the way that you generate an arrival times via a Poisson process is not correct. Poisson process is not the Poisson distribution.

Generating arrival times via Poisson Process does not mean using a Poisson distribution as you do in your code. It is done by creating an exponential distribution based on the Poisson arrival rate lamda.

In short, you need to generate an exponential distribution with an average = 1/lamda,  see the following example:

```<code>#include <iostream>
#include <iterator>
#include <random>

int
main ()
{
 // seed the RNG
 std::random_device rd; // uniformly-distributed integer random number generator
 std::mt19937 rng (rd ()); // mt19937: Pseudo-random number generation

 double averageArrival = 15;
 double lamda = 1 / averageArrival;
 std::exponential_distribution<double> exp (lamda);

double sumArrivalTimes=0;
double newArrivalTime;

 for (int i = 0; i < 10; ++i)
  {
   newArrivalTime=  exp.operator() (rng);// generates the next random number in the distribution
   sumArrivalTimes  = sumArrivalTimes + newArrivalTime;
   std::cout << "newArrivalTime:  " << newArrivalTime  << "    ,sumArrivalTimes:  " << sumArrivalTimes << std::endl;
  }

}
</code>```

The result of running this code:

```<code>newArrivalTime:  21.6419    ,sumArrivalTimes:  21.6419
newArrivalTime:  1.64205    ,sumArrivalTimes:  23.2839
newArrivalTime:  8.35292    ,sumArrivalTimes:  31.6368
newArrivalTime:  1.82962    ,sumArrivalTimes:  33.4665
newArrivalTime:  34.7628    ,sumArrivalTimes:  68.2292
newArrivalTime:  26.0752    ,sumArrivalTimes:  94.3045
newArrivalTime:  63.4728    ,sumArrivalTimes:  157.777
newArrivalTime:  3.22149    ,sumArrivalTimes:  160.999
newArrivalTime:  1.64637    ,sumArrivalTimes:  162.645
newArrivalTime:  13.8235    ,sumArrivalTimes:  176.469
</code>```

so, based on your experiment you can either use: newArrivalTime or  sumArrivalTimes.

ref:  http://www.math.wsu.edu/faculty/genz/416/lect/l05-45.pdf

Body:
There is something I didn't understand. I use the sample given from the cpp reference to generate numbers:

const int nrolls = 10; // number of experiments

std::default_random_engine generator;
std::poisson_distribution<int> distribution(4.1);

for (int i=0; i<nrolls; ++i){
int number = distribution(generator);
cout<<number<<" "<<endl;
}

(original code: http://www.cplusplus.com/reference/random/poisson_distribution/ )

This outputs: 2 3 1 4 3 4 4 3 2 3 and so on...
First of all what those numbers mean? I mean do I have to sum them to create timing? For example:
2, (2+3)=5, (5+1)=6, (6+4)=10,..., and so on..

Secondly, my real question is, I need to produce both random arrivals for network packets and the size of packets. I mean, when the packets come and if packets come, what are the size of packets? How can I do that? I need something like that:
http://i.hizliresim.com/dWmaGX.png

Body:
I'm afraid that the way that you generate an arrival times via a Poisson process is not correct. Poisson process is not the Poisson distribution.

Generating arrival times via Poisson Process does not mean using a Poisson distribution as you do in your code. It is done by creating an exponential distribution based on the Poisson arrival rate lamda.

In short, you need to generate an exponential distribution with an average = 1/lamda,  see the following example:

#include <iostream>
#include <iterator>
#include <random>

int
main ()
{
 // seed the RNG
 std::random_device rd; // uniformly-distributed integer random number generator
 std::mt19937 rng (rd ()); // mt19937: Pseudo-random number generation

 double averageArrival = 15;
 double lamda = 1 / averageArrival;
 std::exponential_distribution<double> exp (lamda);

double sumArrivalTimes=0;
double newArrivalTime;

 for (int i = 0; i < 10; ++i)
  {
   newArrivalTime=  exp.operator() (rng);// generates the next random number in the distribution
   sumArrivalTimes  = sumArrivalTimes + newArrivalTime;
   std::cout << "newArrivalTime:  " << newArrivalTime  << "    ,sumArrivalTimes:  " << sumArrivalTimes << std::endl;
  }

}

The result of running this code:

newArrivalTime:  21.6419    ,sumArrivalTimes:  21.6419
newArrivalTime:  1.64205    ,sumArrivalTimes:  23.2839
newArrivalTime:  8.35292    ,sumArrivalTimes:  31.6368
newArrivalTime:  1.82962    ,sumArrivalTimes:  33.4665
newArrivalTime:  34.7628    ,sumArrivalTimes:  68.2292
newArrivalTime:  26.0752    ,sumArrivalTimes:  94.3045
newArrivalTime:  63.4728    ,sumArrivalTimes:  157.777
newArrivalTime:  3.22149    ,sumArrivalTimes:  160.999
newArrivalTime:  1.64637    ,sumArrivalTimes:  162.645
newArrivalTime:  13.8235    ,sumArrivalTimes:  176.469

so, based on your experiment you can either use: newArrivalTime or  sumArrivalTimes.

ref:  http://www.math.wsu.edu/faculty/genz/416/lect/l05-45.pdf


问:
How do *nix pseudo-terminals work ? What's the master/slave channel?
I want to write a simple, dumb, X terminal emulator in C on a Linux system.

At first, I just thought I would have to popen a shell and display its output.
I checked xterm and rxvt code, and it looks a bit more complicated.

First, I have to open a pseudo-terminal with openpty. So I look at the man page and see that openpty fills 2 file descriptors, the master and the slave.
Both xterm and rxvt code are messy because of the system-dependent-ness of those specials files.

I understand the termios stuff : it's just a bunch of information about the escape code of the terminal.
What I really don't get is : what am I suppose to do with the master/slave file descriptor ?

An example program which open a terminal, logs in, executes a "ls" on the shell would be awesome.

(English is not my native language, excuse my eventual mistake)

Edit:
Here's the sample code I came up with :

```<code>#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <pty.h>
#include <utmp.h>
#include <ctype.h>

void
safe_print (char* s)
{
    while(*s) {
        if(*s == '\n')
            putchar("\n");
        else if(iscntrl(*s))
            printf("\\e(%d)", *s);
        else
            putchar(*s);
        s++;
    }
}

int
main (int argc, char** argv)
{
    char buf[BUFSIZ] = {0};
    int master;
    int ret = forkpty(&master, NULL, NULL, NULL);

    if(ret == -1)
        puts("no fork"), exit(0);

    if(!ret) {
        execl("/bin/sh", "sh", NULL);
        exit(0);
    }

    sleep(1); /* let the shell run */

    if(argc >= 2) {
        write(master, argv[1], strlen(argv[1]));
        write(master, "\n", 1);
    } else {
        write(master, "date\n", sizeof "date\n");
    }

    while(1) {
        switch(ret = read(master, buf, BUFSIZ)) {
        case -1:
            puts("error!");
            exit(1);
            break;
        case 0:
            puts("nothing.."), sleep(1);
            break;
        default:
            buf[ret] = '\0';
            safe_print(buf);

        }
    }

    close(master);

    return 0;
}
</code>```

答:
With respect to the master/slave part of your question, from the pty(4) man page (which is referenced from the openpty(3) man page on my system):

A pseudo terminal is a pair of
  character devices, a master device and
  a slave device.  The slave device
  provides to a process an interface
  identical to that described in tty(4).
  However, whereas all other devices
  which provide the interface described
  in tty(4) have a hardware device of
  some sort behind them, the slave
  device has, instead, another process
  manipulating it through the master
  half of the pseudo terminal.  That is,
  anything written on the master device
  is given to the slave device as input
  and anything written on the slave
  device is presented as input on the
  master device.

Man pages are your friends.

OwnerDisplayName: aaptel

ContentLicense: CC BY-SA 2.5

Body:
I want to write a simple, dumb, X terminal emulator in C on a Linux system.

At first, I just thought I would have to popen a shell and display its output.
I checked xterm and rxvt code, and it looks a bit more complicated.

First, I have to open a pseudo-terminal with openpty. So I look at the man page and see that openpty fills 2 file descriptors, the master and the slave.
Both xterm and rxvt code are messy because of the system-dependent-ness of those specials files.

I understand the termios stuff : it's just a bunch of information about the escape code of the terminal.
What I really don't get is : what am I suppose to do with the master/slave file descriptor ?

An example program which open a terminal, logs in, executes a "ls" on the shell would be awesome.

(English is not my native language, excuse my eventual mistake)

Edit:
Here's the sample code I came up with :

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <pty.h>
#include <utmp.h>
#include <ctype.h>

void
safe_print (char* s)
{
    while(*s) {
        if(*s == '\n')
            putchar("\n");
        else if(iscntrl(*s))
            printf("\\e(%d)", *s);
        else
            putchar(*s);
        s++;
    }
}

int
main (int argc, char** argv)
{
    char buf[BUFSIZ] = {0};
    int master;
    int ret = forkpty(&master, NULL, NULL, NULL);

    if(ret == -1)
        puts("no fork"), exit(0);

    if(!ret) {
        execl("/bin/sh", "sh", NULL);
        exit(0);
    }

    sleep(1); /* let the shell run */

    if(argc >= 2) {
        write(master, argv[1], strlen(argv[1]));
        write(master, "\n", 1);
    } else {
        write(master, "date\n", sizeof "date\n");
    }

    while(1) {
        switch(ret = read(master, buf, BUFSIZ)) {
        case -1:
            puts("error!");
            exit(1);
            break;
        case 0:
            puts("nothing.."), sleep(1);
            break;
        default:
            buf[ret] = '\0';
            safe_print(buf);

        }
    }

    close(master);

    return 0;
}

LastEditorDisplayName: aaptel

OwnerDisplayName: Dave C

LastEditorDisplayName: Jonathan Leffler


问:
Opinions/headers for splitting an application into front-end/back-end (not user/admin, but ui/logic)
I am building a new web application and playing around with the architecture and would like some opinions about splitting UI and business logic and running them on separate servers.

This means that if someone requests a page, the front end will itself request the data from a back-end server and then not actually perform any calculations/logic but just use the data to populate a template and then respond with that.

Back-End: Java + JAX-WS

Front-End: Kohana 3.1 (PHP)

Data Interchange Format: JSON

Advantages:

clear separation of logic and UI

ability to choose language/framework best suited for either end

possibility to add logic/UI servers depending on which one is the bottleneck in case of performance issues

possibility to make the API publicly available without any extra work (pseudo-internal requests will go to the same API as requests from third-part applications)

ability to change (if need be) the framework/language of either side without having to edit the other

ability to specify different server hardware according to the needs of the logic/UI application

better security (if API private) (??)

Disadvantages:

latency (??)

more servers

So what do you think? Is this a good idea? I haven't been able to find much information so far but my guess is that many big sites do it this way, right? How will performance be affected (I am thinking of running it on EC2)? What are further advantages/disadvantages? Any thoughts on the  languages/frameworks choices?

答:
You also might want to employ the idea of keeping your servers stateless and let the client side handle any state.
This simplifies the whole load-balancing and fail-over stuff and makes you think about a more resource-oriented architecture.

And if you are set on JSON already, you might want to explore the idea of NOT mapping POJOS to your data and use a document store like MongoDB or CouchDB to access JSON data directly.


问:
How to do a NOT EXISTS for a value in MongoDB
I'm pretty clear on how to use $exists for a key in a document, but how I would go about doing it for a specific value of a key?

I have a User collection and a Log collection. I need to find, for all possible Users, the ones who don't have a specific value in a key, for a period of time.

Example: I want all Users that doesn't have Logging documents with the key-valye pair "action":"login".

I thought about doing it like this, first I put all userIDs in an array:

```<code>var allUsers = [];
db.Usuario.find({},{_id:0,terminal:1}).forEach(function(d){allUsers.push(d.terminal)});
</code>```

But I'm confused about how I would build the NOT EXISTS step of this operation.
Also, is there a more efficient way of achieving the above users array?

What I have so far:

```<code>db.Logging.find({
    /* what do I put in here? */,
    "terminal": { $in: allUsers },
    "timestamp": { $gte: dateToTimestamp('2017-12-06') }
})
</code>```

答:
$exist - is use whether this key is present in the particular document or not.

$in - is for the search the things in array and it is internally using the OR condition.

$nin - I think this is the thing which you are looking for, this is use for get the documents which are not present in the array

Eg- db.inventory.find( { qty: { $nin: [ 5, 15 ] } } )db.inventory.find( { qty: { $nin: [ 5, 15 ] } } )enter code here

Body:
I'm pretty clear on how to use $exists for a key in a document, but how I would go about doing it for a specific value of a key?

I have a User collection and a Log collection. I need to find, for all possible Users, the ones who don't have a specific value in a key, for a period of time.

Example: I want all Users that doesn't have Logging documents with the key-valye pair "action":"login".

I thought about doing it like this, first I put all userIDs in an array:

var allUsers = [];
db.Usuario.find({},{_id:0,terminal:1}).forEach(function(d){allUsers.push(d.terminal)});

But I'm confused about how I would build the NOT EXISTS step of this operation.
Also, is there a more efficient way of achieving the above users array?

What I have so far:

db.Logging.find({
    /* what do I put in here? */,
    "terminal": { $in: allUsers },
    "timestamp": { $gte: dateToTimestamp('2017-12-06') }
})