问:
Python multiprocessing merge dictionaries of dictionaries from multiple processes
I am trying to use shared memory across multiple processes to update a dictionary that contains dictionaries which contain dictionaries...  I tried using the Manager from the multiprocessing module, but I am having difficulty adding a dictionary to it.  Please see the code and the comments below.  Essentially this code is supposed to create a copy of the input in another dictionary called "output."  Once I get this working, there will be logic to only copy certain "blades" from the input, but the node/cluster/blade hierarchy must be maintained.

```<code>from multiprocessing import Process, Lock, Manager

# Define dictionary that will be used in this example
input = {
    "Node_1": {
        "IP": "127.0.0.1",
        "clusters": {
            "cluster_1": {
                "blades": {
                    "blade_0_1": "127.0.1.1",
                    "blade_0_2": "127.0.1.2"
                }
            },
            "cluster_2": {
                "blades": {
                    "blade_0_3": "127.0.1.3",
                    "blade_0_4": "127.0.1.4"
                }
            }
        }
    },
    "Node_2": {
        "IP": "127.0.0.2",
        "clusters": {
            "cluster_1": {
                "blades": {
                    "blade_0_1": "127.0.1.1",
                    "blade_0_2": "127.0.1.2"
                }
            },
            "cluster_2": {
                "blades": {
                    "blade_0_3": "127.0.1.3",
                    "blade_0_4": "127.0.1.4"
                }
            }
        }
    }
}

def iterate_over_clusters_in_node(input, node, lock, output):
    """ Iterate over the clusters in the node, then over the blades in the cluster.  Add each blade to the output dictionary."""
    for cluster in input[node]['clusters']:
        for blade in input[node]['clusters'][cluster]['blades']:
            with lock:
                print "node: " + node + ", node_IP: " + input[node]['IP'] + ", cluster: " + cluster + ", Blade: " + blade + ", cluster_IP: " + input[node]['clusters'][cluster]['blades'][blade]
            with lock:
                add_blade_to_output(input, node, cluster, blade, output)

def add_blade_to_output(input, node, cluster, blade, output):
    ''' Adds a blade to the managed output dictionary'''
    if node not in output:
        output[node] = {}
        output[node]['IP'] = input[node]['IP']
        output[node]['clusters'] = {}
    # At this point, I would expect output[node]['IP'] and output[node]['clusters'] to exist
    # But the following print raises KeyError: 'IP'
    print output[node]['IP']
    if cluster not in output[node]['clusters']:
        # Raises KeyError: 'clusters'
        output[node]['clusters'][cluster] = {}
        output[node]['clusters'][cluster]['blades'] = {}
    output[node]['clusters'][cluster]['blades'][blade] = input[node]['clusters'][cluster]['blades'][blade]

if __name__ == "__main__":
    # Create lock to ensure correct handling of output from multiple processes
    lock = Lock()

    # Create dictionary to hold any failed blades so that appropriate measures can be taken
    # Must use a Manager so that the dictionary can be shared among processes
    manager = Manager()
    output = manager.dict()

    # Create array to track our processes
    procs = []

    # Iterate over all nodes in input
    for node in input:
        p = Process(target = iterate_over_clusters_in_node, args = (input, node, lock, output))
        p.start()
        procs.append(p)

    # Join processes and wait for them to stop
    for p in procs:
        p.join()

    print "The final output is:"
    print output
    # Expectation: should print the same dictionary as the input
    # Actual: prints "{'Node_2': {}, 'Node_1': {}}"
</code>```

Do I need to be adding manager.dict() to output[node] instead of the built-in dictionary type?  Or am I going about this all wrong?

Thanks!

Edit: I am not against switching this to a "threading" implementation instead of "multiprocessing."  I'm new to running things in parallel, so if threading is better suited for this type of memory sharing, please let me know.

Edit: Here is the working code:

```<code>from multiprocessing import Process, Lock, Manager

# Define dictionary that will be used in this example
input = {
    "Node_1": {
        "IP": "127.0.0.1",
        "clusters": {
            "cluster_1": {
                "blades": {
                    "blade_0_1": "127.0.1.1",
                    "blade_0_2": "127.0.1.2"
                }
            },
            "cluster_2": {
                "blades": {
                    "blade_0_3": "127.0.1.3",
                    "blade_0_4": "127.0.1.4"
                }
            }
        }
    },
    "Node_2": {
        "IP": "127.0.0.2",
        "clusters": {
            "cluster_1": {
                "blades": {
                    "blade_0_1": "127.0.1.1",
                    "blade_0_2": "127.0.1.2"
                }
            },
            "cluster_2": {
                "blades": {
                    "blade_0_3": "127.0.1.3",
                    "blade_0_4": "127.0.1.4"
                }
            }
        }
    }
}

# Create dictionary to hold any failed blades so that appropriate measures can be taken
# Must use a Manager so that the dictionary can be shared among processes
manager = Manager()
output = manager.dict()

def iterate_over_clusters_in_node(input, node, lock):
    """ Iterate over the clusters in the node, then over the blades in the cluster.  Add each blade to the output dictionary."""
    for cluster in input[node]['clusters']:
        for blade in input[node]['clusters'][cluster]['blades']:
            with lock:
                add_blade_to_output(input, node, cluster, blade)

def add_blade_to_output(input, node, cluster, blade):
    ''' Adds a blade to the managed output dictionary'''
    if node not in output:
        new_node = {}
        new_node[node] = {'IP': input[node]['IP'], 'clusters': {}}
        output.update(new_node)
    new_node = {}
    new_node.update(output)
    if cluster not in output[node]['clusters']:
        new_node[node]['clusters'][cluster] = {}
        new_node[node]['clusters'][cluster]['blades'] = {blade: input[node]['clusters'][cluster]['blades'][blade]}
    else:
        new_node[node]['clusters'][cluster]['blades'][blade] = input[node]['clusters'][cluster]['blades'][blade]
    output.update(new_node)

if __name__ == "__main__":
    # Create lock to ensure correct handling of output from multiple processes
    lock = Lock()

    # Create array to track our processes
    procs = []

    # Iterate over all nodes in input
    for node in input:
        p = Process(target = iterate_over_clusters_in_node, args = (input, node, lock))
        p.start()
        procs.append(p)

    # Join processes and wait for them to stop
    for p in procs:
        p.join()

    print "The final output is:"
    print output
</code>```

答:
According to the python docs,

Modifications to mutable values or items in dict and list proxies will
  not be propagated through the manager, because the proxy has no way of
  knowing when its values or items are modified. To modify such an item,
  you can re-assign the modified object to the container proxy.

With this information, we can update the manager accordingly:

```<code>#output[node] = {}
#output[node]['IP'] = input[node]['IP']
#output[node]['clusters'] = {} These changes are not propagated through the manager

new_node = {}
new_node[node] = {'IP': input[node]['IP'], 'clusters': {}}
output.update(new_node)

#if cluster not in output[node]['clusters']:
    # Raises KeyError: 'clusters'
    #output[node]['clusters'][cluster] = {}
    #output[node]['clusters'][cluster]['blades'] = {}
    #output[node]['clusters'][cluster]['blades'][blade] = input[node]['clusters'][cluster]['blades'][blade]

node_copy = output.copy()
if cluster not in node_copy[node]['clusters']:
    node_copy[node]['clusters'].setdefault(cluster, {'blades': {}})
node_copy[node]['clusters'][cluster]['blades'][blade] = input[node]['clusters'][cluster]['blades'][blade]
output.update(node_copy)
</code>```

References

Notice about value propagation

Body:
I am trying to use shared memory across multiple processes to update a dictionary that contains dictionaries which contain dictionaries...  I tried using the Manager from the multiprocessing module, but I am having difficulty adding a dictionary to it.  Please see the code and the comments below.  Essentially this code is supposed to create a copy of the input in another dictionary called "output."  Once I get this working, there will be logic to only copy certain "blades" from the input, but the node/cluster/blade hierarchy must be maintained.

from multiprocessing import Process, Lock, Manager

# Define dictionary that will be used in this example
input = {
    "Node_1": {
        "IP": "127.0.0.1",
        "clusters": {
            "cluster_1": {
                "blades": {
                    "blade_0_1": "127.0.1.1",
                    "blade_0_2": "127.0.1.2"
                }
            },
            "cluster_2": {
                "blades": {
                    "blade_0_3": "127.0.1.3",
                    "blade_0_4": "127.0.1.4"
                }
            }
        }
    },
    "Node_2": {
        "IP": "127.0.0.2",
        "clusters": {
            "cluster_1": {
                "blades": {
                    "blade_0_1": "127.0.1.1",
                    "blade_0_2": "127.0.1.2"
                }
            },
            "cluster_2": {
                "blades": {
                    "blade_0_3": "127.0.1.3",
                    "blade_0_4": "127.0.1.4"
                }
            }
        }
    }
}

def iterate_over_clusters_in_node(input, node, lock, output):
    """ Iterate over the clusters in the node, then over the blades in the cluster.  Add each blade to the output dictionary."""
    for cluster in input[node]['clusters']:
        for blade in input[node]['clusters'][cluster]['blades']:
            with lock:
                print "node: " + node + ", node_IP: " + input[node]['IP'] + ", cluster: " + cluster + ", Blade: " + blade + ", cluster_IP: " + input[node]['clusters'][cluster]['blades'][blade]
            with lock:
                add_blade_to_output(input, node, cluster, blade, output)

def add_blade_to_output(input, node, cluster, blade, output):
    ''' Adds a blade to the managed output dictionary'''
    if node not in output:
        output[node] = {}
        output[node]['IP'] = input[node]['IP']
        output[node]['clusters'] = {}
    # At this point, I would expect output[node]['IP'] and output[node]['clusters'] to exist
    # But the following print raises KeyError: 'IP'
    print output[node]['IP']
    if cluster not in output[node]['clusters']:
        # Raises KeyError: 'clusters'
        output[node]['clusters'][cluster] = {}
        output[node]['clusters'][cluster]['blades'] = {}
    output[node]['clusters'][cluster]['blades'][blade] = input[node]['clusters'][cluster]['blades'][blade]

if __name__ == "__main__":
    # Create lock to ensure correct handling of output from multiple processes
    lock = Lock()

    # Create dictionary to hold any failed blades so that appropriate measures can be taken
    # Must use a Manager so that the dictionary can be shared among processes
    manager = Manager()
    output = manager.dict()

    # Create array to track our processes
    procs = []

    # Iterate over all nodes in input
    for node in input:
        p = Process(target = iterate_over_clusters_in_node, args = (input, node, lock, output))
        p.start()
        procs.append(p)

    # Join processes and wait for them to stop
    for p in procs:
        p.join()

    print "The final output is:"
    print output
    # Expectation: should print the same dictionary as the input
    # Actual: prints "{'Node_2': {}, 'Node_1': {}}"

Do I need to be adding manager.dict() to output[node] instead of the built-in dictionary type?  Or am I going about this all wrong?

Thanks!

Edit: I am not against switching this to a "threading" implementation instead of "multiprocessing."  I'm new to running things in parallel, so if threading is better suited for this type of memory sharing, please let me know.

Edit: Here is the working code:

from multiprocessing import Process, Lock, Manager

# Define dictionary that will be used in this example
input = {
    "Node_1": {
        "IP": "127.0.0.1",
        "clusters": {
            "cluster_1": {
                "blades": {
                    "blade_0_1": "127.0.1.1",
                    "blade_0_2": "127.0.1.2"
                }
            },
            "cluster_2": {
                "blades": {
                    "blade_0_3": "127.0.1.3",
                    "blade_0_4": "127.0.1.4"
                }
            }
        }
    },
    "Node_2": {
        "IP": "127.0.0.2",
        "clusters": {
            "cluster_1": {
                "blades": {
                    "blade_0_1": "127.0.1.1",
                    "blade_0_2": "127.0.1.2"
                }
            },
            "cluster_2": {
                "blades": {
                    "blade_0_3": "127.0.1.3",
                    "blade_0_4": "127.0.1.4"
                }
            }
        }
    }
}

# Create dictionary to hold any failed blades so that appropriate measures can be taken
# Must use a Manager so that the dictionary can be shared among processes
manager = Manager()
output = manager.dict()

def iterate_over_clusters_in_node(input, node, lock):
    """ Iterate over the clusters in the node, then over the blades in the cluster.  Add each blade to the output dictionary."""
    for cluster in input[node]['clusters']:
        for blade in input[node]['clusters'][cluster]['blades']:
            with lock:
                add_blade_to_output(input, node, cluster, blade)

def add_blade_to_output(input, node, cluster, blade):
    ''' Adds a blade to the managed output dictionary'''
    if node not in output:
        new_node = {}
        new_node[node] = {'IP': input[node]['IP'], 'clusters': {}}
        output.update(new_node)
    new_node = {}
    new_node.update(output)
    if cluster not in output[node]['clusters']:
        new_node[node]['clusters'][cluster] = {}
        new_node[node]['clusters'][cluster]['blades'] = {blade: input[node]['clusters'][cluster]['blades'][blade]}
    else:
        new_node[node]['clusters'][cluster]['blades'][blade] = input[node]['clusters'][cluster]['blades'][blade]
    output.update(new_node)

if __name__ == "__main__":
    # Create lock to ensure correct handling of output from multiple processes
    lock = Lock()

    # Create array to track our processes
    procs = []

    # Iterate over all nodes in input
    for node in input:
        p = Process(target = iterate_over_clusters_in_node, args = (input, node, lock))
        p.start()
        procs.append(p)

    # Join processes and wait for them to stop
    for p in procs:
        p.join()

    print "The final output is:"
    print output

Body:
According to the python docs,

Modifications to mutable values or items in dict and list proxies will
  not be propagated through the manager, because the proxy has no way of
  knowing when its values or items are modified. To modify such an item,
  you can re-assign the modified object to the container proxy.

With this information, we can update the manager accordingly:

#output[node] = {}
#output[node]['IP'] = input[node]['IP']
#output[node]['clusters'] = {} These changes are not propagated through the manager

new_node = {}
new_node[node] = {'IP': input[node]['IP'], 'clusters': {}}
output.update(new_node)

#if cluster not in output[node]['clusters']:
    # Raises KeyError: 'clusters'
    #output[node]['clusters'][cluster] = {}
    #output[node]['clusters'][cluster]['blades'] = {}
    #output[node]['clusters'][cluster]['blades'][blade] = input[node]['clusters'][cluster]['blades'][blade]

node_copy = output.copy()
if cluster not in node_copy[node]['clusters']:
    node_copy[node]['clusters'].setdefault(cluster, {'blades': {}})
node_copy[node]['clusters'][cluster]['blades'][blade] = input[node]['clusters'][cluster]['blades'][blade]
output.update(node_copy)

References

Notice about value propagation


来源: stackexchange

问:
Add buttons to google sheets that links me to another sheet
Im in need for a script that when I make a button in google sheets. I can click on it and will take me to another work sheet. Something like below but I cant get this to work

```<code>function GoToSheet1() {
  var SPREADSHEET_URL = 'INSERT_SPREADSHEET_URL_HERE';
  // Name of the specific sheet in the spreadsheet.
  var SHEET_NAME = 'INSERT_SHEET_NAME_HERE';
</code>```

Thanks in advance Jarrad

答:
Here's one way to do it with a sidebar or a dialog.  I like sidebars better but hey take up more room.  You modify this so that you only get the sheets you want.

```<code>  function showGoToSheet() {

  var allsheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
  var s = '<style>#mySheets{margin:5px 5px 5px 5px;background-color:#cccccc;}#btn0, #btn1, #btn2, #btn3, #btn4, #btn5, #btn6, #btn7, #btn8{margin:0px 5px 5px 0px;}</style><div id="mySheets">';
  for (var i=0; i<allsheets.length; i++)
  {
    var sheet_name = allsheets[i].getName();
    if (sheet_name != 'ActivityLog' && sheet_name != 'AllData' && sheet_name != 'Scratch' && sheet_name != 'Data Validation')
    {
      s += '<input id="btn' + i +'" type="button" value="Go to: ' + sheet_name + '" onClick="google.script.run.getMySheet(\'' + sheet_name + '\');" /><br />';
    }
  }
  s += '<input type="button" value="Exit" onClick="google.script.host.close();" /></div>';
  //myUtilities.dispStatus('My Sheets',s,600,400);
  var html=HtmlService().createHtmlOutput(s).setWidth(600).setHeight(400);
  SpreadsheetApp.getUi().showModelessDialog(html, 'My Sheets');
}
</code>```

Or you can try to use the little icon in the lower left of your spreadsheet.  I like the little icon if you have a lot of sheets.

ContentLicense: CC BY-SA 3.0

Body:
Im in need for a script that when I make a button in google sheets. I can click on it and will take me to another work sheet. Something like below but I cant get this to work

function GoToSheet1() {
  var SPREADSHEET_URL = 'INSERT_SPREADSHEET_URL_HERE';
  // Name of the specific sheet in the spreadsheet.
  var SHEET_NAME = 'INSERT_SHEET_NAME_HERE';

Thanks in advance Jarrad

Body:
Here's one way to do it with a sidebar or a dialog.  I like sidebars better but hey take up more room.  You modify this so that you only get the sheets you want.

  function showGoToSheet() {

  var allsheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
  var s = '<style>#mySheets{margin:5px 5px 5px 5px;background-color:#cccccc;}#btn0, #btn1, #btn2, #btn3, #btn4, #btn5, #btn6, #btn7, #btn8{margin:0px 5px 5px 0px;}</style><div id="mySheets">';
  for (var i=0; i<allsheets.length; i++)
  {
    var sheet_name = allsheets[i].getName();
    if (sheet_name != 'ActivityLog' && sheet_name != 'AllData' && sheet_name != 'Scratch' && sheet_name != 'Data Validation')
    {
      s += '<input id="btn' + i +'" type="button" value="Go to: ' + sheet_name + '" onClick="google.script.run.getMySheet(\'' + sheet_name + '\');" /><br />';
    }
  }
  s += '<input type="button" value="Exit" onClick="google.script.host.close();" /></div>';
  //myUtilities.dispStatus('My Sheets',s,600,400);
  var html=HtmlService().createHtmlOutput(s).setWidth(600).setHeight(400);
  SpreadsheetApp.getUi().showModelessDialog(html, 'My Sheets');
}

Or you can try to use the little icon in the lower left of your spreadsheet.  I like the little icon if you have a lot of sheets.


问:
Is there a way to specify specific repository classes to include in Spring Data MongoDB?
I have several repository interfaces defined in one package. However, I want to configure them separately, in groups, to use with respective database setup. @EnableMongoRepositories seems to only consider packages as unit of grouping. Is there a way to achieve multiple repository configuration without having to break up my interfaces into multiple packages?

答:
Link each profile to distinct property source (.properties file)

```<code>@Configuration
    public class AppConfig
    {
        @Configuration
        @Profile("dev")
        @PropertySource("classpath:localdb.properties")
        static class LocalDb
        { }

        @Configuration
        @Profile("prod")
        @PropertySource({"classpath:remotedb.properties"})
        static class RemoteDB
        {}
</code>```

Define active profile via VM args

```<code>-Dspring.profiles.active=dev
</code>```

or programatically

```<code>SpringApplication.setAdditionalProfiles(..)
//or
ConfigurableEnvironment environment = this.applicationContext.getEnvironment();
environment.setActiveProfiles("dev");

// or in case of WebAppContext via web.xml
<context-param>
    <param-name>spring.profiles.active</param-name>
    <param-value>dev</param-value> // or prod
 </context-param>

//or in case of WebAppContext if using servlet 3.1+ container set programatically
servletContext.setInitParameter("spring.profiles.active", "dev");
</code>```

Body:
Link each profile to distinct property source (.properties file)

@Configuration
    public class AppConfig
    {
        @Configuration
        @Profile("dev")
        @PropertySource("classpath:localdb.properties")
        static class LocalDb
        { }

        @Configuration
        @Profile("prod")
        @PropertySource({"classpath:remotedb.properties"})
        static class RemoteDB
        {}

Define active profile via VM args

-Dspring.profiles.active=dev

or programatically

SpringApplication.setAdditionalProfiles(..)
//or
ConfigurableEnvironment environment = this.applicationContext.getEnvironment();
environment.setActiveProfiles("dev");

// or in case of WebAppContext via web.xml
<context-param>
    <param-name>spring.profiles.active</param-name>
    <param-value>dev</param-value> // or prod
 </context-param>

//or in case of WebAppContext if using servlet 3.1+ container set programatically
servletContext.setInitParameter("spring.profiles.active", "dev");


问:
Weird scanf behaviour
I was working on a C program and I found a weird behaviour with scanf:

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

int main() {
    int *a, i;
    printf("Hello, World!\n");
    for (i = 0; i < 10; i++) {
        scanf("%u", &a[i]);
    }
    for (i = 0; i < 10; i++) {
        printf("%d\n", a[i]);
    }
    return 0;
}
</code>```

For 10 input I sent + and the output was like:

```<code>1
0
239646720
32767
0
0
239646727
32767
239646771
32767
</code>```

I expected a memory leak, could any one please explain me this behaviour ?

答:
Multiple problems in your code:

a is an uninitialized pointer, you should instead define it as an array of 10 int. As coded, your program has undefined behavior, it is quite surprising that it runs at all.

you should check the return value of scanf(): if the conversion fails, it returns 0 or EOF and the destination is not modified, printing it has undefined behavior. Typing just a + sign for an integer results in a conversion failure.

Here is a corrected version:

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

int main(void) {
    int a[10], i;
    printf("Hello, World!\n");
    for (i = 0; i < 10; i++) {
        if (scanf("%u", &a[i]) != 1) {
            fprintf(stderr, "input error\n");
            exit(1);
        }
    }
    for (i = 0; i < 10; i++) {
        printf("%d\n", a[i]);
    }
    return 0;
}
</code>```

Title: Weird scanf behaviour

Body:
I was working on a C program and I found a weird behaviour with scanf:

#include <stdio.h>

int main() {
    int *a, i;
    printf("Hello, World!\n");
    for (i = 0; i < 10; i++) {
        scanf("%u", &a[i]);
    }
    for (i = 0; i < 10; i++) {
        printf("%d\n", a[i]);
    }
    return 0;
}

For 10 input I sent + and the output was like:

1
0
239646720
32767
0
0
239646727
32767
239646771
32767

I expected a memory leak, could any one please explain me this behaviour ?

Body:
Multiple problems in your code:

a is an uninitialized pointer, you should instead define it as an array of 10 int. As coded, your program has undefined behavior, it is quite surprising that it runs at all.

you should check the return value of scanf(): if the conversion fails, it returns 0 or EOF and the destination is not modified, printing it has undefined behavior. Typing just a + sign for an integer results in a conversion failure.

Here is a corrected version:

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

int main(void) {
    int a[10], i;
    printf("Hello, World!\n");
    for (i = 0; i < 10; i++) {
        if (scanf("%u", &a[i]) != 1) {
            fprintf(stderr, "input error\n");
            exit(1);
        }
    }
    for (i = 0; i < 10; i++) {
        printf("%d\n", a[i]);
    }
    return 0;
}


问:
MERGE INTO not working with Postgres 9.6
In my Postgres 9.6 environment, when I try to execute "MERGE INTO" query, it throws me following error:

```<code>ERROR:  syntax error at or near "MERGE"
LINE 1: MERGE INTO Stock USING Buy ON Stock.item_id = Buy.item_id  W...
        ^
</code>```

It seems like it does not support MERGE query. However when I do google, it seems that MERGE is supported by Postgres since version 9.1.

Please tell me whats going wrong here.

Edit: Following are the sources from where I found MERGE support in Postgres.

https://wiki.postgresql.org/wiki/MergeTestExamples

答:
MERGE aka INSERT ... ON CONFLICT DO NOTHING/UPDATE or UPSERT is only available to postgres 9.5 and later:

Note: MERGE is often used interchangeably with the term UPSERT.

UPSERT functionality will be in the PostgreSQL 9.5 release -- see
  What's new in PostgreSQL 9.5  MERGE is not in 9.4.5 (the latest
  PostgreSQL release as of 2015-10-08)

Body:
In my Postgres 9.6 environment, when I try to execute "MERGE INTO" query, it throws me following error:

ERROR:  syntax error at or near "MERGE"
LINE 1: MERGE INTO Stock USING Buy ON Stock.item_id = Buy.item_id  W...
        ^

It seems like it does not support MERGE query. However when I do google, it seems that MERGE is supported by Postgres since version 9.1.

Please tell me whats going wrong here.

Edit: Following are the sources from where I found MERGE support in Postgres.

https://wiki.postgresql.org/wiki/MergeTestExamples


问:
How to convert mySQL Query to Laravel 5.4 Query Builder
Please someone should help me convert this SQL Query to Laravel 5.4 Query Builder syntax. I have searched for solutions and found some but not exactly as I wanted.

I have 3 tables:

Feeds:
   - feed_id
   - user_id
   - feed_title

Users:
   - id
   - username

Commments:
   - comment_id
   - feed_id
   - text
   - user_id

On my view returned, I want to see the feed title, user's user name, and a count of all comments to each feed. Like what you see on facebook: displaying the amount of comments on each post displayed. Please I really need this to be done:

This is the SQL code I tried in MySQL Database, it kinda works there but returns an error when I try to implement the same in Laravel

```<code>select *, count(comments.comment_id) as comment_count
from `feeds`
inner join `users` on
`feeds`.`user_id` = `users`.`id`
inner join `comments` on
`feeds`.`feed_id` = `comments`.`comment_feed_id`
group by `comments`.`comment_feed_id`
</code>```

答:
```<code>DB::table('feeds')
    ->selectRaw('*, count(comments.comment_id) as comment_count')
    ->join('users', 'users.id', '=', 'feeds.user_id')
    ->join('comments', 'feeds.id', '=', 'comments.comment_feed_id')
    ->groupBy('comments.comment_feed_id')
    ->get();
</code>```

Body:
Please someone should help me convert this SQL Query to Laravel 5.4 Query Builder syntax. I have searched for solutions and found some but not exactly as I wanted.

I have 3 tables:

Feeds:
   - feed_id
   - user_id
   - feed_title

Users:
   - id
   - username

Commments:
   - comment_id
   - feed_id
   - text
   - user_id

On my view returned, I want to see the feed title, user's user name, and a count of all comments to each feed. Like what you see on facebook: displaying the amount of comments on each post displayed. Please I really need this to be done:

This is the SQL code I tried in MySQL Database, it kinda works there but returns an error when I try to implement the same in Laravel

select *, count(comments.comment_id) as comment_count
from `feeds`
inner join `users` on
`feeds`.`user_id` = `users`.`id`
inner join `comments` on
`feeds`.`feed_id` = `comments`.`comment_feed_id`
group by `comments`.`comment_feed_id`


问:
Google spreadsheets auto fill formula with form submission
I am trying to get my Google form submissions set up so I can produce a PDF with Auto Crat with the right information since my form has yes and no questions.

I need 4 different columns to auto fill with my different but similar formula below as my first sheet is filled using IMPORTRANGE from my Form submissions master sheet. If there is an easier way to do all this please let me know since I am really new to Google formulas.

=if(Sheet1!P3="Yes", (CONCATENATE("My yes answer "&CHAR(10)&CHAR(10)&"Employee name: "&Sheet1!Q3&CHAR(10)&"Location (room number where the employee will be during the emergency): "&Sheet1!R3&CHAR(10)&"Telephone number (room where the employee will be during the emergency): "&Sheet1!S3&CHAR(10)&"Critical operation: "&Sheet1!T3)), "it is the no response")

Here is the Master

Here is the two sheets I am using. The first pulls in the information and the second sheet is where I use my formulas.

答: I was able to get an add-on to sheets called copyDown to copy the formula down the rows for me. This helped me to keep it all on one sheet instead of having two sheets so I could use AutoCrat for compiling my PDF correctly. Thank you for all the help in solving this issue.</p>


问:
How to set Maximum PageSize per Page in gridView in ASP.net
I want to set Maximum Pagesize per Page in gridview.If you know ,please tell me.</p>

答:
I see @Aristos got few upvotes and did not get correct answer because code snippet was incorrect.
Should update to:</p>

```<code>YourGridviewID.AllowPaging=false;
</code>```

Body:
I see @Aristos got few upvotes and did not get correct answer because code snippet was incorrect.
Should update to:

YourGridviewID.AllowPaging=false;


问:
Neo4j how to create a property set, with out duplicate values unlike a List
I have a :hobby relation between :User nodes.

The hobby relation contains a List property { hobbies:['football','hockey'] }

Now I am iterating through a data stream and i want to uniquely merge the hobbies into this List (Like a set). I tried using coalesce like this:

```<code>MERGE  (from)-[rel:hobbies]->(to)
set rel.hobbies= COALESCE(rel.hobbies, []) + 'football';
</code>```

The problem is that now my property contains duplicates

{ hobbies:['football','hockey','football'] }

How can i avoid duplicates?

答:
[UPDATED]

This query will add 'football' to the hobbies collection only if it does not already exist (by doing a check first):

```<code>MERGE (from)-[rel:hobbies]->(to)
FOREACH(x in CASE WHEN NOT ('football' IN rel.hobbies) THEN [1] END |
  SET rel.hobbies = COALESCE(rel.hobbies, []) + 'football')
</code>```

Instead of hardcoding the hobby to add (e.g., 'football'), you should use a parameter.

Also, you should consider altering your data model to use Hobby nodes to represent the different hobbies, which is a more graph-oriented approach.

Body:
I have a :hobby relation between :User nodes.

The hobby relation contains a List property { hobbies:['football','hockey'] }

Now I am iterating through a data stream and i want to uniquely merge the hobbies into this List (Like a set). I tried using coalesce like this:

MERGE  (from)-[rel:hobbies]->(to)
set rel.hobbies= COALESCE(rel.hobbies, []) + 'football';

The problem is that now my property contains duplicates

{ hobbies:['football','hockey','football'] }

How can i avoid duplicates?

Body:
[UPDATED]

This query will add 'football' to the hobbies collection only if it does not already exist (by doing a check first):

MERGE (from)-[rel:hobbies]->(to)
FOREACH(x in CASE WHEN NOT ('football' IN rel.hobbies) THEN [1] END |
  SET rel.hobbies = COALESCE(rel.hobbies, []) + 'football')

Instead of hardcoding the hobby to add (e.g., 'football'), you should use a parameter.

Also, you should consider altering your data model to use Hobby nodes to represent the different hobbies, which is a more graph-oriented approach.


问:
Having trouble with Bash / Shell While Loop String Comparison
I'm learning scripting to help with my work, and I'm just trying to wrap my head around using while loops.

I want to repeat a question if a user doesn't answer with Yes or No.
Currently I have that working with an if conditional statement, that was easy, but it simply exits the script if the user doesn't answer with y or n.

I've tried various iterations of the below, figured out that I can't use -ne unless it's an integer, but what I can't seem to get right is the string comparison.

I found much better ways to do this online, but it's pointless to copy-paste those if I'm missing something basic about a simple while loop.

```<code>#!/bin/sh

while [ $CONFIRM != "^y"|"^n"] # This is where I'm stuck
do
echo "Please say Yes or No."   # Probably not doing this right either
read CONFIRM                   # Or this
done

if  echo "$CONFIRM" | grep -iq "^n" ; then
echo "Okay, stopping script."
else

#do some cool stuff

fi
</code>```

Any and all advice appreciated.

And the correct answer is...

```<code>#!/bin/bash

shopt -s nocasematch

while ! [[ $CONFIRM =~ ^(y|n) ]]
do
echo "Please say Yes or No."
read CONFIRM
done

echo "Success!"
</code>```

答:
You are mixing regular expressions with pattern matching.

```<code># Regular expression
while ! [[ $confirm =~ ^(y|n) ]]; do
</code>```

or

```<code># extended pattern
while [[ $confirm != @(y|n)* ]]; do
</code>```

should each do what you want.

The read command takes the name of a variable as its argument.

```<code>read confirm
</code>```

Using a parameter expansion causes read to set the value of the variable whose name is contained in confirm:

```<code>$ confirm=foo
$ read $confirm <<< 3
$ echo "$foo"
3
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm learning scripting to help with my work, and I'm just trying to wrap my head around using while loops.

I want to repeat a question if a user doesn't answer with Yes or No.
Currently I have that working with an if conditional statement, that was easy, but it simply exits the script if the user doesn't answer with y or n.

I've tried various iterations of the below, figured out that I can't use -ne unless it's an integer, but what I can't seem to get right is the string comparison.

I found much better ways to do this online, but it's pointless to copy-paste those if I'm missing something basic about a simple while loop.

#!/bin/sh

while [ $CONFIRM != "^y"|"^n"] # This is where I'm stuck
do
echo "Please say Yes or No."   # Probably not doing this right either
read CONFIRM                   # Or this
done

if  echo "$CONFIRM" | grep -iq "^n" ; then
echo "Okay, stopping script."
else

#do some cool stuff

fi

Any and all advice appreciated.

And the correct answer is...

#!/bin/bash

shopt -s nocasematch

while ! [[ $CONFIRM =~ ^(y|n) ]]
do
echo "Please say Yes or No."
read CONFIRM
done

echo "Success!"

Body:
You are mixing regular expressions with pattern matching.

# Regular expression
while ! [[ $confirm =~ ^(y|n) ]]; do

or

# extended pattern
while [[ $confirm != @(y|n)* ]]; do

should each do what you want.

The read command takes the name of a variable as its argument.

read confirm

Using a parameter expansion causes read to set the value of the variable whose name is contained in confirm:

$ confirm=foo
$ read $confirm <<< 3
$ echo "$foo"
3


问:
jQuery wrong math
I have an issue with comparing two fields. In console when I run:

```<code>$("input[name=light]").val() <= $("#units_home #light").text()
</code>```

with Values:

```<code>$("input[name=light]").val() = 10
$("#units_home #light").text() = 7
</code>```

The result is true. Below is a screenshot of my console.

答:
You're trying to perform a mathematical comparison on strings. Use parseInt to convert them to numbers first:</p>

```<code>parseInt($("input[name=light]").val()) <= parseInt($("#units_home #light").text())
</code>```

Title: jQuery wrong math

Body:
I have an issue with comparing two fields. In console when I run:

$("input[name=light]").val() <= $("#units_home #light").text()

with Values:

$("input[name=light]").val() = 10
$("#units_home #light").text() = 7

The result is true. Below is a screenshot of my console.

Body:
You're trying to perform a mathematical comparison on strings. Use parseInt to convert them to numbers first:

parseInt($("input[name=light]").val()) <= parseInt($("#units_home #light").text())


问:
Cordova is not giving the wanted result
Trying to do an app using Cordova, and I'm not having the wanted result.

Here's my app before building (displaying using ripple in google chrome)

And Here's the rendering after being built (in my phone)

Don't mind about the background image, I just need to design one with the appropriate size.

Other things that doesn't work well, all the animations, are either not with the right animation-duration, or not playing with the right size (like filling a button with another color when clicking on it goes out of its border).

HTML:

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height">
    <title>LoginPage</title>
    <link rel="stylesheet" href="css/ExternalCSS/materialize.min.css">
    <link rel="stylesheet" href="css/ExternalCSS/semantic.min.css">
    <link rel="stylesheet" href="css/MyCSS/LoginPage.css">
</head>
<body id="body" class="verticalDiv">
    <div id="title" class="verticalDiv">
        <h1>SIGN IN</h1>
        <div class="horizentalDiv">
            <div class="verticalDiv">
                <svg><line x1="10" y1="0" x2="96" y2="0"/></svg>
                <svg><line x1="10" y1="0" x2="96" y2="0"/></svg>
            </div>
            <h6 style="margin: 0px 0px 0px 0px;">TO</h6>
            <div class="verticalDiv">
                <svg><line x1="5" y1="0" x2="90" y2="0"/></svg>
                <svg><line x1="5" y1="0" x2="90" y2="0"/></svg>
            </div>
        </div>
        <h3>YOUR ACCOUNT</h3>
    </div>
    <!-- FIN DU TEXTE -->
    <div id="informations" class="verticalDiv" >
        <div id="formulaireEmail">
            <div class="horizentalDiv">
                <input type="text" placeholder=" Email adress">
            </div>
        </div>
        <div id="FormulairePassword">
            <div class="horizentalDiv">
                <input type="password" placeholder=" Password">
            </div>
        </div>
        <div id="FormulaireConfirmationPassword">
            <div class="horizentalDiv">
                <input type="password" placeholder=" Password confirmation" style="animation-duration: 1s; display: none">
            </div>
        </div>
        <div id="buttons" class="horizentalDiv">
            <button class="horizentalDiv btn-large btn-floating waves-effect waves-light cyan">
                <img src="img/iconeConnexion.png" style="width: 25px; ">
            </button>
            <button class="horizentalDiv btn-large btn-floating pulse scale-transition cyan scale-in">
                <img src="img/iconeInscription.png" style="width: 25px;">
            </button>
            <button class="horizentalDiv btn-large btn-floating scale-transition cyan pulse scale-out">
                <img src="img/iconeAccueil.png" style="width: 25px;">
            </button>
        </div>
    </div>
    <div id="fbgmailsignin" class="verticalDiv">
        <button class="horizentalDiv fbgmail waves-effect waves-light ">
            <img src="img/FB.png">
        </button>
        <button class="horizentalDiv fbgmail waves-effect waves-light ">
            <img src="img/Gmail.png">
        </button>
    </div>
</body>
<script src="js/ExternalJS/jquery.min.js"></script>
<script src="js/ExternalJS/semantic.min.js"></script>
<script src="js/ExternalJS/materialize.min.js"></script>
<script src="js/MyJS/LoginPage.js"></script>
</code>```

CSS:

```<code>html{  width: 100%;  height: 100%;  }
#body {
    position: absolute;
    width: 100%;
height: 100%;
left: 0px;
top: 0px;
margin: 0px 0px 0px 0px;
background-repeat: no-repeat;
background-image: linear-gradient(2deg, rgba(0, 206, 155, 0.3) 0%, rgba(0,         196, 208, 0.3) 100%), url("../../img/Background-image.png");
justify-content: space-around;
}
svg{  width: 100px;  height: 2px;  }
line{  stroke: rgb(255,255,255);  }
::-webkit-input-placeholder{  color: rgba(255,255,255,0.4);  }
h1,h2,h3,h4,h5,h6{  color: white;  margin: 5px 5px 0px 5px;  }
hr{  margin: 5px 0px 0px 0px;  }
input{  color: rgba(255,255,255,0.8);  font-size: 12pt;  }
/* My Classes */
.horizentalDiv{
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
    margin: 0px 0px 0px 0px;
    padding: 0px 0px 0px 0px;
}
.verticalDiv{
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    margin: 0px 0px 0px 0px;
    padding: 0px 0px 0px 0px;
}

/* DIV Text au millieu */
#title {animation-duration: 1.5s;}
#title h1{  margin: 0px 0px 0px 0px;  font-size: 40pt;  }
#title h6{  font-size: 8pt;  }
#title h3{  font-size: 14pt;  }
/* DIV Sign in */
#informations input{ padding: 0px 0px 0px 40px; }
#informations input[type="text"]{
    background: url("../../img/iconeEmail.png");
    background-repeat: no-repeat;
    background-position: left;
}
#informations input[type="password"]{
    background: url("../../img/iconePass.png");
    background-repeat: no-repeat;
    background-position: left;
}
/* Sign up / Sign in buttons */
#buttons button:nth-child(1),#buttons button:nth-child(2){  margin-right: 10px;  }
/* Gmail/FB Container */

#fbgmailsignin button:nth-child(1){  margin-bottom: 5px;  }
.fbgmail{  border-radius: 24px;  }
</code>```

JavaScript:

```<code>LoginPage = {
launch: function(){
    this.initListeners();
},

initListeners: function(){
    var bouttonLogin = document.querySelector("#buttons button:nth-child(1)");
        bouttonLogin.addEventListener("click", function(){
            $("#buttons button:nth-child(1)").transition('jiggle');

        });
    var title = document.querySelector("#title");
        title.addEventListener("animationend", function(){
            LoginPage.Animation.animateTitleNext();
        });
    var bouttonInscription = document.querySelector("#buttons button:nth-child(2)");
        bouttonInscription.addEventListener("click", function(){
            LoginPage.Animation.animateButtonSignup(false);
            LoginPage.Animation.animerBouttonAccueil(true);
            LoginPage.Animation.animatePasswordConfirmation();
            LoginPage.Animation.animateTitle();
            LoginPage.Animation.animateFBGmail();
        });
    var bouttonAccueil = document.querySelector("#buttons button:nth-child(3");
        bouttonAccueil.addEventListener("click", function(){
            LoginPage.Animation.animerBouttonAccueil(false);
            LoginPage.Animation.animateButtonSignup(true);
            LoginPage.Animation.animatePasswordConfirmation();
            LoginPage.Animation.animateTitle();
            LoginPage.Animation.animateFBGmail();
        });
    var bouttonFB = document.querySelector("#fbgmailsignin button:nth-child(1)");
        bouttonFB.addEventListener("click", function(){
            $("#fbgmailsignin button:nth-child(1)").transition('jiggle');
        })
    var bouttonGmail = document.querySelector("#fbgmailsignin button:nth-child(2)");
        bouttonGmail.addEventListener("click", function(){
            $("#fbgmailsignin button:nth-child(2)").transition('jiggle');
        })
},

Animation: {
    firstTime: true,
    stop: false,

    animateTitle: function(){
        $("#title").transition('swing down');
        this.firstTime = !this.firstTime;
        this.stop = false;
    },
    animateTitleNext: function(){
        if(!this.stop){
            $("#title").transition('swing down');
            if(!this.firstTime) {
                document.querySelector("#title h1").innerHTML = "SIGN UP";
                document.querySelector("#title h6").innerHTML = "AND";
                document.querySelector("#title h3").innerHTML = "ENJOY !";
            }
            else {
                document.querySelector("#title h1").innerHTML = "SIGN IN";
                document.querySelector("#title h6").innerHTML = "TO";
                document.querySelector("#title h3").innerHTML = "YOUR ACCOUNT";
            }
            this.stop = true;
        }
    },
    animatePasswordConfirmation: function(){
        if(this.firstTime)
            $("#FormulaireConfirmationPassword input").transition("horizontal flip");
        else $("#FormulaireConfirmationPassword input").transition("vertical flip");
    },
    animateFBGmail: function(){
        if(this.firstTime){
            $("#fbgmailsignin button:nth-child(1)").transition('fly left');
            $("#fbgmailsignin button:nth-child(2)").transition('fly right');
        }
        else {
            $("#fbgmailsignin button:nth-child(1)").transition('fly right');
            $("#fbgmailsignin button:nth-child(2)").transition('fly left');
        }
    },
    animateButtonSignup: function(repere){
        var bouttonInscription = document.querySelector("#buttons button:nth-child(2)");
        if(repere){
            bouttonInscription.classList.remove("scale-out");
            bouttonInscription.classList.add("scale-in");
        }
        else{
            bouttonInscription.classList.remove("scale-in");
            bouttonInscription.classList.add("scale-out");
        }
    },
    animerBouttonAccueil: function(repere){
        var bouttonAccueil = document.querySelector("#buttons button:nth-child(3)");
            if(repere){
                bouttonAccueil.classList.remove("scale-out");
                bouttonAccueil.classList.add("scale-in");
            }
            else{
                bouttonAccueil.classList.remove("scale-in");
                bouttonAccueil.classList.add("scale-out");
            }
        }
    }
}
LoginPage.launch();
</code>```

Here's the project link for the ones who want to test it.
https://www.fichier-rar.fr/2017/07/05/myproject/

Thanks in advance...

答:
It looks like is not a responsive site and the container in your cordova app is bigger than browser one. You could debug your app in Chrome in Android case or Safari in the iOS case.

Regardig to effects, make sure that scale-out and scale-in classes have their transitions with prefix -web-kit the other way this does not works.

Title: Cordova is not giving the wanted result

Body:
Trying to do an app using Cordova, and I'm not having the wanted result.

Here's my app before building (displaying using ripple in google chrome)

And Here's the rendering after being built (in my phone)

Don't mind about the background image, I just need to design one with the appropriate size.

Other things that doesn't work well, all the animations, are either not with the right animation-duration, or not playing with the right size (like filling a button with another color when clicking on it goes out of its border).

HTML:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height">
    <title>LoginPage</title>
    <link rel="stylesheet" href="css/ExternalCSS/materialize.min.css">
    <link rel="stylesheet" href="css/ExternalCSS/semantic.min.css">
    <link rel="stylesheet" href="css/MyCSS/LoginPage.css">

SIGN IN

                <svg><line x1="10" y1="0" x2="96" y2="0"/></svg>
                <svg><line x1="10" y1="0" x2="96" y2="0"/></svg>

TO

                <svg><line x1="5" y1="0" x2="90" y2="0"/></svg>
                <svg><line x1="5" y1="0" x2="90" y2="0"/></svg>

YOUR ACCOUNT

                <input type="text" placeholder=" Email adress">

                <input type="password" placeholder=" Password">

                <input type="password" placeholder=" Password confirmation" style="animation-duration: 1s; display: none">

            <button class="horizentalDiv btn-large btn-floating waves-effect waves-light cyan">

            </button>
            <button class="horizentalDiv btn-large btn-floating pulse scale-transition cyan scale-in">

            </button>
            <button class="horizentalDiv btn-large btn-floating scale-transition cyan pulse scale-out">

            </button>

        <button class="horizentalDiv fbgmail waves-effect waves-light ">

        </button>
        <button class="horizentalDiv fbgmail waves-effect waves-light ">

        </button>

CSS:

html{  width: 100%;  height: 100%;  }
#body {
    position: absolute;
    width: 100%;
height: 100%;
left: 0px;
top: 0px;
margin: 0px 0px 0px 0px;
background-repeat: no-repeat;
background-image: linear-gradient(2deg, rgba(0, 206, 155, 0.3) 0%, rgba(0,         196, 208, 0.3) 100%), url("../../img/Background-image.png");
justify-content: space-around;
}
svg{  width: 100px;  height: 2px;  }
line{  stroke: rgb(255,255,255);  }
::-webkit-input-placeholder{  color: rgba(255,255,255,0.4);  }
h1,h2,h3,h4,h5,h6{  color: white;  margin: 5px 5px 0px 5px;  }
hr{  margin: 5px 0px 0px 0px;  }
input{  color: rgba(255,255,255,0.8);  font-size: 12pt;  }
/* My Classes */
.horizentalDiv{
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
    margin: 0px 0px 0px 0px;
    padding: 0px 0px 0px 0px;
}
.verticalDiv{
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    margin: 0px 0px 0px 0px;
    padding: 0px 0px 0px 0px;
}

/* DIV Text au millieu */
#title {animation-duration: 1.5s;}
#title h1{  margin: 0px 0px 0px 0px;  font-size: 40pt;  }
#title h6{  font-size: 8pt;  }
#title h3{  font-size: 14pt;  }
/* DIV Sign in */
#informations input{ padding: 0px 0px 0px 40px; }
#informations input[type="text"]{
    background: url("../../img/iconeEmail.png");
    background-repeat: no-repeat;
    background-position: left;
}
#informations input[type="password"]{
    background: url("../../img/iconePass.png");
    background-repeat: no-repeat;
    background-position: left;
}
/* Sign up / Sign in buttons */
#buttons button:nth-child(1),#buttons button:nth-child(2){  margin-right: 10px;  }
/* Gmail/FB Container */

#fbgmailsignin button:nth-child(1){  margin-bottom: 5px;  }
.fbgmail{  border-radius: 24px;  }

JavaScript:

LoginPage = {
launch: function(){
    this.initListeners();
},

initListeners: function(){
    var bouttonLogin = document.querySelector("#buttons button:nth-child(1)");
        bouttonLogin.addEventListener("click", function(){
            $("#buttons button:nth-child(1)").transition('jiggle');

        });
    var title = document.querySelector("#title");
        title.addEventListener("animationend", function(){
            LoginPage.Animation.animateTitleNext();
        });
    var bouttonInscription = document.querySelector("#buttons button:nth-child(2)");
        bouttonInscription.addEventListener("click", function(){
            LoginPage.Animation.animateButtonSignup(false);
            LoginPage.Animation.animerBouttonAccueil(true);
            LoginPage.Animation.animatePasswordConfirmation();
            LoginPage.Animation.animateTitle();
            LoginPage.Animation.animateFBGmail();
        });
    var bouttonAccueil = document.querySelector("#buttons button:nth-child(3");
        bouttonAccueil.addEventListener("click", function(){
            LoginPage.Animation.animerBouttonAccueil(false);
            LoginPage.Animation.animateButtonSignup(true);
            LoginPage.Animation.animatePasswordConfirmation();
            LoginPage.Animation.animateTitle();
            LoginPage.Animation.animateFBGmail();
        });
    var bouttonFB = document.querySelector("#fbgmailsignin button:nth-child(1)");
        bouttonFB.addEventListener("click", function(){
            $("#fbgmailsignin button:nth-child(1)").transition('jiggle');
        })
    var bouttonGmail = document.querySelector("#fbgmailsignin button:nth-child(2)");
        bouttonGmail.addEventListener("click", function(){
            $("#fbgmailsignin button:nth-child(2)").transition('jiggle');
        })
},

Animation: {
    firstTime: true,
    stop: false,

    animateTitle: function(){
        $("#title").transition('swing down');
        this.firstTime = !this.firstTime;
        this.stop = false;
    },
    animateTitleNext: function(){
        if(!this.stop){
            $("#title").transition('swing down');
            if(!this.firstTime) {
                document.querySelector("#title h1").innerHTML = "SIGN UP";
                document.querySelector("#title h6").innerHTML = "AND";
                document.querySelector("#title h3").innerHTML = "ENJOY !";
            }
            else {
                document.querySelector("#title h1").innerHTML = "SIGN IN";
                document.querySelector("#title h6").innerHTML = "TO";
                document.querySelector("#title h3").innerHTML = "YOUR ACCOUNT";
            }
            this.stop = true;
        }
    },
    animatePasswordConfirmation: function(){
        if(this.firstTime)
            $("#FormulaireConfirmationPassword input").transition("horizontal flip");
        else $("#FormulaireConfirmationPassword input").transition("vertical flip");
    },
    animateFBGmail: function(){
        if(this.firstTime){
            $("#fbgmailsignin button:nth-child(1)").transition('fly left');
            $("#fbgmailsignin button:nth-child(2)").transition('fly right');
        }
        else {
            $("#fbgmailsignin button:nth-child(1)").transition('fly right');
            $("#fbgmailsignin button:nth-child(2)").transition('fly left');
        }
    },
    animateButtonSignup: function(repere){
        var bouttonInscription = document.querySelector("#buttons button:nth-child(2)");
        if(repere){
            bouttonInscription.classList.remove("scale-out");
            bouttonInscription.classList.add("scale-in");
        }
        else{
            bouttonInscription.classList.remove("scale-in");
            bouttonInscription.classList.add("scale-out");
        }
    },
    animerBouttonAccueil: function(repere){
        var bouttonAccueil = document.querySelector("#buttons button:nth-child(3)");
            if(repere){
                bouttonAccueil.classList.remove("scale-out");
                bouttonAccueil.classList.add("scale-in");
            }
            else{
                bouttonAccueil.classList.remove("scale-in");
                bouttonAccueil.classList.add("scale-out");
            }
        }
    }
}
LoginPage.launch();

Here's the project link for the ones who want to test it.
https://www.fichier-rar.fr/2017/07/05/myproject/

Thanks in advance...


问:
Breaking a form with a partial
I have this form made by rails scaffold:

```<code><%= form_for(@archive) do |f| %>
  <% if @archive.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@archive.errors.count, "error") %> prohibited this archive from being saved:</h2>

      <ul>
      <% @archive.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :objective %><br>
    <%= f.cktext_area :objective %>
  </div>
  <div class="field">
    <%= f.label :settings %><br>
    <%= f.cktext_area :settings %>
  </div>
  <div class="field">
    <%= f.label :related_documents %><br>
    <%= f.cktext_area :related_documents %>
  </div>
  <div class="field">
    <%= f.label :responsability %><br>
    <%= f.cktext_area :responsability %>
  </div>
  <div class="field">
    <%= f.label :material_needed %><br>
    <%= f.cktext_area :material_needed %>
  </div>
  <div class="field">
    <%= f.label :description %><br>
    <%= f.cktext_area :description %>
  </div>
  <div class="field">
    <%= f.label :preventive_measures %><br>
    <%= f.cktext_area :preventive_measures %>
  </div>
  <div class="field">
    <%= f.label :corrective_actions %><br>
    <%= f.cktext_area :corrective_actions %>
  </div>
  <div class="field">
    <%= f.label :execution %><br>
    <%= f.cktext_area :execution %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>
</code>```

And I wanted to separate the fields, I wanted to use partials because it keeps repeating, what changes is the name of the field, I wanted to render the partial form of a field and pass the field name. Because of the fact that I'm going to use the custom ckeditor, and I'll keep repeating on the form, it may give the error chance. Am I right to think that? Is my idea correct? If so, how can I do to pass the field? Will this influence something in the database?
I wanted to do something like this.

form:

```<code><%= form_for(@archive) do |f| %>
  <% if @archive.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@archive.errors.count, "error") %> prohibited this archive from being saved:</h2>

      <ul>
      <% @archive.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

<%= render partial 'fields', 'field_name' %>

 <!-- Call many times and pass the field name -->

  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>
</code>```

partial:

```<code>  <div class="field">
    <%= f.label :field_name%><br>
    <%= f.cktext_area :field_name %>
  </div>
</code>```

答:
A better approach to this in my humble opinion is to customize a form helper and do something like this:

```<code><%= f.cktext_with_label :objective %>
<%= f.cktext_with_label :settings %>
<%= f.cktext_with_label :related_documents %>
<%= f.cktext_with_label :responsability %>
...
</code>```

You create a new form helper called "cktext_with_label" then that create the fields like you want, even the div container for example.

You can check this answer Custom form helpers

Title: Breaking a form with a partial

Body:
I have this form made by rails scaffold:

<%= form_for(@archive) do |f| %>
  <% if @archive.errors.any? %>

<%= pluralize(@archive.errors.count, "error") %> prohibited this archive from being saved:

      <% @archive.errors.full_messages.each do |message| %>

<%= message %>

      <% end %>

  <% end %>

    <%= f.label :objective %>

    <%= f.cktext_area :objective %>

    <%= f.label :settings %>

    <%= f.cktext_area :settings %>

    <%= f.label :related_documents %>

    <%= f.cktext_area :related_documents %>

    <%= f.label :responsability %>

    <%= f.cktext_area :responsability %>

    <%= f.label :material_needed %>

    <%= f.cktext_area :material_needed %>

    <%= f.label :description %>

    <%= f.cktext_area :description %>

    <%= f.label :preventive_measures %>

    <%= f.cktext_area :preventive_measures %>

    <%= f.label :corrective_actions %>

    <%= f.cktext_area :corrective_actions %>

    <%= f.label :execution %>

    <%= f.cktext_area :execution %>

    <%= f.submit %>

<% end %>

And I wanted to separate the fields, I wanted to use partials because it keeps repeating, what changes is the name of the field, I wanted to render the partial form of a field and pass the field name. Because of the fact that I'm going to use the custom ckeditor, and I'll keep repeating on the form, it may give the error chance. Am I right to think that? Is my idea correct? If so, how can I do to pass the field? Will this influence something in the database?
I wanted to do something like this.

form:

<%= form_for(@archive) do |f| %>
  <% if @archive.errors.any? %>

<%= pluralize(@archive.errors.count, "error") %> prohibited this archive from being saved:

      <% @archive.errors.full_messages.each do |message| %>

<%= message %>

      <% end %>

  <% end %>

<%= render partial 'fields', 'field_name' %>

    <%= f.submit %>

<% end %>

partial:

    <%= f.label :field_name%>

    <%= f.cktext_area :field_name %>

Body:
A better approach to this in my humble opinion is to customize a form helper and do something like this:

<%= f.cktext_with_label :objective %>
<%= f.cktext_with_label :settings %>
<%= f.cktext_with_label :related_documents %>
<%= f.cktext_with_label :responsability %>
...

You create a new form helper called "cktext_with_label" then that create the fields like you want, even the div container for example.

You can check this answer Custom form helpers


问:
Formatting CSV with PHP
I'm taking form data and writing it to a csv file on the server. I keep running into the same type of issues and I don't know what I am doing wrong. Either the column headers repeat with each entry, or each additional submission writes on the same row. Also, how would I take the $_POST data and populate the csv? I have to declare it twice to get this to work to this point. Here is what I have that somewhat works.</p>

```<code><?php
   //this is just for the post data, but I'm having to declare the key/values again below. I'm sure this is wrong.
   $email = $_POST['email'];
   //rest of the form inputs go here same as $email
   //some server side validation builds an 'error' array

   if(!isset($error) {
        $del = ", ";
        //this is where I have to repeat the post data key/values
        $data[1] = $_POST['email'];
        $data[2] = $_POST['FirstName'];
        $data[3] = $_POST['LastName'];
        $data[4] = $_POST['Address'];
        $data[5] = $_POST['City'];
        $data[6] = $_POST['Country'];
        $data[7] = $_POST['State'];
        $data[8] = $_POST['Phone1'];
        $data[9] = $_POST['password'];

        $file = fopen("Registration.csv", "a");
        //$data is the column headers that won't behave
        $data = "Email, First Name, Last Name, Address, City, Country, State, Phone, Password
        ".implode($del, $data);
        fwrite($file, $data);
        fclose($file);
   }
?>
</code>```

答:
```<code>$myfile = fopen("Registration.csv", "a") or die("Unable to open file!");
$data = "Email, First Name, Last Name, Address, City, Country, State, Phone, Password
    ".implode($del, $data);

fwrite($myfile, "\n". $txt);
fclose($myfile);
</code>```

i hope this helps

Title: Formatting CSV with PHP

Body:
I'm taking form data and writing it to a csv file on the server. I keep running into the same type of issues and I don't know what I am doing wrong. Either the column headers repeat with each entry, or each additional submission writes on the same row. Also, how would I take the $_POST data and populate the csv? I have to declare it twice to get this to work to this point. Here is what I have that somewhat works.

<?php
   //this is just for the post data, but I'm having to declare the key/values again below. I'm sure this is wrong.
   $email = $_POST['email'];
   //rest of the form inputs go here same as $email
   //some server side validation builds an 'error' array

   if(!isset($error) {
        $del = ", ";
        //this is where I have to repeat the post data key/values
        $data[1] = $_POST['email'];
        $data[2] = $_POST['FirstName'];
        $data[3] = $_POST['LastName'];
        $data[4] = $_POST['Address'];
        $data[5] = $_POST['City'];
        $data[6] = $_POST['Country'];
        $data[7] = $_POST['State'];
        $data[8] = $_POST['Phone1'];
        $data[9] = $_POST['password'];

        $file = fopen("Registration.csv", "a");
        //$data is the column headers that won't behave
        $data = "Email, First Name, Last Name, Address, City, Country, State, Phone, Password
        ".implode($del, $data);
        fwrite($file, $data);
        fclose($file);
   }
?>

Body:
$myfile = fopen("Registration.csv", "a") or die("Unable to open file!");
$data = "Email, First Name, Last Name, Address, City, Country, State, Phone, Password
    ".implode($del, $data);

fwrite($myfile, "\n". $txt);
fclose($myfile);

i hope this helps


问:
Resolve <unresolved overloaded function type> in std::async call
Can't resolve this instance of calling std::lower_bound from std::async. Example:

```<code>#include <vector>
#include <algorithm>
#include <future>
#include <iostream>

int main() {
  std::vector<int> v = {1,3,4,6,7};
  auto res = std::async(std::launch::async, std::lower_bound, v.begin(), v.end(), 4);
  std::cout << *res.get() << std::endl;
  return 0;
}
</code>```

Compiler output makes it look like it doesn't realize std::launch::async is a launch policy and it should use the async call with the launch policy but I could be wrong.

```<code>test.cpp:8:84: error: no matching function for call to ‘async(std::launch, <unresolved overloaded function type>, std::vector<int>::iterator, std::vector<int>::iterator, int)’
res = std::async(std::launch::async, std::lower_bound, v.begin(), v.end(), 3);
                                                                            ^
In file included from test.cpp:3:0:
/usr/include/c++/6/future:1709:5: note: candidate: template<class _Fn, class ... _Args> std::future<typename std::result_of<typename std::decay<_Tp>::type(typename std::decay<_BoundArgs>::type ...)>::type> std::async(std::launch, _Fn&&, _Args&& ...)
 async(launch __policy, _Fn&& __fn, _Args&&... __args)
 ^~~~~
/usr/include/c++/6/future:1709:5: note:   template argument deduction/substitution failed:
test.cpp:8:84: note:   couldn't deduce template parameter ‘_Fn’
res = std::async(std::launch::async, std::lower_bound, v.begin(), v.end(), 3);
                                                                          ^
In file included from test.cpp:3:0:
/usr/include/c++/6/future:1739:5: note: candidate: template<class _Fn, class ... _Args> std::future<typename std::result_of<typename std::decay<_Tp>::type(typename std::decay<_BoundArgs>::type ...)>::type> std::async(_Fn&&, _Args&& ...)
 async(_Fn&& __fn, _Args&&... __args)
 ^~~~~
/usr/include/c++/6/future:1739:5: note:   template argument deduction/substitution failed:
/usr/include/c++/6/future: In substitution of ‘template<class _Fn, class ... _Args> std::future<typename std::result_of<typename std::decay<_Tp>::type(typename std::decay<_BoundArgs>::type ...)>::type> std::async(_Fn&&, _Args&& ...) [with _Fn = std::launch; _Args = {}]’:
test.cpp:8:84:   required from here
/usr/include/c++/6/future:1739:5: error: no type named ‘type’ in ‘class std::result_of<std::launch()>’
</code>```

答:
std::lower_bound is a function template, you have to explicitly specify its arguments to be able to pass it around:

```<code>int main() {
  using V = std::vector<int>;
  V v = {1,3,4,6,7};
  auto res = std::async(std::launch::async, std::lower_bound<V::iterator, int>, v.begin(), v.end(), 4);
  std::cout << *res.get() << std::endl;
  return 0;
}
</code>```

Body:
Can't resolve this instance of calling std::lower_bound from std::async. Example:

#include <vector>
#include <algorithm>
#include <future>
#include <iostream>

int main() {
  std::vector<int> v = {1,3,4,6,7};
  auto res = std::async(std::launch::async, std::lower_bound, v.begin(), v.end(), 4);
  std::cout << *res.get() << std::endl;
  return 0;
}

Compiler output makes it look like it doesn't realize std::launch::async is a launch policy and it should use the async call with the launch policy but I could be wrong.

test.cpp:8:84: error: no matching function for call to ‘async(std::launch, <unresolved overloaded function type>, std::vector<int>::iterator, std::vector<int>::iterator, int)’
res = std::async(std::launch::async, std::lower_bound, v.begin(), v.end(), 3);
                                                                            ^
In file included from test.cpp:3:0:
/usr/include/c++/6/future:1709:5: note: candidate: template<class _Fn, class ... _Args> std::future<typename std::result_of<typename std::decay<_Tp>::type(typename std::decay<_BoundArgs>::type ...)>::type> std::async(std::launch, _Fn&&, _Args&& ...)
 async(launch __policy, _Fn&& __fn, _Args&&... __args)
 ^~~~~
/usr/include/c++/6/future:1709:5: note:   template argument deduction/substitution failed:
test.cpp:8:84: note:   couldn't deduce template parameter ‘_Fn’
res = std::async(std::launch::async, std::lower_bound, v.begin(), v.end(), 3);
                                                                          ^
In file included from test.cpp:3:0:
/usr/include/c++/6/future:1739:5: note: candidate: template<class _Fn, class ... _Args> std::future<typename std::result_of<typename std::decay<_Tp>::type(typename std::decay<_BoundArgs>::type ...)>::type> std::async(_Fn&&, _Args&& ...)
 async(_Fn&& __fn, _Args&&... __args)
 ^~~~~
/usr/include/c++/6/future:1739:5: note:   template argument deduction/substitution failed:
/usr/include/c++/6/future: In substitution of ‘template<class _Fn, class ... _Args> std::future<typename std::result_of<typename std::decay<_Tp>::type(typename std::decay<_BoundArgs>::type ...)>::type> std::async(_Fn&&, _Args&& ...) [with _Fn = std::launch; _Args = {}]’:
test.cpp:8:84:   required from here
/usr/include/c++/6/future:1739:5: error: no type named ‘type’ in ‘class std::result_of<std::launch()>’

Body:
std::lower_bound is a function template, you have to explicitly specify its arguments to be able to pass it around:

int main() {
  using V = std::vector<int>;
  V v = {1,3,4,6,7};
  auto res = std::async(std::launch::async, std::lower_bound<V::iterator, int>, v.begin(), v.end(), 4);
  std::cout << *res.get() << std::endl;
  return 0;
}


问:
RecyclerView gets confused when notifying changes manually and through the DiffUtil
I've got an interesting situation where my adapter has 2 view types - HEADER and ITEM. Header view is always at position 0. When I update my data, I use DiffUtil to get the diff of the data. To disptach the updates and rebind, I use a ListUpdateCallback:

```<code>private void dispatchUpdates(
        @NonNull final RecyclerView.Adapter adapter,
        @NonNull DiffUtil.DiffResult result) {
    result.dispatchUpdatesTo(new ListUpdateCallback() {
        @Override
        public void onInserted(int position, int count) {
            adapter.notifyItemRangeInserted(position + getItemOffset(), count);
        }
    ....
</code>```

so I can add the offset (i.e. 1 cause of the header that's always present) to the position calculated by DiffUtil to update the correct elements. This works fine.

The problem happens when I also need to update the header. I manually calculate the header diff and notify the adapter. Together with DiffUtil the code looks like this:

```<code>        DiffUtil.DiffResult diffResult = DiffUtil
                .calculateDiff(new ItemDiffUtil(getItems(), newData));
        Bundle headerDiff = getDiffPayload(newData);
        dispatchUpdates(this, diffResult);
        if (!isNullOrEmpty(headerDiff.keySet())) {
            notifyItemChanged(0, headerDiff);
        }
</code>```

This is refusing to play nicely. With multiple updates dispatched to the adapter (say, inserting 3 items), it gets confused and I can see duplicate items in my grid (just the thumbnails loaded through Picasso). If I comment out notifyItemChanged(0, headerDiff); the header is obviously not updated, but everything else works fine.

My question is whether it's possible to queue these updates in a more meaningful way so that I can still use the DiffUtil but my header gets updated as well?

EDIT: interestingly, the same issue persists if I use AirBnb's Epoxy instead of my own RecyclerView adapter

答:
I'm still not sure why this is happening, but the culprit I think is Picasso. I've noticed a few things in the logs:

When the issue manifests, Picasso never completes the request:

```<code>D/Picasso: Main        created      [R14655] Request{content://com.app.myapp.contentprovider/thumb/20170705173259427 resize(534,534) centerCrop}
D/Picasso: Dispatcher  enqueued     [R14655]+0ms
D/Picasso: Hunter      executing    [R14655]+0ms
D/Picasso: Hunter      removed      [R14655]+4ms from
D/Picasso: Dispatcher  canceled     [R14655]+4ms
</code>```

Also there's something weird happening with Picasso as it goes into an endless loop creating requests for each element in my grid:

```<code>D/Picasso: Main        created      [R14424] Request{content://com.app.myapp.contentprovider/thumb/20170705173054794 resize(534,534) centerCrop}
D/Picasso: Main        completed    [R14424] from MEMORY
<...> // repeated for each ViewHolder forever in an endless loop
</code>```

Anyway, moving to Glide has solved the issue as far as I can tell.

Body:
I've got an interesting situation where my adapter has 2 view types - HEADER and ITEM. Header view is always at position 0. When I update my data, I use DiffUtil to get the diff of the data. To disptach the updates and rebind, I use a ListUpdateCallback:

private void dispatchUpdates(
        @NonNull final RecyclerView.Adapter adapter,
        @NonNull DiffUtil.DiffResult result) {
    result.dispatchUpdatesTo(new ListUpdateCallback() {
        @Override
        public void onInserted(int position, int count) {
            adapter.notifyItemRangeInserted(position + getItemOffset(), count);
        }
    ....

so I can add the offset (i.e. 1 cause of the header that's always present) to the position calculated by DiffUtil to update the correct elements. This works fine.

The problem happens when I also need to update the header. I manually calculate the header diff and notify the adapter. Together with DiffUtil the code looks like this:

        DiffUtil.DiffResult diffResult = DiffUtil
                .calculateDiff(new ItemDiffUtil(getItems(), newData));
        Bundle headerDiff = getDiffPayload(newData);
        dispatchUpdates(this, diffResult);
        if (!isNullOrEmpty(headerDiff.keySet())) {
            notifyItemChanged(0, headerDiff);
        }

This is refusing to play nicely. With multiple updates dispatched to the adapter (say, inserting 3 items), it gets confused and I can see duplicate items in my grid (just the thumbnails loaded through Picasso). If I comment out notifyItemChanged(0, headerDiff); the header is obviously not updated, but everything else works fine.

My question is whether it's possible to queue these updates in a more meaningful way so that I can still use the DiffUtil but my header gets updated as well?

EDIT: interestingly, the same issue persists if I use AirBnb's Epoxy instead of my own RecyclerView adapter

Body:
I'm still not sure why this is happening, but the culprit I think is Picasso. I've noticed a few things in the logs:

When the issue manifests, Picasso never completes the request:

D/Picasso: Main        created      [R14655] Request{content://com.app.myapp.contentprovider/thumb/20170705173259427 resize(534,534) centerCrop}
D/Picasso: Dispatcher  enqueued     [R14655]+0ms
D/Picasso: Hunter      executing    [R14655]+0ms
D/Picasso: Hunter      removed      [R14655]+4ms from
D/Picasso: Dispatcher  canceled     [R14655]+4ms

Also there's something weird happening with Picasso as it goes into an endless loop creating requests for each element in my grid:

D/Picasso: Main        created      [R14424] Request{content://com.app.myapp.contentprovider/thumb/20170705173054794 resize(534,534) centerCrop}
D/Picasso: Main        completed    [R14424] from MEMORY
<...> // repeated for each ViewHolder forever in an endless loop

Anyway, moving to Glide has solved the issue as far as I can tell.


问:
adding variable to python function using other variable
I would like pass the variables into the function that uses range(). How do I pass variable C that has more then one number via one variable. Something like range(5, 10, 2)?

Here is my example code:

```<code>a = 0
b = 10
c = 2
def num_count(a, b, c):
        for number in range(c):
            a += b
        print("New Count is: {0}".format(a))
</code>```

I tried passing it as a string and converting it to an integer as well as by using a list. Nothing worked.

答:
you can pass in the range like you mentioned with only a small change to the
for loop

```<code>a = 0
b = 10
c = range(5, 10, 2)
def num_count(a, b, c):
    for number in c:
        a += b
    print("New Count is: {0}".format(a))

num_count(a,b,c)
</code>```

or, as khelwood* mentioned, pass in a list/tuple and expand it with *

```<code>a = 0
b = 10
c = (5, 10, 2)
def num_count(a, b, c):
    for number in range(*c):
        a += b
    print("New Count is: {0}".format(a))

num_count(a,b,c)
</code>```

both output 30 which is expected

Body:
I would like pass the variables into the function that uses range(). How do I pass variable C that has more then one number via one variable. Something like range(5, 10, 2)?

Here is my example code:

a = 0
b = 10
c = 2
def num_count(a, b, c):
        for number in range(c):
            a += b
        print("New Count is: {0}".format(a))

I tried passing it as a string and converting it to an integer as well as by using a list. Nothing worked.

Body:
you can pass in the range like you mentioned with only a small change to the
for loop

a = 0
b = 10
c = range(5, 10, 2)
def num_count(a, b, c):
    for number in c:
        a += b
    print("New Count is: {0}".format(a))

num_count(a,b,c)

or, as khelwood* mentioned, pass in a list/tuple and expand it with *

a = 0
b = 10
c = (5, 10, 2)
def num_count(a, b, c):
    for number in range(*c):
        a += b
    print("New Count is: {0}".format(a))

num_count(a,b,c)

both output 30 which is expected


问:
Replacing quotes in xml
I have this below incoming xml where i have " instead of ". How can I replace those with ". please let me know

Input XML:

```<code><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
 <soapenv:Body>
  <ns1:PDM xmlns:ns1="http://example.com">
   <ns1:ds><Details ID="3453636" Add=""/></ns1:ds>
  </ns1:PDM>
 </soapenv:Body>
</soapenv:Envelope>
</code>```

Expected Output:

```<code><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
 <soapenv:Body>
  <ns1:PDM xmlns:ns1="http://example.com">
   <ns1:ds><Details ID="3453636" Add=""/></ns1:ds>
  </ns1:PDM>
 </soapenv:Body>
</soapenv:Envelope>
</code>```

答:
Your input text is not a valid XML, so XSLT will refuse to process it.

Instead you can use e.g. the following Perl one-liner script:

```<code>perl -pe "s/"/\"/g" -i.bak your_file.xml
</code>```

Of course, you must have Perl installed.

Replace your_file.xml with the actual name of your file.

This command will replace the input file with the changed content
and the original (input) content will be saved as your_file.xml.bak.

Title: Replacing quotes in xml

Body:
I have this below incoming xml where i have " instead of ". How can I replace those with ". please let me know

Input XML:

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
 <soapenv:Body>
  <ns1:PDM xmlns:ns1="http://example.com">
   <ns1:ds></ns1:ds>
  </ns1:PDM>
 </soapenv:Body>
</soapenv:Envelope>

Expected Output:

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
 <soapenv:Body>
  <ns1:PDM xmlns:ns1="http://example.com">
   <ns1:ds></ns1:ds>
  </ns1:PDM>
 </soapenv:Body>
</soapenv:Envelope>

Body:
Your input text is not a valid XML, so XSLT will refuse to process it.

Instead you can use e.g. the following Perl one-liner script:

perl -pe "s/&quot;/\"/g" -i.bak your_file.xml

Of course, you must have Perl installed.

Replace your_file.xml with the actual name of your file.

This command will replace the input file with the changed content
and the original (input) content will be saved as your_file.xml.bak.


问:
Passing a string variable to querySelector() in an angular2 component
When I hardcode the css selector inside querySelector(), everything goes well. But, when I pass the css selector as a variable of type string, it doesn't work (Actually, when I log the result of querySelector with the css selector variable passed to it, there is an object in console but nothing has changed in DOM).
In this component, I've created an "amChart" chart and I want to change the font family of the value and category axes of the chart.

here is the component.ts and component.html files:

import {AfterViewInit, Component, ElementRef, Input, OnInit, Renderer} from '@angular/core';
import { AmChartsService } from '@amcharts/amcharts3-angular';
import { AmChartDataProviderService } from '../../services/amChartDataProvider';
import { LineAmChartsColorPickerService } from '../../services/lineAmChartsColorPicker';

@Component({
  selector: 'am-chart',
  templateUrl: './am-chart.component.html',
  styleUrls: ['./am-chart.component.scss'],
})
export class AmChartComponent implements OnInit, AfterViewInit {
  private chart: any;
  private data: object;
  private cssSelector: string;

  @Input() chartId: string;

  constructor(private _amChartsService: AmChartsService, private _amChartDataProvider: AmChartDataProviderService,
              private _lineAmChartColorPicker: LineAmChartsColorPickerService, private _el: ElementRef, private _renderer: Renderer) {
    this.cssSelector = `#${this.chartId} .amcharts-chart-div`;
  }

  ngOnInit() {
    this.data = this._amChartDataProvider.getData();
    this.data = this._lineAmChartColorPicker.lineAmChartColorPicker(this.data);
    this.chart = this._amChartsService.makeChart(this.chartId, this.data);

    this.chart.addListener('rendered', (event) => {
      this._renderer.setElementStyle(this._el.nativeElement.querySelector(this.cssSelector),
      'font-family', 'B Nazanin');  // this line of code doesn't work properly. I should pass "#chart1 .amcharts-chart-div" instrad of this.cssSelector.
    });
  }

  ngAfterViewInit() {
    this.data = this._amChartsService.makeChart(this.chartId, this.data);
  }

  private zoomChart() {
    this.chart.zoomToIndexes(this.chart.dataProvider.length - 20, this.chart.dataProvider.length - 1);
  }

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="{{chartId}}" class="chart-dimensions"></div></code>```

答:
I found the answer myself!
First I should use amcharts3 instead of amcharts-angular package because there is a plugin called "amchart responsive" that handles the change of the chart's container.
Secondly, I should only call makeChart once in ngAfterViewInit().
Here's my final component.ts and component.html and component.scss:

import {AfterViewInit, Component, DoCheck, ElementRef, Input, OnInit, Output, Renderer, ViewChild} from '@angular/core';
import { AmChartsService } from '@amcharts/amcharts3-angular';
import { AmChartDataProviderService } from '../../services/amChartDataProvider';
import { LineAmChartsColorPickerService } from '../../services/lineAmChartsColorPicker';

import 'amcharts3';
import 'amcharts3/amcharts/plugins/responsive/responsive.js';
import 'amcharts3/amcharts/serial.js';

import 'ammap3';
import 'ammap3/ammap/maps/js/worldLow';

@Component({
  selector: 'am-chart',
  templateUrl: './am-chart.component.html',
  styleUrls: ['./am-chart.component.scss'],
})
export class AmChartComponent implements OnInit, AfterViewInit {
  private chart: any;
  private data: object;

  @Input() chartId: string;

  @ViewChild('myAmChart') _selector: ElementRef;

  constructor(private _amChartsService: AmChartsService, private _amChartDataProvider: AmChartDataProviderService,
              private _lineAmChartColorPicker: LineAmChartsColorPickerService) { }

  ngOnInit() {
    this.data = this._amChartDataProvider.getData();
    this.data = this._lineAmChartColorPicker.lineAmChartColorPicker(this.data);
    // this.chart = this._amChartsService.makeChart(this.chartId, this.data);
    // this.chart = AmCharts.makeChart(this._selector.nativeElement, this.data);
  }

  ngAfterViewInit() {
    this.chart = AmCharts.makeChart(this._selector.nativeElement, this.data);
  }

  private zoomChart() {
    this.chart.zoomToIndexes(this.chart.dataProvider.length - 20, this.chart.dataProvider.length - 1);
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.chart-dimensions {
  width:100%;
  height:380px;
}</code>```

```

Body:
I found the answer myself!
First I should use amcharts3 instead of amcharts-angular package because there is a plugin called "amchart responsive" that handles the change of the chart's container.
Secondly, I should only call makeChart once in ngAfterViewInit().
Here's my final component.ts and component.html and component.scss:

import {AfterViewInit, Component, DoCheck, ElementRef, Input, OnInit, Output, Renderer, ViewChild} from '@angular/core';
import { AmChartsService } from '@amcharts/amcharts3-angular';
import { AmChartDataProviderService } from '../../services/amChartDataProvider';
import { LineAmChartsColorPickerService } from '../../services/lineAmChartsColorPicker';

import 'amcharts3';
import 'amcharts3/amcharts/plugins/responsive/responsive.js';
import 'amcharts3/amcharts/serial.js';

import 'ammap3';
import 'ammap3/ammap/maps/js/worldLow';

@Component({
  selector: 'am-chart',
  templateUrl: './am-chart.component.html',
  styleUrls: ['./am-chart.component.scss'],
})
export class AmChartComponent implements OnInit, AfterViewInit {
  private chart: any;
  private data: object;

  @Input() chartId: string;

  @ViewChild('myAmChart') _selector: ElementRef;

  constructor(private _amChartsService: AmChartsService, private _amChartDataProvider: AmChartDataProviderService,
              private _lineAmChartColorPicker: LineAmChartsColorPickerService) { }

  ngOnInit() {
    this.data = this._amChartDataProvider.getData();
    this.data = this._lineAmChartColorPicker.lineAmChartColorPicker(this.data);
    // this.chart = this._amChartsService.makeChart(this.chartId, this.data);
    // this.chart = AmCharts.makeChart(this._selector.nativeElement, this.data);
  }

  ngAfterViewInit() {
    this.chart = AmCharts.makeChart(this._selector.nativeElement, this.data);
  }

  private zoomChart() {
    this.chart.zoomToIndexes(this.chart.dataProvider.length - 20, this.chart.dataProvider.length - 1);
  }
}

.chart-dimensions {
  width:100%;
  height:380px;
}

<div #myAmChart id="{{chartId}}" class="chart-dimensions"></div>


问:
Performance Comparison of Shell Scripts vs high level interpreted langs (C#/Java/etc.)
First - This is not meant to be a 'which is better, ignorant nonionic war thread'... But rather, I generally need help in making an architecture decision / argument to put forward to my boss.

Skipping the details - I simply just would love to know and find the results of anyone who has done some performance comparisons of Shell vs [Insert General Purpose Programming Language (interpreted) here), such as C# or Java...

Surprisingly, I have spent some time on Google on searching here to not find any of this data. Has anyone ever done these comparisons, in different use-cases; hitting a database like in a XYX # of loops doing different types of SQL (Oracle pref, but MSSQL would do) queries such as any of the CRUD ops - and also not hitting database and just regular 50k loop type comparison doing different types of calculations, and things of that nature?

In particular - for right now, I need to a comparison of hitting an Oracle DB from a shell script vs, lets say C# (again, any GPPL thats interpreted would be fine, even the higher level ones like Python). But I also need to know about standard programming calculations / instructions/etc...

Before you ask 'why not just write a quick test yourself? The answer is: I've been a Windows developer my whole life/career and have very limited knowledge of Shell scripting - not to mention *nix as a whole.... So asking the question on here from the more experienced guys would be grealty beneficial, not to mention time saving as we are in near perputual deadline crunch as it is ;).

答:
While this doesn't include "Shell" (aka sh/bash/ksh/powerscript) languages, it is a relatively large list of "language [implementation] performance" -- packed full with generalities and caveats. In any case, someone may enjoy it.

http://benchmarksgame.alioth.debian.org/


问:
How do I minimize the color selector in Visual Studio (Mac)?
How do I get out of this jam, where I've opened the color editor in Visual Studio (v7.0.1 build 24) and pressed Maximize? I'm finding the color selector popover to be completely broken, the close button does not work. Also, it will not set the color when I enter a HEX value.

How can I fix this?

答: Open your Storyboards / XIBs in Xcode and edit there.</p>


问:
Relationship between the shell and a C program
I wrote the following code as part of an exercise in chapter one of K&R.  The code replaces tabs and backslashes as expected, but it does not replace backspaces with \b.  Here is the code:

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

int main(void)
{
    int c;

    while((c = getchar()) != EOF)
    {
        if (c == '\t')
        {
            putchar('\\');
            putchar('t');
        }

        if (c == '\b')
        {
            //putchar('\\');
            //putchar('b');
            printf("\\b");
        }

        if (c == '\\')
        {
            putchar('\\');
            putchar('\\');
        }

        if (c != '\t' && c != '\b' && c != '\\')
        {
            putchar(c);
        }
    }

    return 0;
}
</code>```

I've looked through Stack Overflow.  The answers to this question talk about the shell's consuming the backspace, the result being that code I write never sees the backspace.  This brings me to my question: what happens to the input I provide at the keyboard?  I assume this becomes part of the stdin stream.  Clearly, though, not all the characters I enter make it to my code.  Can someone please explain what processing happens between my keystrokes and the handling of that input by my code?  Also, is there a way for my code to read the stdin buffer before this processing occurs?

I hope these questions make sense.  It took me a while to figure out what I am trying to ask, and I'm not sure I've figured that out completely.

答:
When getchar() is reading from an interactive console, the function won't return until after you press the ENTER key.  Then it will return with the first character entered, and immediately return for each subsequent character you entered up to a newline character.

If you pressed backspace, delete, or an arrow key prior to pressing ENTER, the terminal processes those keystrokes and will only send the "final result" when you press ENTER.

Had you been reading from a redirected-in file (i.e. you called you program as ./myprog < input_file) or piped output from another program (i.e. ./otherprog | ./myprog), then getchar would return right away for each character and you would see everything, including control characters and individual UTF-8 bytes.

Body:
I wrote the following code as part of an exercise in chapter one of K&R.  The code replaces tabs and backslashes as expected, but it does not replace backspaces with \b.  Here is the code:

#include <stdio.h>

int main(void)
{
    int c;

    while((c = getchar()) != EOF)
    {
        if (c == '\t')
        {
            putchar('\\');
            putchar('t');
        }

        if (c == '\b')
        {
            //putchar('\\');
            //putchar('b');
            printf("\\b");
        }

        if (c == '\\')
        {
            putchar('\\');
            putchar('\\');
        }

        if (c != '\t' && c != '\b' && c != '\\')
        {
            putchar(c);
        }
    }

    return 0;
}

I've looked through Stack Overflow.  The answers to this question talk about the shell's consuming the backspace, the result being that code I write never sees the backspace.  This brings me to my question: what happens to the input I provide at the keyboard?  I assume this becomes part of the stdin stream.  Clearly, though, not all the characters I enter make it to my code.  Can someone please explain what processing happens between my keystrokes and the handling of that input by my code?  Also, is there a way for my code to read the stdin buffer before this processing occurs?

I hope these questions make sense.  It took me a while to figure out what I am trying to ask, and I'm not sure I've figured that out completely.


答:
That's because the backspace character never gets to getchar in standard input. When you type backspace, it just cancels the character you just typed.

If you manage to create a text file with backspace characters and feed it to your program that will work, though.

Title: Relationship between the shell and a C program


问:
Inverted Collectors.toMap to add to an ArrayList
I would like to put the frequencies of the numbers in a TreeMap with the frequencies as the keys and the numbers that have that frequency in an ArrayList.

I have two problems:

1) I'm getting a "non-static methods cannot be referenced from a static context" error in the first parameter (AFAIK the stream references an object - what's going on?)

2) There are 4 parameters for Collectors.toMap() - it seems like parameter 4 requires initialization with a new TreeMap>, parameter 2 could be an ArrayList add() function and parameter 3 could be null (maybe). How is this done?

```<code>import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

public class Main {

    public static void main(String[] args) {

        List<Integer> array = Arrays.asList(1, 2, 4, 5, 6, 4, 8, 4, 2, 3);

        Map<Integer, Long> m = array.stream()
            .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

        System.out.println(m);

        TreeMap<Long, List<Integer>> tm = m.entrySet().stream()
            .collect(Collectors.toMap(Map.Entry::getValue, ...));
</code>```

At the moment I can't use see how to get from
https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html to where I need to be.

答:
I wouldn't use streams to create the inverted map. Instead, I would just do:

```<code>Map<Long, List<Integer>> tm = new TreeMap<>();
m.forEach((num, freq) -> tm.computeIfAbsent(freq, k -> new ArrayList<>()).add(num));

System.out.println(tm); // {1=[1, 3, 5, 6, 8], 2=[2], 3=[4]}
</code>```

As the code to create the inverted map is short, you could use Collectors.collectingAndThen to create both the frequencies and inverted map in one step:

```<code>TreeMap<Long, List<Integer>> invertedFrequenciesMap = array.stream()
    .collect(Collectors.collectingAndThen(
        Collectors.groupingBy(Function.identity(), Collectors.counting()),
        map -> {
            TreeMap<Long, List<Integer>> tm = new TreeMap<>();
            map.forEach((num, freq) ->
                    tm.computeIfAbsent(freq, k -> new ArrayList<>()).add(num));
            return tm;
        }));
</code>```

Body:
I would like to put the frequencies of the numbers in a TreeMap with the frequencies as the keys and the numbers that have that frequency in an ArrayList.

I have two problems:

1) I'm getting a "non-static methods cannot be referenced from a static context" error in the first parameter (AFAIK the stream references an object - what's going on?)

2) There are 4 parameters for Collectors.toMap() - it seems like parameter 4 requires initialization with a new TreeMap>, parameter 2 could be an ArrayList add() function and parameter 3 could be null (maybe). How is this done?

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

public class Main {

    public static void main(String[] args) {

        List<Integer> array = Arrays.asList(1, 2, 4, 5, 6, 4, 8, 4, 2, 3);

        Map<Integer, Long> m = array.stream()
            .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

        System.out.println(m);

        TreeMap<Long, List<Integer>> tm = m.entrySet().stream()
            .collect(Collectors.toMap(Map.Entry::getValue, ...));

At the moment I can't use see how to get from
https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html to where I need to be.

Body:
I wouldn't use streams to create the inverted map. Instead, I would just do:

Map<Long, List<Integer>> tm = new TreeMap<>();
m.forEach((num, freq) -> tm.computeIfAbsent(freq, k -> new ArrayList<>()).add(num));

System.out.println(tm); // {1=[1, 3, 5, 6, 8], 2=[2], 3=[4]}

As the code to create the inverted map is short, you could use Collectors.collectingAndThen to create both the frequencies and inverted map in one step:

TreeMap<Long, List<Integer>> invertedFrequenciesMap = array.stream()
    .collect(Collectors.collectingAndThen(
        Collectors.groupingBy(Function.identity(), Collectors.counting()),
        map -> {
            TreeMap<Long, List<Integer>> tm = new TreeMap<>();
            map.forEach((num, freq) ->
                    tm.computeIfAbsent(freq, k -> new ArrayList<>()).add(num));
            return tm;
        }));


答:
The 7 is actually a string, so the 10 is also converted to a string ("10"). Those two strings are compared alphabetically and character by character:

The first characters are: 7 and 1, so it sees that 7 is higher.

To compare numbers, parse the second value to a number using parseInt():

```<code>$("input[name=light]").val() <= parseInt($("#units_home #light").text(), 10)
</code>```

Title: jQuery wrong math

Body:
I have an issue with comparing two fields. In console when I run:

$("input[name=light]").val() <= $("#units_home #light").text()

with Values:

$("input[name=light]").val() = 10
$("#units_home #light").text() = 7

The result is true. Below is a screenshot of my console.

Body:
The 7 is actually a string, so the 10 is also converted to a string ("10"). Those two strings are compared alphabetically and character by character:

The first characters are: 7 and 1, so it sees that 7 is higher.

To compare numbers, parse the second value to a number using parseInt():

$("input[name=light]").val() <= parseInt($("#units_home #light").text(), 10)