问:
Maven Invoker Plugin not detecting failed test
As part of a root parent pom project, several integration tests have been added to test it on sample projects.

The structure of the project folder is as following:

```<code>-root-maven-parent-project
    |- src
    |   |-it
    |      |-sample-project-test1
    |      |-sample-project-test2
    |      |-sample-project-test3
    |      |-settings.xml
    |- pom.xml
</code>```

The main issue is: although the build of sample-project-test2 is wrongly failing (it should not), the build is SUCCESSFUL for the Invoker plugin and the overall build does not fail.

Here is the concerned maven-invoker-plugin configuration:

```<code><profile>
    <id>it-tests</id>
    <build>
        <plugins>
            <!-- Integration tests configuration -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-invoker-plugin</artifactId>
                <version>3.0.0</version>
                <configuration>
                    <streamLogs>true</streamLogs>
                    <goals>
                        <goal>clean</goal>
                        <goal>generate-sources</goal>
                    </goals>
                    <settingsFile>src/it/settings.xml</settingsFile>
                    <failIfNoProjects>true</failIfNoProjects>
                </configuration>
                <executions>
                    <execution>
                        <id>integration-test-release</id>
                        <goals>
                            <goal>install</goal>
                            <goal>integration-test</goal>
                            <goal>verify</goal>
                        </goals>
                        <configuration>
                            <cloneProjectsTo>${project.build.directory}/its/sample-project-test1</cloneProjectsTo>
                            <pom>src/it/sample-project-test1/pom.xml</pom>
                            <properties>
                                <scmBranch>release-something</scmBranch>
                            </properties>
                        </configuration>
                    </execution>
                    <execution>
                        <id>integration-test-hotfix</id>
                        <goals>
                            <goal>install</goal>
                            <goal>integration-test</goal>
                            <goal>verify</goal>
                        </goals>
                        <configuration>
                            <cloneProjectsTo>${project.build.directory}/its/sample-project-test2</cloneProjectsTo>
                            <pom>src/it/sample-project-test2/pom.xml</pom>
                            <properties>
                                <scmBranch>hotfix-something</scmBranch>
                            </properties>
                        </configuration>
                    </execution>
                    <execution>
                        <id>integration-test-master</id>
                        <goals>
                            <goal>install</goal>
                            <goal>integration-test</goal>
                            <goal>verify</goal>
                        </goals>
                        <configuration>
                            <cloneProjectsTo>${project.build.directory}/its/sample-project-test3</cloneProjectsTo>
                            <pom>src/it/sample-project-test3/pom.xml</pom>
                            <properties>
                                <scmBranch>master</scmBranch>
                            </properties>
                        </configuration>
                    </execution>
            </plugin>
        </plugins>
    </build>
</profile>
</code>```

As you can see, multiple executions are configured because each execution would need its own properties. Each execution is also pointing at its own integration test project and pom.

The build is clearly failing for a specific execution:

```<code>[INFO] [INFO] ------------------------------------------------------------------------
[INFO] [INFO] BUILD FAILURE
[INFO] [INFO] ------------------------------------------------------------------------
[INFO] [INFO] Total time: 2.337 s
[INFO] [INFO] Finished at: 2017-07-04T17:35:49+02:00
[INFO] [INFO] Final Memory: 12M/220M
[INFO] [INFO] ------------------------------------------------------------------------
[INFO] [ERROR] Failed to execute goal org.apache.maven.plugins:maven-enforcer-plugin:1.4.1:enforce (enforce-snapshot-management) on project cmp-sample-project-test2: Some Enforcer rules have failed. Look above for specific messages explaining why the rule failed. -> [Help 1]
[INFO] [ERROR]
[INFO] [ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[INFO] [ERROR] Re-run Maven using the -X switch to enable full debug logging.
[INFO] [ERROR]
[INFO] [ERROR] For more information about the errors and possible solutions, please read the following articles:
[INFO] [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException
[INFO]           pom.xml .......................................... FAILED (4.1 s)
[INFO]   The build exited with code 1. See C:\data\git-repositories\root-maven-parent\target\its\sample-project-test2\build.log for details.
</code>```

However, at the bottom of the build we see that the verify goal of the maven-invoker-plugin aggregated the results, flagged the concerned test as Passed and made the build SUCCESS:

```<code>[INFO]
[INFO] --- maven-invoker-plugin:3.0.0:verify (integration-test-release) @ root-maven-parent ---
[INFO] -------------------------------------------------
[INFO] Build Summary:
[INFO]   Passed: 1, Failed: 0, Errors: 0, Skipped: 0
[INFO] -------------------------------------------------
[INFO]
[INFO] --- maven-invoker-plugin:3.0.0:verify (integration-test-hotfix) @ root-maven-parent ---
[INFO] -------------------------------------------------
[INFO] Build Summary:
[INFO]   Passed: 1, Failed: 0, Errors: 0, Skipped: 0
[INFO] -------------------------------------------------
[INFO]
[INFO] --- maven-invoker-plugin:3.0.0:verify (integration-test-master) @ root-maven-parent ---
[INFO] -------------------------------------------------
[INFO] Build Summary:
[INFO]   Passed: 1, Failed: 0, Errors: 0, Skipped: 0
[INFO] -------------------------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
</code>```

Moreover, by only running the failing test from command line as:

```<code>mvn invoker:integration-test@integration-test-hotfix invoker:verify -Pit-tests
</code>```

The sub-build of the test project fails, the output is correctly marked as Failed in the test summary, and the build is correctly ending with FAILURE.

Question: why when executing multiple integration tests using the maven-invoker-plugin, although a test is failed, it is marked as Passed in the test summary and the build does not fail, while running only the isolated test everything fails correctly?

Note: no invoker property file is used.

答:
Issue solved with the following explanation, although I think something could be improved in the behavior of the plugin (see below).

The whole maven-invoker-plugin was reduced to the following configuration:

```<code><profile>
    <id>it-tests</id>
    <build>
        <plugins>
            <!-- Integration tests configuration -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-invoker-plugin</artifactId>
                <version>3.0.0</version>
                <configuration>
                    <streamLogs>true</streamLogs>
                    <goals>
                        <goal>clean</goal>
                        <goal>generate-sources</goal>
                    </goals>
                    <settingsFile>src/it/settings.xml</settingsFile>
                    <failIfNoProjects>true</failIfNoProjects>
                    <cloneProjectsTo>${project.build.directory}/its</cloneProjectsTo>
                </configuration>
                <executions>
                    <execution>
                        <id>integration-test-release</id>
                        <goals>
                            <goal>install</goal>
                            <goal>integration-test</goal>
                            <goal>verify</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</profile>
</code>```

Basically: only one plugin execution, instead of an execution per test, which indeed was verbose and non scalable, but forced by the need of having different values for the same property in each integration test. Apparently, this is not possible via pom configuration and only achievable - unless I am not mistaken - via a test.properties file.
Hence, as a complement to the configuration above, I added in each and every integration test project folder a test.properties file with the following content e.g.:

```<code>scmBranch=master
</code>```

De facto replacing what in the pom.xml file was (as part of an execution of the maven-invoker-plugin:

```<code><properties>
    <scmBranch>master</scmBranch>
</properties>
</code>```

This mechanism (single execution of the plugin + test properties file per test folder) fixed the issue, allowing the build to have multiple integration tests each with its own different value for the same property. Hopefully this solution may help troubleshooting similar issues.

Here is the final result from the build correctly aggregating tests and effectively respecting their sub-build output (while before the build was generating 6 Build Summary of Passed: 1 each time, although not correct).

```<code>[INFO] --- maven-invoker-plugin:3.0.0:verify (pom-integration-test) @ root-maven-parent ---
[INFO] -------------------------------------------------
[INFO] Build Summary:
[INFO]   Passed: 6, Failed: 0, Errors: 0, Skipped: 0
[INFO] -------------------------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
</code>```

However, some questions remain:

Without using the test.properties file, how to achieve the same via pom.xml configuration? Normally, it should only be an alternative, not a mandatory and only possible solution. That's why this is rather a uncomplete feature (a bug?) to me.

Having multiple execution of the plugin results in test summaries at the end of the build which correctly follow the executions order, the number of tests executed (always 1 per execution, in this case), but apparently do not reflect the effective result of each sub-build. Why? This is rather a bug or a misbehavior of the plugin due to an unexpected usage of it, perhaps.

Body:
As part of a root parent pom project, several integration tests have been added to test it on sample projects.

The structure of the project folder is as following:

-root-maven-parent-project
    |- src
    |   |-it
    |      |-sample-project-test1
    |      |-sample-project-test2
    |      |-sample-project-test3
    |      |-settings.xml
    |- pom.xml

The main issue is: although the build of sample-project-test2 is wrongly failing (it should not), the build is SUCCESSFUL for the Invoker plugin and the overall build does not fail.

Here is the concerned maven-invoker-plugin configuration:

<profile>
    <id>it-tests</id>
    <build>
        <plugins>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-invoker-plugin</artifactId>
                <version>3.0.0</version>
                <configuration>
                    <streamLogs>true</streamLogs>
                    <goals>
                        <goal>clean</goal>
                        <goal>generate-sources</goal>
                    </goals>
                    <settingsFile>src/it/settings.xml</settingsFile>
                    <failIfNoProjects>true</failIfNoProjects>
                </configuration>
                <executions>
                    <execution>
                        <id>integration-test-release</id>
                        <goals>
                            <goal>install</goal>
                            <goal>integration-test</goal>
                            <goal>verify</goal>
                        </goals>
                        <configuration>
                            <cloneProjectsTo>${project.build.directory}/its/sample-project-test1</cloneProjectsTo>
                            <pom>src/it/sample-project-test1/pom.xml</pom>
                            <properties>
                                <scmBranch>release-something</scmBranch>
                            </properties>
                        </configuration>
                    </execution>
                    <execution>
                        <id>integration-test-hotfix</id>
                        <goals>
                            <goal>install</goal>
                            <goal>integration-test</goal>
                            <goal>verify</goal>
                        </goals>
                        <configuration>
                            <cloneProjectsTo>${project.build.directory}/its/sample-project-test2</cloneProjectsTo>
                            <pom>src/it/sample-project-test2/pom.xml</pom>
                            <properties>
                                <scmBranch>hotfix-something</scmBranch>
                            </properties>
                        </configuration>
                    </execution>
                    <execution>
                        <id>integration-test-master</id>
                        <goals>
                            <goal>install</goal>
                            <goal>integration-test</goal>
                            <goal>verify</goal>
                        </goals>
                        <configuration>
                            <cloneProjectsTo>${project.build.directory}/its/sample-project-test3</cloneProjectsTo>
                            <pom>src/it/sample-project-test3/pom.xml</pom>
                            <properties>
                                <scmBranch>master</scmBranch>
                            </properties>
                        </configuration>
                    </execution>
            </plugin>
        </plugins>
    </build>
</profile>

As you can see, multiple executions are configured because each execution would need its own properties. Each execution is also pointing at its own integration test project and pom.

The build is clearly failing for a specific execution:

[INFO] [INFO] ------------------------------------------------------------------------
[INFO] [INFO] BUILD FAILURE
[INFO] [INFO] ------------------------------------------------------------------------
[INFO] [INFO] Total time: 2.337 s
[INFO] [INFO] Finished at: 2017-07-04T17:35:49+02:00
[INFO] [INFO] Final Memory: 12M/220M
[INFO] [INFO] ------------------------------------------------------------------------
[INFO] [ERROR] Failed to execute goal org.apache.maven.plugins:maven-enforcer-plugin:1.4.1:enforce (enforce-snapshot-management) on project cmp-sample-project-test2: Some Enforcer rules have failed. Look above for specific messages explaining why the rule failed. -> [Help 1]
[INFO] [ERROR]
[INFO] [ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[INFO] [ERROR] Re-run Maven using the -X switch to enable full debug logging.
[INFO] [ERROR]
[INFO] [ERROR] For more information about the errors and possible solutions, please read the following articles:
[INFO] [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException
[INFO]           pom.xml .......................................... FAILED (4.1 s)
[INFO]   The build exited with code 1. See C:\data\git-repositories\root-maven-parent\target\its\sample-project-test2\build.log for details.

However, at the bottom of the build we see that the verify goal of the maven-invoker-plugin aggregated the results, flagged the concerned test as Passed and made the build SUCCESS:

[INFO]
[INFO] --- maven-invoker-plugin:3.0.0:verify (integration-test-release) @ root-maven-parent ---
[INFO] -------------------------------------------------
[INFO] Build Summary:
[INFO]   Passed: 1, Failed: 0, Errors: 0, Skipped: 0
[INFO] -------------------------------------------------
[INFO]
[INFO] --- maven-invoker-plugin:3.0.0:verify (integration-test-hotfix) @ root-maven-parent ---
[INFO] -------------------------------------------------
[INFO] Build Summary:
[INFO]   Passed: 1, Failed: 0, Errors: 0, Skipped: 0
[INFO] -------------------------------------------------
[INFO]
[INFO] --- maven-invoker-plugin:3.0.0:verify (integration-test-master) @ root-maven-parent ---
[INFO] -------------------------------------------------
[INFO] Build Summary:
[INFO]   Passed: 1, Failed: 0, Errors: 0, Skipped: 0
[INFO] -------------------------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------

Moreover, by only running the failing test from command line as:

mvn invoker:integration-test@integration-test-hotfix invoker:verify -Pit-tests

The sub-build of the test project fails, the output is correctly marked as Failed in the test summary, and the build is correctly ending with FAILURE.

Question: why when executing multiple integration tests using the maven-invoker-plugin, although a test is failed, it is marked as Passed in the test summary and the build does not fail, while running only the isolated test everything fails correctly?

Note: no invoker property file is used.

Body:
Issue solved with the following explanation, although I think something could be improved in the behavior of the plugin (see below).

The whole maven-invoker-plugin was reduced to the following configuration:

<profile>
    <id>it-tests</id>
    <build>
        <plugins>
            <!-- Integration tests configuration -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-invoker-plugin</artifactId>
                <version>3.0.0</version>
                <configuration>
                    <streamLogs>true</streamLogs>
                    <goals>
                        <goal>clean</goal>
                        <goal>generate-sources</goal>
                    </goals>
                    <settingsFile>src/it/settings.xml</settingsFile>
                    <failIfNoProjects>true</failIfNoProjects>
                    <cloneProjectsTo>${project.build.directory}/its</cloneProjectsTo>
                </configuration>
                <executions>
                    <execution>
                        <id>integration-test-release</id>
                        <goals>
                            <goal>install</goal>
                            <goal>integration-test</goal>
                            <goal>verify</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</profile>

Basically: only one plugin execution, instead of an execution per test, which indeed was verbose and non scalable, but forced by the need of having different values for the same property in each integration test. Apparently, this is not possible via pom configuration and only achievable - unless I am not mistaken - via a test.properties file.
Hence, as a complement to the configuration above, I added in each and every integration test project folder a test.properties file with the following content e.g.:

scmBranch=master

De facto replacing what in the pom.xml file was (as part of an execution of the maven-invoker-plugin:

<properties>
    <scmBranch>master</scmBranch>
</properties>

This mechanism (single execution of the plugin + test properties file per test folder) fixed the issue, allowing the build to have multiple integration tests each with its own different value for the same property. Hopefully this solution may help troubleshooting similar issues.

Here is the final result from the build correctly aggregating tests and effectively respecting their sub-build output (while before the build was generating 6 Build Summary of Passed: 1 each time, although not correct).

[INFO] --- maven-invoker-plugin:3.0.0:verify (pom-integration-test) @ root-maven-parent ---
[INFO] -------------------------------------------------
[INFO] Build Summary:
[INFO]   Passed: 6, Failed: 0, Errors: 0, Skipped: 0
[INFO] -------------------------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------

However, some questions remain:

Without using the test.properties file, how to achieve the same via pom.xml configuration? Normally, it should only be an alternative, not a mandatory and only possible solution. That's why this is rather a uncomplete feature (a bug?) to me.

Having multiple execution of the plugin results in test summaries at the end of the build which correctly follow the executions order, the number of tests executed (always 1 per execution, in this case), but apparently do not reflect the effective result of each sub-build. Why? This is rather a bug or a misbehavior of the plugin due to an unexpected usage of it, perhaps.


来源: stackexchange

问:
How to send an HTTP request using Telnet
How to get a web page's content using Telnet?

For example, the content of https://stackoverflow.com/questions.

答:
For posterity, your question was how to send an http request to https://stackoverflow.com/questions. The real answer is: you cannot with telnet, cause this is an https-only reachable url.

So, you might want to use openssl instead of telnet, like this for instance

```<code>$ openssl s_client -connect stackoverflow.com:443
...
---
GET /questions HTTP/1.1
Host: stackoverflow.com
</code>```

This will give you the https response.

ContentLicense: CC BY-SA 4.0

Body:
For posterity, your question was how to send an http request to https://stackoverflow.com/questions. The real answer is: you cannot with telnet, cause this is an https-only reachable url.

So, you might want to use openssl instead of telnet, like this for instance

$ openssl s_client -connect stackoverflow.com:443
...
---
GET /questions HTTP/1.1
Host: stackoverflow.com

This will give you the https response.

ContentLicense: CC BY-SA 3.0


问:
Change `font-family` in Angular Chart.js
How to change font-family in Angular Chart and set a custom font for labels?

答:
You can set a custom font-family for the chart, in the following way ...

```<code>Chart.defaults.global.defaultFontFamily = 'Verdana';
</code>```

add this, at the beginning of your script (before initializing the app)

Body:
You can set a custom font-family for the chart, in the following way ...

Chart.defaults.global.defaultFontFamily = 'Verdana';

add this, at the beginning of your script (before initializing the app)


问:
How to collect items in Laravel eloquent query?
I am trying to fetch all profile data for user. And user can have multiple files uploaded for the server which can give the user badges. I have 2 users in my test environment and 1 of the users has 3 files. Now when I return JSON from the controller I get three results, but I would like to merge or somehow combine so the one user could have all data in one object.

Here is the JSON I currently get returned

```<code>[
    {
        "id":1,
        "avatar":"john.jpg",
        "role":2,
        "first_name":"John",
        "last_name":"Doe",
        "user_name":"johndoe",
        "account_status":2,
        "one_child":"6",
        "introduction":"test",
        "file_type":1,
        "file":"1498725633.docx",
        "status":2,
        "lat":59.44,
        "lng":24.74,
        "rating":"5",
        "recommended":"1",
        "rating_count":2,
        "distance":0.29988841983648
    },
    {
        "id":1,
        "avatar":"john.jpg",
        "role":2,
        "first_name":"Joe",
        "last_name":"Doe",
        "user_name":"johndoe",
        "account_status":2,
        "one_child":"6",
        "introduction":"test",
        "file_type":4,
        "file":"118771941-merged.mp4",
        "status":1,
        "lat":59.44,
        "lng":24.74,
        "rating":"5",
        "recommended":"1",
        "rating_count":2,
        "distance":0.29988841983648
    },
    {
        "id":4,
        "avatar":"capture.JPG",
        "role":2,
        "first_name":"Jane",
        "last_name":"Doe",
        "user_name":"janedoe",
        "account_status":2,
        "one_child":"4",
        "introduction":"Test",
        "file_type":2,
        "file":"1498732136.docx",
        "status":1,
        "lat":59.46,
        "lng":24.83,
        "rating":"3",
        "recommended":"2",
        "rating_count":2,
        "distance":5.5651349391591
    }
]
</code>```

As you can see john doe has two files but I would like to have all the files and file types under one object so there would be only one John and one Jane object atm.

Here is my raw sql extracted from laravel

```<code>select
   `users`.`id` as `id`,
   `users`.`avatar`,
   `users`.`role`,
   `users`.`first_name`,
   `users`.`last_name`,
   `users`.`user_name`,
   `users`.`account_status`,
   `user_wage_preferences`.`one_child`,
   `user_introductions`.`introduction`,
   `user_files`.`file_type`,
   `user_files`.`file`,
   `user_files`.`status` as `status`,
   `user_contact_informations`.`lat`,
   `user_contact_informations`.`lng`,
   ROUND(AVG( user_reviews.rating )) AS rating,
   SUM(user_reviews.recommended) as recommended,
   COUNT(user_reviews.id) as rating_count,
   `user_files`.`status`,
   (
      6371 * acos( cos( radians(59.4424504) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(24.7377842) ) + sin( radians(59.4424504) ) * sin( radians(lat) ) )
   )
   AS distance
from
   `users`
   inner join
      `user_files`
      on `users`.`id` = `user_files`.`user_id`
   left join
      `user_reviews`
      on `users`.`id` = `user_reviews`.`nanny_id`
   inner join
      `user_introductions`
      on `users`.`id` = `user_introductions`.`user_id`
   inner join
      `user_wage_preferences`
      on `users`.`id` = `user_wage_preferences`.`user_id`
   inner join
      `user_contact_informations`
      on `users`.`id` = `user_contact_informations`.`user_id`
where
   `users`.`role` = ?
   and `users`.`account_status` = ?
group by
   `users`.`id`,
   `users`.`avatar`,
   `users`.`role`,
   `users`.`first_name`,
   `users`.`last_name`,
   `users`.`user_name`,
   `user_files`.`status`,
   `users`.`id`,
   `user_contact_informations`.`lat`,
   `user_contact_informations`.`lng`,
   `user_wage_preferences`.`one_child`,
   `user_introductions`.`introduction`,
   `user_files`.`file_type`,
   `user_files`.`file`
having
   `recommended` > ?
order by
   `distance` asc jquery - 3.2.1.min.js:2 Uncaught TypeError: Cannot use 'in' operator to search for 'length' in
   select
      `users`.`id` as `id`,
      `users`.`avatar`,
      `users`.`role`,
      `users`.`first_name`,
      `users`.`last_name`,
      `users`.`user_name`,
      `users`.`account_status`,
      `user_wage_preferences`.`one_child`,
      `user_introductions`.`introduction`,
      `user_files`.`file_type`,
      `user_files`.`file`,
      `user_files`.`status` as `status`,
      `user_contact_informations`.`lat`,
      `user_contact_informations`.`lng`,
      ROUND(AVG( user_reviews.rating )) AS rating,
      SUM(user_reviews.recommended) as recommended,
      COUNT(user_reviews.id) as rating_count,
      `user_files`.`status`,
      (
         6371 * acos( cos( radians(59.4424504) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(24.7377842) ) + sin( radians(59.4424504) ) * sin( radians(lat) ) )
      )
      AS distance
   from
      `users`
      inner join
         `user_files`
         on `users`.`id` = `user_files`.`user_id`
      left join
         `user_reviews`
         on `users`.`id` = `user_reviews`.`nanny_id`
      inner join
         `user_introductions`
         on `users`.`id` = `user_introductions`.`user_id`
      inner join
         `user_wage_preferences`
         on `users`.`id` = `user_wage_preferences`.`user_id`
      inner join
         `user_contact_informations`
         on `users`.`id` = `user_contact_informations`.`user_id`
   where
      `users`.`role` = ?
      and `users`.`account_status` = ?
   group by
      `users`.`id`,
      `users`.`avatar`,
      `users`.`role`,
      `users`.`first_name`,
      `users`.`last_name`,
      `users`.`user_name`,
      `user_files`.`status`,
      `users`.`id`,
      `user_contact_informations`.`lat`,
      `user_contact_informations`.`lng`,
      `user_wage_preferences`.`one_child`,
      `user_introductions`.`introduction`,
      `user_files`.`file_type`,
      `user_files`.`file`
   having
      `recommended` > ?
   order by
      `distance` asc
</code>```

I have all the connection made in my migrations so user_id references id in users table. How could I fetch all the files under one user object?

答:
Instead of joining the users and user_files tables in the query you can add a relation to them.

In your case to the users model would have a function something like this:

```<code>public function files()
{
    return $this->hasMany('App\UserFiles', 'user_id');
    //Where UserFiles is the name of the model of the user_files table
    //and user_id is the foreign key
}
</code>```

Once you have this relation set up you can add the files relation into your query by using the with:

```<code>Users::with('files')->where(...)->orderBy(...)->get();
</code>```

This will load the files into the user objects like so:

```<code> {
    "id":1,
    "avatar":"john.jpg",
    "role":2,
    "first_name":"John",
    "last_name":"Doe",
    "user_name":"johndoe",
    "account_status":2,
    "one_child":"6",
    "introduction":"test",
    "files": [
        {
            //File Object
        },
        {
            //File Object
        }
    ],
    "lat":59.44,
    "lng":24.74,
    "rating":"5",
    "recommended":"1",
    "rating_count":2,
    "distance":0.29988841983648
}
</code>```

Body:
I am trying to fetch all profile data for user. And user can have multiple files uploaded for the server which can give the user badges. I have 2 users in my test environment and 1 of the users has 3 files. Now when I return JSON from the controller I get three results, but I would like to merge or somehow combine so the one user could have all data in one object.

Here is the JSON I currently get returned

[
    {
        "id":1,
        "avatar":"john.jpg",
        "role":2,
        "first_name":"John",
        "last_name":"Doe",
        "user_name":"johndoe",
        "account_status":2,
        "one_child":"6",
        "introduction":"test",
        "file_type":1,
        "file":"1498725633.docx",
        "status":2,
        "lat":59.44,
        "lng":24.74,
        "rating":"5",
        "recommended":"1",
        "rating_count":2,
        "distance":0.29988841983648
    },
    {
        "id":1,
        "avatar":"john.jpg",
        "role":2,
        "first_name":"Joe",
        "last_name":"Doe",
        "user_name":"johndoe",
        "account_status":2,
        "one_child":"6",
        "introduction":"test",
        "file_type":4,
        "file":"118771941-merged.mp4",
        "status":1,
        "lat":59.44,
        "lng":24.74,
        "rating":"5",
        "recommended":"1",
        "rating_count":2,
        "distance":0.29988841983648
    },
    {
        "id":4,
        "avatar":"capture.JPG",
        "role":2,
        "first_name":"Jane",
        "last_name":"Doe",
        "user_name":"janedoe",
        "account_status":2,
        "one_child":"4",
        "introduction":"Test",
        "file_type":2,
        "file":"1498732136.docx",
        "status":1,
        "lat":59.46,
        "lng":24.83,
        "rating":"3",
        "recommended":"2",
        "rating_count":2,
        "distance":5.5651349391591
    }
]

As you can see john doe has two files but I would like to have all the files and file types under one object so there would be only one John and one Jane object atm.

Here is my raw sql extracted from laravel

select
   `users`.`id` as `id`,
   `users`.`avatar`,
   `users`.`role`,
   `users`.`first_name`,
   `users`.`last_name`,
   `users`.`user_name`,
   `users`.`account_status`,
   `user_wage_preferences`.`one_child`,
   `user_introductions`.`introduction`,
   `user_files`.`file_type`,
   `user_files`.`file`,
   `user_files`.`status` as `status`,
   `user_contact_informations`.`lat`,
   `user_contact_informations`.`lng`,
   ROUND(AVG( user_reviews.rating )) AS rating,
   SUM(user_reviews.recommended) as recommended,
   COUNT(user_reviews.id) as rating_count,
   `user_files`.`status`,
   (
      6371 * acos( cos( radians(59.4424504) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(24.7377842) ) + sin( radians(59.4424504) ) * sin( radians(lat) ) )
   )
   AS distance
from
   `users`
   inner join
      `user_files`
      on `users`.`id` = `user_files`.`user_id`
   left join
      `user_reviews`
      on `users`.`id` = `user_reviews`.`nanny_id`
   inner join
      `user_introductions`
      on `users`.`id` = `user_introductions`.`user_id`
   inner join
      `user_wage_preferences`
      on `users`.`id` = `user_wage_preferences`.`user_id`
   inner join
      `user_contact_informations`
      on `users`.`id` = `user_contact_informations`.`user_id`
where
   `users`.`role` = ?
   and `users`.`account_status` = ?
group by
   `users`.`id`,
   `users`.`avatar`,
   `users`.`role`,
   `users`.`first_name`,
   `users`.`last_name`,
   `users`.`user_name`,
   `user_files`.`status`,
   `users`.`id`,
   `user_contact_informations`.`lat`,
   `user_contact_informations`.`lng`,
   `user_wage_preferences`.`one_child`,
   `user_introductions`.`introduction`,
   `user_files`.`file_type`,
   `user_files`.`file`
having
   `recommended` > ?
order by
   `distance` asc jquery - 3.2.1.min.js:2 Uncaught TypeError: Cannot use 'in' operator to search for 'length' in
   select
      `users`.`id` as `id`,
      `users`.`avatar`,
      `users`.`role`,
      `users`.`first_name`,
      `users`.`last_name`,
      `users`.`user_name`,
      `users`.`account_status`,
      `user_wage_preferences`.`one_child`,
      `user_introductions`.`introduction`,
      `user_files`.`file_type`,
      `user_files`.`file`,
      `user_files`.`status` as `status`,
      `user_contact_informations`.`lat`,
      `user_contact_informations`.`lng`,
      ROUND(AVG( user_reviews.rating )) AS rating,
      SUM(user_reviews.recommended) as recommended,
      COUNT(user_reviews.id) as rating_count,
      `user_files`.`status`,
      (
         6371 * acos( cos( radians(59.4424504) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(24.7377842) ) + sin( radians(59.4424504) ) * sin( radians(lat) ) )
      )
      AS distance
   from
      `users`
      inner join
         `user_files`
         on `users`.`id` = `user_files`.`user_id`
      left join
         `user_reviews`
         on `users`.`id` = `user_reviews`.`nanny_id`
      inner join
         `user_introductions`
         on `users`.`id` = `user_introductions`.`user_id`
      inner join
         `user_wage_preferences`
         on `users`.`id` = `user_wage_preferences`.`user_id`
      inner join
         `user_contact_informations`
         on `users`.`id` = `user_contact_informations`.`user_id`
   where
      `users`.`role` = ?
      and `users`.`account_status` = ?
   group by
      `users`.`id`,
      `users`.`avatar`,
      `users`.`role`,
      `users`.`first_name`,
      `users`.`last_name`,
      `users`.`user_name`,
      `user_files`.`status`,
      `users`.`id`,
      `user_contact_informations`.`lat`,
      `user_contact_informations`.`lng`,
      `user_wage_preferences`.`one_child`,
      `user_introductions`.`introduction`,
      `user_files`.`file_type`,
      `user_files`.`file`
   having
      `recommended` > ?
   order by
      `distance` asc

I have all the connection made in my migrations so user_id references id in users table. How could I fetch all the files under one user object?

Body:
Instead of joining the users and user_files tables in the query you can add a relation to them.

In your case to the users model would have a function something like this:

public function files()
{
    return $this->hasMany('App\UserFiles', 'user_id');
    //Where UserFiles is the name of the model of the user_files table
    //and user_id is the foreign key
}

Once you have this relation set up you can add the files relation into your query by using the with:

Users::with('files')->where(...)->orderBy(...)->get();

This will load the files into the user objects like so:

 {
    "id":1,
    "avatar":"john.jpg",
    "role":2,
    "first_name":"John",
    "last_name":"Doe",
    "user_name":"johndoe",
    "account_status":2,
    "one_child":"6",
    "introduction":"test",
    "files": [
        {
            //File Object
        },
        {
            //File Object
        }
    ],
    "lat":59.44,
    "lng":24.74,
    "rating":"5",
    "recommended":"1",
    "rating_count":2,
    "distance":0.29988841983648
}


问:
Extend array modal editor
Is it possible to extend the array modal dialog without overwriting the array-modal.js (apostrophe-schemas/public/js)?

I'm trying to create a link array in the global module, for that i created:

```<code>...
name: 'links',
label: 'Links',
type: 'array',
titleField: 'title',
schema: [{
  name: 'title',
  label: 'Title',
  type: 'string'
}, {
  name: 'url',
  label: 'Url',
  type: 'url'
}, {
  name: '_page',
  label: 'Page',
  type: 'joinByOne',
  withType: 'apostrophe-page',
  idField: 'pageId',
  filter: {
    projection: {
      title: 1,
      slug: 1
    }
  }
}]
...
</code>```

Now i want to set the title field and disable the url field if a Page is
selected. Or use the title and url field.
If i register a script like this:

```<code>apos.define('apostrophe-array-editor-modal', {
  extend: 'apostrophe-modal',
  source: 'arrayEditor',
  ...
});
</code>```

i overwrite the orginal array-modal.js, but i only want to register a change handler and check the inputs before save.

My goal is a list of (footer/static) links the admin can edit in the global section and i can use them in several pages.

Thank you!

答:
My recommendation would be to make some sort of type field for each link where the editor makes a choice between an internal page join and an external URL.

select schema fields have a showFields parameter that can hide/show parts of a schema form based on the selection made, check out the documentation here http://apostrophecms.org/docs/tutorials/getting-started/schema-guide.html#code-select-code

Your code would look something like

```<code>  name: 'links',
  label: 'Links',
  type: 'array',
  titleField: 'title',
  schema: [{
    name: 'title',
    label: 'Title',
    type: 'string'
  }, {
    name: 'linkType',
    type: 'select',
    label: 'Type',
    choices: [{
      label: 'External',
      value: 'external',
      showFields: ['url']
    }, {
      label: 'Internal',
      value: 'internal',
      showFields: ['_page']
    }]
  }, {
    name: 'url',
    label: 'Url',
    type: 'url'
  }, {
    name: '_page',
    label: 'Page',
    type: 'joinByOne',
    withType: 'apostrophe-page',
    idField: 'pageId',
    filter: {
      projection: {
        title: 1,
        slug: 1
      }
    }
  }]
</code>```

In your template you can always check the value of linkType to make markup decisions.

Title: Extend array modal editor

Body:
Is it possible to extend the array modal dialog without overwriting the array-modal.js (apostrophe-schemas/public/js)?

I'm trying to create a link array in the global module, for that i created:

...
name: 'links',
label: 'Links',
type: 'array',
titleField: 'title',
schema: [{
  name: 'title',
  label: 'Title',
  type: 'string'
}, {
  name: 'url',
  label: 'Url',
  type: 'url'
}, {
  name: '_page',
  label: 'Page',
  type: 'joinByOne',
  withType: 'apostrophe-page',
  idField: 'pageId',
  filter: {
    projection: {
      title: 1,
      slug: 1
    }
  }
}]
...

Now i want to set the title field and disable the url field if a Page is
selected. Or use the title and url field.
If i register a script like this:

apos.define('apostrophe-array-editor-modal', {
  extend: 'apostrophe-modal',
  source: 'arrayEditor',
  ...
});

i overwrite the orginal array-modal.js, but i only want to register a change handler and check the inputs before save.

My goal is a list of (footer/static) links the admin can edit in the global section and i can use them in several pages.

Thank you!

Body:
My recommendation would be to make some sort of type field for each link where the editor makes a choice between an internal page join and an external URL.

select schema fields have a showFields parameter that can hide/show parts of a schema form based on the selection made, check out the documentation here http://apostrophecms.org/docs/tutorials/getting-started/schema-guide.html#code-select-code

Your code would look something like

  name: 'links',
  label: 'Links',
  type: 'array',
  titleField: 'title',
  schema: [{
    name: 'title',
    label: 'Title',
    type: 'string'
  }, {
    name: 'linkType',
    type: 'select',
    label: 'Type',
    choices: [{
      label: 'External',
      value: 'external',
      showFields: ['url']
    }, {
      label: 'Internal',
      value: 'internal',
      showFields: ['_page']
    }]
  }, {
    name: 'url',
    label: 'Url',
    type: 'url'
  }, {
    name: '_page',
    label: 'Page',
    type: 'joinByOne',
    withType: 'apostrophe-page',
    idField: 'pageId',
    filter: {
      projection: {
        title: 1,
        slug: 1
      }
    }
  }]

In your template you can always check the value of linkType to make markup decisions.


问:
Running a matlab mfile on a remote cluster
I am solving a nonlinear partial differential equation in Matlab. My code calls the fft2 and ifft2 commands many times. So I want to use a GPU of a cluster to speed up the computations. I have prepared my codes for gpu using gpuArray and gather. However, I am quite naive in cluster using and the only thing I know is that I should use an ssh terminal using putty and Matlab is not installed on the cluster and my codes need to be compiled first.
1st of all I would like to know how I should compile my Matlab codes
And 2nd, how to run this code on this remote cluster? what are the commands?

Many thanks in advance for your help

答:
First, in order to utilize the GPU you need to change fft2(x) into gather(fft2(gpuArray(x))). Similarly, ifft2(x) becomes gather(ifft2(gpuArray(x))).

Assuming you're not talking about using the cluster as a worker for parallel computation, you can run MATLAB commands from a linux terminal using a command of the form matlab -r 'myfunction'. Note that myfunction.m must exist in the current working directory or MATLAB's default path.

Once you've modified your script to use the GPU, ssh into the cluster, change to the directory containing your script and run matlab -r command.


问:
How can I find the maximum value and its index in array in MATLAB?
Suppose I have an array, a = [2 5 4 7]. What is the function returning the maximum value and its index?

For example, in my case that function should return 7 as the maximum value and 4 as the index.

答:
3D case

Modifying Mohsen's answer for 3D array:

```<code>[M,I] = max (A(:));
[ind1, ind2, ind3] = ind2sub(size(A),I)
</code>```

Body:
3D case

Modifying Mohsen's answer for 3D array:

[M,I] = max (A(:));
[ind1, ind2, ind3] = ind2sub(size(A),I)


问:
How to get a std::list<T>::iterator from an element of that list?
Given a std:: list

```<code>std::list< int > myList
</code>```

and a reference (or a pointer) to an element in that list

```<code>int& myElement    |     int* pElement
</code>```

So, basically I know the address of that element

How can I get an std::list<int>::iterator to that element efficiently?

A slow yet working example is

```<code>const_iterator it
for( it = myList.begin(); it != &myElement; ++it)
{
    // do nothing, for loop terminates if "it" points to "myElem"
}
</code>```

Is there a quicker way? like

```<code>const_iterator it = magicToIteratorConverter( myList, myElem )
</code>```

Case of vector (but I need list):

For a vector, you could do the following:

```<code>const int* pStart = &myVector[0] // address of first element
const int* pElement = &myElem; // address of my element
const idx = static_cast< int >( pElement- pStart ); // no need to divide by size of an elem

std::vector< int >::iterator it = myVector.begin() + idx;
</code>```

Case of std::list:

答:
Given a list, you can only get to anything by starting from one end walking through it, making sure you don't go beyond the end.

```<code>const_iterator it, end;
for( it = myList.begin(), end = myList.end(); it!=end && it != &myElement; ++it)
{
    // do nothing, for loop terminates if "it" points to "myElem"
      // or if we don't find your element.
}
</code>```

Of course, you could use a standard algorithm, like std::find to look for it.

Alternatively, you could keep hold of the iterator when you insert, and under many conditions it will still be valid later on.

If you want lookup speed, you should probably use something other than a list.

If you have something like

```<code>int x = 42;
int * this_might_be_handy = &x;
myList.insert(x);
</code>```

myList now has a COPY of the number - it has the value 42, but in a different memory location.

If you kept pointers to ints in the list, that would be different. getting the value from the front of the list and looking at the address will not give the same address as x.

But you would have to manage them smartly.

Body:
Given a std:: list

std::list< int > myList

and a reference (or a pointer) to an element in that list

int& myElement    |     int* pElement

So, basically I know the address of that element

How can I get an std::list<int>::iterator to that element efficiently?

A slow yet working example is

const_iterator it
for( it = myList.begin(); it != &myElement; ++it)
{
    // do nothing, for loop terminates if "it" points to "myElem"
}

Is there a quicker way? like

const_iterator it = magicToIteratorConverter( myList, myElem )

Case of vector (but I need list):

For a vector, you could do the following:

const int* pStart = &myVector[0] // address of first element
const int* pElement = &myElem; // address of my element
const idx = static_cast< int >( pElement- pStart ); // no need to divide by size of an elem

std::vector< int >::iterator it = myVector.begin() + idx;

Case of std::list:

Body:
Given a list, you can only get to anything by starting from one end walking through it, making sure you don't go beyond the end.

const_iterator it, end;
for( it = myList.begin(), end = myList.end(); it!=end && it != &myElement; ++it)
{
    // do nothing, for loop terminates if "it" points to "myElem"
      // or if we don't find your element.
}

Of course, you could use a standard algorithm, like std::find to look for it.

Alternatively, you could keep hold of the iterator when you insert, and under many conditions it will still be valid later on.

If you want lookup speed, you should probably use something other than a list.

If you have something like

int x = 42;
int * this_might_be_handy = &x;
myList.insert(x);

myList now has a COPY of the number - it has the value 42, but in a different memory location.

If you kept pointers to ints in the list, that would be different. getting the value from the front of the list and looking at the address will not give the same address as x.

But you would have to manage them smartly.


问:
Knex select from multiple tables
I want to run following SQL with knex:

```<code>select * from (
  (select * from foo)
  union all
  (select * from bar)) as biz limit 10 offset 20;
</code>```

Is there a way to do it without knex.raw?

答:
knex does support union and unionAll. it's documented

```<code>knex.select().from(function() {
    this.select().from('foo')
        .unionAll(function() {
            this.select().from('bar')
        }).as('biz')
}).limit(10).offset(20).toString()
</code>```

Output:

```<code>select * from (select * from `foo` union all select * from `bar`) as `biz` limit 10 offset 20
</code>```

Title: Knex select from multiple tables

Body:
I want to run following SQL with knex:

select * from (
  (select * from foo)
  union all
  (select * from bar)) as biz limit 10 offset 20;

Is there a way to do it without knex.raw?

Body:
knex does support union and unionAll. it's documented

knex.select().from(function() {
    this.select().from('foo')
        .unionAll(function() {
            this.select().from('bar')
        }).as('biz')
}).limit(10).offset(20).toString()

Output:

select * from (select * from `foo` union all select * from `bar`) as `biz` limit 10 offset 20


问:
Git not moving to a specific branch
I cloned a project that I'm working on. Then I'm trying to move to a specific branch using git checkout branch_name and nothing happens, the terminal just add a blank line. After awhile the terminal is in the same state. Nothing changes.

I cloned it using git lfs clone https_url_to_repo

What I tried:

Clone it again

Reinstall git in my mac

Nothing worked.

```<code>Git version = 2.13.2 (installed using homebrew)
Git-lfs version = 1.5.5 (installed using homebrew)
</code>```

Note: I can move to other branches, the issue is just with that one.
Maybe the issue was caused because there was an interruption in my internet connection while moving to that branch.

答:
Summary:

This is most likely due to a buglet in Git-LFS, the fix (or at least workaround) for which is in a slightly newer version of Git-LFS.

See https://github.com/git-lfs/git-lfs/issues/1880 and https://github.com/git-lfs/git-lfs/pull/1932 for a a description of the bug and fix/work-around.

Here's my capsule summary though:

When you use Git-LFS, your standard Git configuration is modified to use Git's clean and smudge filtering processes.  A smudge filter is meant to "dirty up" a file as it comes out of the version control system, and a clean filter is its logical opposite: it cleans up the file for storage inside the VCS.  To use such filters, you must mark up both your .git/config file and your .gitattributes file; Git-LFS does this marking-up for you automatically.

As a somewhat silly example, some people like to have each line end with CR-LF instead of just a newline (LF-only), yet store the version-controlled version of the file with newline endings.  Git can do this directly (using end-of-line filters) but if for some reason you wanted to write a program to do it yourself, you would use the smudge filter to replace LF-only with CR-LF, and use the clean filter to replace CR-LF with LF-only.  Your work-tree files would then have your desired Windows-style line endings, while your committed files would have the desired Linux-style line endings.

More practically, some people like to expand keywords (RCS- or CVS-like $Id$ for instance).  Git also includes a built-in ident filter that does this specifically for $Id$.  The expansion is done when extracting files to the work-tree (as if by a smudge filter), and removed—put back to just $Id$—when adding files to go into new commits.1  If you wanted to handle more keywords, e.g., $Log$,2 you would have to write your own filters.

What Git-LFS does is to use (abuse?) the clean and smudge filters to replace large files with specially decorated hash IDs that act as "pointers" to external large-file storage.  This way, Git never stores—or even sees, in a sense—the large files at all.  It sees, and stores, only these decorated hashes.  The Git-LFS filters are responsible for replacing a funny hash with the actual large-file contents on checkout, and replacing the large-file contents with a funny hash (new or re-used as appropriate) at git add time.

But there is a technical glitch: Git uses pipes to implement both smudge and clean filters.  (These pipes have become quite fancy recently; see the Long Running Filter Process section of the gitattributes documentation.)  The Git-LFS code and the Git code itself must be careful not to "constipate" the pipes ... and, well, it wasn't.  (See my answer to live output from subprocess command for some of the details.)

1Specifically, smudge filters (along with ident and any end-of-line hacking) are applied to files when they are copied from Git's index to the work-tree.  Clean filters are applied to files when they are copied from work-tree into the index.  Since committed trees are built only from files as found in the index, and the index version is always "clean", all commits are always clean as well.

2What $Log$ does in RCS and CVS is to expand to the entire log-message history of the file—essentially, all the commits that touched the file, except that RCS and CVS are file-based rather than commit-based—so that the history is there while you are editing the file itself.  Having actually used such things before, I am firmly convinced that this is a bad idea: this kind of metadata belongs only in the version control system (which, like Git or Mercurial, should be distributed with developers given access to the entire repository).  Nonetheless, there are people who like this, and it is technically possible to do it in Git.

Title: Git not moving to a specific branch

Body:
I cloned a project that I'm working on. Then I'm trying to move to a specific branch using git checkout branch_name and nothing happens, the terminal just add a blank line. After awhile the terminal is in the same state. Nothing changes.

I cloned it using git lfs clone https_url_to_repo

What I tried:

Clone it again

Reinstall git in my mac

Nothing worked.

Git version = 2.13.2 (installed using homebrew)
Git-lfs version = 1.5.5 (installed using homebrew)

Note: I can move to other branches, the issue is just with that one.
Maybe the issue was caused because there was an interruption in my internet connection while moving to that branch.


问:
vba code to load text file into ms access table
file data image I need to import a text file data into an Access table. Below is my VBA code

```<code>DoCmd.TransferText transfertype:=acImportDelim, _
  TransferType:=acImportDelim, _
  SpecificationName:="Generic", _
  FileName:="C:\Users\Documents\Rawfile.txt", _
  hasfieldnames:=False
</code>```

Data is loading into table.
But when column headers/names order changes in raw file then this TransferText loading data into table as per column headers/names order specified in 'SpecificationName' and doesn't cross check column names in file, resulting the one column data loading into another column in table.

Is there any alternate solution while loading data it should check column names and load data into correct column headers/names ?

Note: column header names doesn't change in file but only column header order may changes in raw file.

答:
I've had this issue with the import specs before.  They're great for layouts that do not change.  There's a couple alternatives, one is via Access's SQL.</p>

```<code>'RawFile may have to be renamed as .CSV vs .TXT

DoCmd.RunSQL "SELECT ColumnIKnow1, ColumnIKnow2, ColumnIKnow3 INTO TargetTable FROM [Text;DATABASE=C:\Users\Documents\;HDR=Yes].Rawfile.csv"
</code>```

Body:
file data image I need to import a text file data into an Access table. Below is my VBA code

DoCmd.TransferText transfertype:=acImportDelim, _
  TransferType:=acImportDelim, _
  SpecificationName:="Generic", _
  FileName:="C:\Users\Documents\Rawfile.txt", _
  hasfieldnames:=False

Data is loading into table.
But when column headers/names order changes in raw file then this TransferText loading data into table as per column headers/names order specified in 'SpecificationName' and doesn't cross check column names in file, resulting the one column data loading into another column in table.

Is there any alternate solution while loading data it should check column names and load data into correct column headers/names ?

Note: column header names doesn't change in file but only column header order may changes in raw file.

Body:
I've had this issue with the import specs before.  They're great for layouts that do not change.  There's a couple alternatives, one is via Access's SQL.

'RawFile may have to be renamed as .CSV vs .TXT

DoCmd.RunSQL "SELECT ColumnIKnow1, ColumnIKnow2, ColumnIKnow3 INTO TargetTable FROM [Text;DATABASE=C:\Users\Documents\;HDR=Yes].Rawfile.csv"


问:
Why isn't it updating
```<code>User.update({_id: req.params.id}, userTemp).then(function(){
    User.findOne({_id: req.params.id}).then(function(user){
      res.send(user);

    });
  });
</code>```

So this code is running but it doesn't actually change the value in the database. I should replace the previous user with a new one however it does not.

答:
As you can find out in documentation update can be used on document when you already have that document: doc

For your example I would rather use findByIdAndUpdate like this:

```<code>User.findByIdAndUpdate(req.params.id, userTemp, function(err, user) {
  res.send(user);
})
</code>```

Title: Why isn't it updating

Body:
User.update({_id: req.params.id}, userTemp).then(function(){
    User.findOne({_id: req.params.id}).then(function(user){
      res.send(user);

    });
  });

So this code is running but it doesn't actually change the value in the database. I should replace the previous user with a new one however it does not.

Body:
As you can find out in documentation update can be used on document when you already have that document: doc

For your example I would rather use findByIdAndUpdate like this:

User.findByIdAndUpdate(req.params.id, userTemp, function(err, user) {
  res.send(user);
})


问:
Error calling function _this3.xxxxx() is not a function
Hi I am getting the following error when clicking on a TouchableOpacity that is created within a loop.

The TouchableOpacity that calls it is here

```<code>    constructor() {

    super();

    this.pressRowContact = this.pressRowContact.bind(this);
    this.fetchData = this.fetchData.bind(this);
    this.goBack = this.goBack.bind(this);
    this.onAddedContactPress = this.onAddedContactPress.bind(this);
    this.sendMessage = this.sendMessage.bind(this);

    this.state = {
      loadingVisible: false,
      inputText: "",
      arrayContactsSelected: [],
      dataContactList: [],
      showContactList: false,
    };
  }

  componentDidMount() {
    this.fetchData();
  }

  onChangeTextHandler = (e) => {
    this.textInputValue = e;
  }

  onAddedContactPress(){}

  render() {

    const { navigate } = this.props.navigation;

    console.log(this.state.showContactList);

    if(this.state.showContactList == true){
        var contactListView = <View style={styles.contactListWrapper}>
            <FlatList
                data = {this.state.dataContactList}
                renderItem={({item}) => <TouchableOpacity onPress={() => this.pressRowContact( item )} >
                <View style={styles.contactRow}>
                    <View style={styles.standardProfilePicWrapper}>
                        <Image source={require('../../images/demo/Profile/sample2.jpg')} style={{width: 30, height: 30}}/>
                    </View>
                    <Text>Someone Name Here</Text>
                </View>
            </TouchableOpacity>}
            />
        </View>
    }else {
        var contactListView;
    }

    var selectedUsers = this.state.arrayContactsSelected.map(function(item) {
        return (
            <TouchableOpacity onPress={() => this.onAddedContactPress(item)} key={item.userID} style={styles.selectedUserItem} >
                <View style={styles.smallProfilePictureWrapper}>
                        <Image source={require('../../images/demo/Profile/sample2.jpg')} style={{width: 14, height: 14}}/>
                    </View>
                <Text style={styles.contactSelectedName} >Oliver Rice</Text>
            </TouchableOpacity>
        );
     });

    /*<TextInput
                            style={styles.addContactInput}
                            onChangeText={this.onChangeTextHandler}
                            value={this.state.inputText}
                          />*/

    return (
        <KeyboardAvoidingView behavior="padding" style={{flex: 1}}>
        <View style={{flex: 1}}>
            <StatusBar hidden={true} />
            <View style={styles.headerBar}>
                <NavBar navigation={this.props.navigation} goBack={this.goBack} title="NEW MESSAGE" backButton={true} />
            </View>
            <View style={styles.contentWrapper}>
                <View style={styles.addContactWrapper} >
                    <View style={styles.addContactLeft} >
                        <Text style={styles.contactTo}>To:</Text>
                    </View>
                    <View style={styles.addContactRight} >
                        {selectedUsers}
                        <TouchableOpacity style={styles.addedContactWrapper} onPress={() => this.showContacts("")}>
                            <Image source={require('../../images/icons/IconAddContact.png')} style={{width: 18, height: 18}}/>
                        </TouchableOpacity>
                    </View>
                </View>
                <View style={styles.mainContentWrapper} >
                    {contactListView}
                    <TextInput
                        style={styles.inputTextMainMessage}
                        multiline={true}
                        placeholder="Your message here"
                        blurOnSubmit={true}
                    />
                </View>
                <TouchableOpacity onPress={() => this.sendMessage( )} style={styles.buttonWrapper} >
                    <Text style={styles.sendMessage}>Send Message</Text>
                </TouchableOpacity>
            </View>
        </View>
        </KeyboardAvoidingView>
    );
  }
</code>```

I thought I could solve the issue by adding this.onAddedContactPress = this.onAddedContactPress.bind(this); in the constructor but it isn't having any impact.

答:
Where is your onPressfunction added? I think it is inside render function and that create a problem.

I tested it and your code works well.

```<code>import React, { Component } from 'react';
import {
    StyleSheet,
    Text,
    View,
    TouchableOpacity,
    Alert
} from 'react-native';

export default class APP extends Component {
    constructor(){
        super();
        this.state = {
            contactsSelected: [
                {name: 'one'},
                {name: 'two'},
                {name: 'three'},
            ]
        }
    }

    onAddedContactPress(item){
        Alert.alert(item.name)
    }

    render() {
        return (
            <View style={styles.container}>
                {this.state.contactsSelected.map(item => {
                    return (
                        <TouchableOpacity onPress={() => this.onAddedContactPress(item)} key={item.name}>
                            <Text>{item.name}</Text>
                        </TouchableOpacity>
                    )
                })}
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#F5FCFF',
    }
});
</code>```

Hope this helps.

Body:
Hi I am getting the following error when clicking on a TouchableOpacity that is created within a loop.

The TouchableOpacity that calls it is here

    constructor() {

    super();

    this.pressRowContact = this.pressRowContact.bind(this);
    this.fetchData = this.fetchData.bind(this);
    this.goBack = this.goBack.bind(this);
    this.onAddedContactPress = this.onAddedContactPress.bind(this);
    this.sendMessage = this.sendMessage.bind(this);

    this.state = {
      loadingVisible: false,
      inputText: "",
      arrayContactsSelected: [],
      dataContactList: [],
      showContactList: false,
    };
  }

  componentDidMount() {
    this.fetchData();
  }

  onChangeTextHandler = (e) => {
    this.textInputValue = e;
  }

  onAddedContactPress(){}

  render() {

    const { navigate } = this.props.navigation;

    console.log(this.state.showContactList);

    if(this.state.showContactList == true){
        var contactListView = <View style={styles.contactListWrapper}>
            <FlatList
                data = {this.state.dataContactList}
                renderItem={({item}) => <TouchableOpacity onPress={() => this.pressRowContact( item )} >
                <View style={styles.contactRow}>
                    <View style={styles.standardProfilePicWrapper}>
                        <Image source={require('../../images/demo/Profile/sample2.jpg')} style={{width: 30, height: 30}}/>
                    </View>
                    <Text>Someone Name Here</Text>
                </View>
            </TouchableOpacity>}
            />
        </View>
    }else {
        var contactListView;
    }

    var selectedUsers = this.state.arrayContactsSelected.map(function(item) {
        return (
            <TouchableOpacity onPress={() => this.onAddedContactPress(item)} key={item.userID} style={styles.selectedUserItem} >
                <View style={styles.smallProfilePictureWrapper}>
                        <Image source={require('../../images/demo/Profile/sample2.jpg')} style={{width: 14, height: 14}}/>
                    </View>
                <Text style={styles.contactSelectedName} >Oliver Rice</Text>
            </TouchableOpacity>
        );
     });

    /*<TextInput
                            style={styles.addContactInput}
                            onChangeText={this.onChangeTextHandler}
                            value={this.state.inputText}
                          />*/

    return (
        <KeyboardAvoidingView behavior="padding" style={{flex: 1}}>
        <View style={{flex: 1}}>
            <StatusBar hidden={true} />
            <View style={styles.headerBar}>
                <NavBar navigation={this.props.navigation} goBack={this.goBack} title="NEW MESSAGE" backButton={true} />
            </View>
            <View style={styles.contentWrapper}>
                <View style={styles.addContactWrapper} >
                    <View style={styles.addContactLeft} >
                        <Text style={styles.contactTo}>To:</Text>
                    </View>
                    <View style={styles.addContactRight} >
                        {selectedUsers}
                        <TouchableOpacity style={styles.addedContactWrapper} onPress={() => this.showContacts("")}>
                            <Image source={require('../../images/icons/IconAddContact.png')} style={{width: 18, height: 18}}/>
                        </TouchableOpacity>
                    </View>
                </View>
                <View style={styles.mainContentWrapper} >
                    {contactListView}
                    <TextInput
                        style={styles.inputTextMainMessage}
                        multiline={true}
                        placeholder="Your message here"
                        blurOnSubmit={true}
                    />
                </View>
                <TouchableOpacity onPress={() => this.sendMessage( )} style={styles.buttonWrapper} >
                    <Text style={styles.sendMessage}>Send Message</Text>
                </TouchableOpacity>
            </View>
        </View>
        </KeyboardAvoidingView>
    );
  }

I thought I could solve the issue by adding this.onAddedContactPress = this.onAddedContactPress.bind(this); in the constructor but it isn't having any impact.

Body:
Where is your onPressfunction added? I think it is inside render function and that create a problem.

I tested it and your code works well.

import React, { Component } from 'react';
import {
    StyleSheet,
    Text,
    View,
    TouchableOpacity,
    Alert
} from 'react-native';

export default class APP extends Component {
    constructor(){
        super();
        this.state = {
            contactsSelected: [
                {name: 'one'},
                {name: 'two'},
                {name: 'three'},
            ]
        }
    }

    onAddedContactPress(item){
        Alert.alert(item.name)
    }

    render() {
        return (
            <View style={styles.container}>
                {this.state.contactsSelected.map(item => {
                    return (
                        <TouchableOpacity onPress={() => this.onAddedContactPress(item)} key={item.name}>
                            <Text>{item.name}</Text>
                        </TouchableOpacity>
                    )
                })}
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#F5FCFF',
    }
});

Hope this helps.


问:
Omniauth passing data to Facebook and having them return it after authentication
I've got omniauth Facebook working and I'd like to implement age verification so that minors can't join.

I have decided to ask users for their date of birth before I show them the signup page.

If the user provides a valid date of birth and chooses to join with Facebook, then I would like to send that date of birth over to Facebook and have it returned along with the user when authentication is complete, so that I can use it when creating their account.

Do that make sense? Is it possible to tell omniauth that I have a bunch of attributes gathered earlier, and I'd need you to send them back to me so I don't lose them and have to ask the user for their date of birth twice?

Failing that, what can I do besides ask for the date of birth again?

答:
You can ask facebook to pass the "birthday" of the user but for that you'll need to ask for that scope on your oauth flow, by requesting "user_birthday" scope. Then you'll need to issue a new request to fetch that.

So after the oauth flow you should have a token, scoped for user_birthday.

With that token you can construct the following URI:

```<code>https://graph.facebook.com/v2.4/me?fields=birthday&access_token=THE_TOKEN_RECEIVED_THROUGH_OMNIAUTH
</code>```

And use Net::HTTP to get that resource (or whatever library you want). If your access token grants access to the birthday scope you'll get a json response that you'll need to parse so you can read the value.

You'll also need to take care of the situation in which the user might reject to give you permission to the birthday scope (say they thought you could use that to verify their age - since you asked for it earlier it's an easy to make deduction... and they deny you access to it over facebook because they're not the age you required), by either halting the registration, proceeding, or whatever you deem appropriate. Also remember that the user might not have the birthday set on facebook.

If you just want to keep track of the birthday the user input in the first place, just store it in the session[:user_birthday] or something.

Body:
You can ask facebook to pass the "birthday" of the user but for that you'll need to ask for that scope on your oauth flow, by requesting "user_birthday" scope. Then you'll need to issue a new request to fetch that.

So after the oauth flow you should have a token, scoped for user_birthday.

With that token you can construct the following URI:

https://graph.facebook.com/v2.4/me?fields=birthday&access_token=THE_TOKEN_RECEIVED_THROUGH_OMNIAUTH

And use Net::HTTP to get that resource (or whatever library you want). If your access token grants access to the birthday scope you'll get a json response that you'll need to parse so you can read the value.

You'll also need to take care of the situation in which the user might reject to give you permission to the birthday scope (say they thought you could use that to verify their age - since you asked for it earlier it's an easy to make deduction... and they deny you access to it over facebook because they're not the age you required), by either halting the registration, proceeding, or whatever you deem appropriate. Also remember that the user might not have the birthday set on facebook.

If you just want to keep track of the birthday the user input in the first place, just store it in the session[:user_birthday] or something.


问:
react native how to deal with Cannot read property 'undefined' of undefined
I'm expecting some data from remote server to show it in the screen but I got this error in the simulator Cannot read property 'undefined' of undefined the reason why is the content is rendered before the arrival of the results, this the part of code where I'm having this error :

```<code>caption = { this.state.customFieldDropdown['gender'][this.state.dropDownSelectedItems['gender'] ] || '---Choose---' }
</code>```

So the property caption is expecting a text, and to deal with undefined values I added this  || '---Choose---' to show text '---Choose---' in case of null but the problem is this.state.dropDownSelectedItems['gender'] is undefined and when this.state.customFieldDropdown access that value it caused the error ( reading property which is undefined)

So how to deal with this issue?

答:
Idx is really good. You can do something like that:</p>

```<code>if (idx(this.state, _ => _.customFieldDropdown.gender[_.dropDownSelectedItems.gender]))
    caption = this.state.customFieldDropdown.gender[this.state.dropDownSelectedItems.gender]
else
    caption = '---Choose---'
</code>```

Body:
I'm expecting some data from remote server to show it in the screen but I got this error in the simulator Cannot read property 'undefined' of undefined the reason why is the content is rendered before the arrival of the results, this the part of code where I'm having this error :

caption = { this.state.customFieldDropdown['gender'][this.state.dropDownSelectedItems['gender'] ] || '---Choose---' }

So the property caption is expecting a text, and to deal with undefined values I added this  || '---Choose---' to show text '---Choose---' in case of null but the problem is this.state.dropDownSelectedItems['gender'] is undefined and when this.state.customFieldDropdown access that value it caused the error ( reading property which is undefined)

So how to deal with this issue?

Body:
Idx is really good. You can do something like that:

if (idx(this.state, _ => _.customFieldDropdown.gender[_.dropDownSelectedItems.gender]))
    caption = this.state.customFieldDropdown.gender[this.state.dropDownSelectedItems.gender]
else
    caption = '---Choose---'


问:
Search box to find user in rails
I'm somewhat new to rails. I'm going through making the classic twitter clone right now. I want to have a search bar on my homepage that allows the user to search for a twitter handle, and if the handle exists, it will send the user to the show page for that twitter handle.

I've been following a RailsCast on how to implement a simple search, but instead of doing it on the index like the video, I want to do it on the show action. I've run into some problems though. The form sits on my user index view.
Here is the error:

```<code>ActionController::UrlGenerationError in Users#index
Showing c:/Sites/Projects/twitterapp/twitter/app/views/users/index.html.erb where line #2 raised:

No route matches {:action=>"show", :controller=>"users"} missing required keys: [:id]
</code>```

Here is the form:

```<code><%= form_tag(user_path, method: 'get') do %>
      <%= text_field_tag(:search, params[:search]) %>
      <%= submit_tag("Search", name: nil) %>
<% end %>
</code>```

Here is my show action:

```<code>def show
        @user = User.search(params[:search])
end
</code>```

And here is my search method in my user model:

```<code>def self.search(search)
        if search
            find(:all, conditions:['name LIKE ?', "%#{search}%"])
        else
            find(:all)
        end
end
</code>```

答:
Found your question via Google, but the responses and suggestions didn't work for me. Found another solution that did, so seems worth posting here.

"Search and Filter Rails Models Without Bloating Your Controller":
http://www.justinweiss.com/articles/search-and-filter-rails-models-without-bloating-your-controller/

Title: Search box to find user in rails

Body:
I'm somewhat new to rails. I'm going through making the classic twitter clone right now. I want to have a search bar on my homepage that allows the user to search for a twitter handle, and if the handle exists, it will send the user to the show page for that twitter handle.

I've been following a RailsCast on how to implement a simple search, but instead of doing it on the index like the video, I want to do it on the show action. I've run into some problems though. The form sits on my user index view.
Here is the error:

ActionController::UrlGenerationError in Users#index
Showing c:/Sites/Projects/twitterapp/twitter/app/views/users/index.html.erb where line #2 raised:

No route matches {:action=>"show", :controller=>"users"} missing required keys: [:id]

Here is the form:

<%= form_tag(user_path, method: 'get') do %>
      <%= text_field_tag(:search, params[:search]) %>
      <%= submit_tag("Search", name: nil) %>
<% end %>

Here is my show action:

def show
        @user = User.search(params[:search])
end

And here is my search method in my user model:

def self.search(search)
        if search
            find(:all, conditions:['name LIKE ?', "%#{search}%"])
        else
            find(:all)
        end
end


问:
regex How to find the last occurrence of char using regex
I ran a dir /s command to list files in folders & sub-folders, and to show the file size. My issue is that I use a "," as a separator between the file name and size.

Is their any way to find the last comma in the and replace it with";"?

My text file looks like this:

```<code>H:\IP Phones, Mobile Information.xls,152064
H:\Master Sheet Updated.xlsx,46446
</code>```

答:
The following regex will match a comma that is not followed by .* (any number of any character) and a comma.

```<code>,(?!.*?,)
</code>```

Then just use the Replace... functionality in Sublime (Ctrl+H) and it should work.

Body:
I ran a dir /s command to list files in folders & sub-folders, and to show the file size. My issue is that I use a "," as a separator between the file name and size.

Is their any way to find the last comma in the and replace it with";"?

My text file looks like this:

H:\IP Phones, Mobile Information.xls,152064
H:\Master Sheet Updated.xlsx,46446

Body:
The following regex will match a comma that is not followed by .* (any number of any character) and a comma.

,(?!.*?,)

Then just use the Replace... functionality in Sublime (Ctrl+H) and it should work.


问:
Using python lists with TensorFlow while_loop
Is there any way to iterate through a python list while using control_flow_ops.while_loop?

I am using control_flow_ops.while_loop to iterate through a sequence in my RNN.
I also have a list L of functions that I want to call.

Let 'j' represent the current index of the sequence in the while_loop.
As I iterate through, I want to call the function at index j in L.

But calling L[j] doesn't work: j is a tensor representing the index of the sequence, and L is a python list. tf.gather also doesn't work because I also can't convert L to a tensor (the elements are functions).

How do I access the elements of L in the while_loop? Example below:

```<code>L = [fn1,fn2,fn3]

def body(j,seq):
    seq_elem = seq.read(j)

    # Try to get the function stored in L.
    fn = L[j] # Doesn't work, L is a python list while j is a tensor.

    fn(seq_elem)
    return j+1,seq

_, _ = control_flow_ops.while_loop(
        cond = lambda j, _: j < seq_length,
        body=body,
        loop_vars=(tf.constant(0,dtype=tf.int32), seq)
</code>```

答: Lists which cannot be converted to tensors will not work with tf.while_loop (as of july 2017).</p>

Body:
Is there any way to iterate through a python list while using control_flow_ops.while_loop?

I am using control_flow_ops.while_loop to iterate through a sequence in my RNN.
I also have a list L of functions that I want to call.

Let 'j' represent the current index of the sequence in the while_loop.
As I iterate through, I want to call the function at index j in L.

But calling L[j] doesn't work: j is a tensor representing the index of the sequence, and L is a python list. tf.gather also doesn't work because I also can't convert L to a tensor (the elements are functions).

How do I access the elements of L in the while_loop? Example below:

L = [fn1,fn2,fn3]

def body(j,seq):
    seq_elem = seq.read(j)

    # Try to get the function stored in L.
    fn = L[j] # Doesn't work, L is a python list while j is a tensor.

    fn(seq_elem)
    return j+1,seq

_, _ = control_flow_ops.while_loop(
        cond = lambda j, _: j < seq_length,
        body=body,
        loop_vars=(tf.constant(0,dtype=tf.int32), seq)


问:
Run node module from powershell
Say that I have a folder with a node module installed inside. How can I, using powershell, run this module ? For example, I have a folder with webpack installed inside and I'd like to be able to do something like

```<code>node webpack
</code>```

This does not work because it can't find the module. However, it works if I do:

```<code>node ".\node_module\webpack\bin\webpack.js"
</code>```

However, I can't really use this because I'm working on a powershell script that allows the user to define a json file with actions. For example:

```<code>{
  "type": "run-node",
  "options": {
    "module": "webpack",
    "parameters": "--configFile=config/webpack.prod.js"
  }
}
</code>```

As the module to execute is dynamic, I don't know where it will be (except if all module are installed in ".\node_modules\module\bin\module.js" ?), so I can't launch it.

答:
You can define a webpack script in your package.json:

```<code>"scripts": {
    "webpack": "node \"./node_module/webpack/bin/webpack.js\""
}
</code>```

Then you can use npm run webpack or yarn webpack to run it.

Title: Run node module from powershell

Body:
Say that I have a folder with a node module installed inside. How can I, using powershell, run this module ? For example, I have a folder with webpack installed inside and I'd like to be able to do something like

node webpack

This does not work because it can't find the module. However, it works if I do:

node ".\node_module\webpack\bin\webpack.js"

However, I can't really use this because I'm working on a powershell script that allows the user to define a json file with actions. For example:

{
  "type": "run-node",
  "options": {
    "module": "webpack",
    "parameters": "--configFile=config/webpack.prod.js"
  }
}

As the module to execute is dynamic, I don't know where it will be (except if all module are installed in ".\node_modules\module\bin\module.js" ?), so I can't launch it.

Body:
You can define a webpack script in your package.json:

"scripts": {
    "webpack": "node \"./node_module/webpack/bin/webpack.js\""
}

Then you can use npm run webpack or yarn webpack to run it.


问:
ipcRenderer send vs sendSync
I am developing a CRUD Angular/Electron application and I would like to use electron-store to persist my data. Angular will not use directly electron-store. Instead it will send commands to the ipcMain process and the main process will save/edit/delete the data. Should I use sendSync or send from the ipcRenderer to communicate data to the main process?

I have read that send is not recommended because it is synchronous but electron-store does not seem to do things asynchronously.

答:
It depends from the synchronization of your operations.

sendSync is used when you need the function to be executed immediately or when you need a return value from this function.
It will wait for the execution of the function, as the name said is synchronous.

In other cases, I use send function, that is asynchronous.

Title: ipcRenderer send vs sendSync


问:
How to correctly configure multi-services docker-compose
I have Docker with version 1.13.1 on Windows. And next configuration for compose:

```<code>version: '2.1'
services:
  discovery:
    build: ../discovery
    ports:
     - 8761:8761

  gateway:
    build: ../gateway
    ports:
     - 8888:8888
</code>```

My gateway service tried to lookup discovery service by localhost:8761, but it failed.

I tried to set discovery:8761 but it also failed.
It works only with IP from DOCKER_HOST property.
I forwarded ports 8761 from VB image to localhost, and it available on localhost:8761 from windows.

How to correctly configure multi-services docker-compose and domain names without hard coded ips in services?

答: Even though you fixed it, my two cents: maybe you should force a startup order in docker-compose.yml, following: https://docs.docker.com/compose/compose-file/#depends_on</p>

Body:
I have Docker with version 1.13.1 on Windows. And next configuration for compose:

version: '2.1'
services:
  discovery:
    build: ../discovery
    ports:
     - 8761:8761

  gateway:
    build: ../gateway
    ports:
     - 8888:8888

My gateway service tried to lookup discovery service by localhost:8761, but it failed.

I tried to set discovery:8761 but it also failed.
It works only with IP from DOCKER_HOST property.
I forwarded ports 8761 from VB image to localhost, and it available on localhost:8761 from windows.

How to correctly configure multi-services docker-compose and domain names without hard coded ips in services?


问:
Why the switch statement and not if-else?
I've been wondering this for some time now.  I'm by far not a hardcore programmer, mainly small Python scripts and I've written a couple molecular dynamics simulations.  For the real question:  What is the point of the switch statement?  Why can't you just use the if-else statement?

Thanks for your answer and if this has been asked before please point me to the link.

EDIT

S.Lott has pointed out that this may be a duplicate of questions If/Else vs. Switch.  If you want to close then do so.  I'll leave it open for further discussion.

答:
A switch construct is more easily translated into a jump (or branch) table. This can make switch statements much more efficient than if-else when the case labels are close together. The idea is to place a bunch of jump instructions sequentially in memory and then add the value to the program counter. This replaces a sequence of comparison instructions with an add operation.

Below are some extremely simplified psuedo-assembly examples. First, the if-else version:

```<code>    // C version
    if (1 == value)
        function1();
    else if (2 == value)
        function2();
    else if (3 == value)
        function3();

    // assembly version
    compare value, 1
    jump if zero label1
    compare value, 2
    jump if zero label2
    compare value, 3
    jump if zero label3
label1:
    call function1
label2:
    call function2
label3:
    call function3
</code>```

Next is the switch version:

```<code>    // C version
    switch (value) {
    case 1: function1(); break;
    case 2: function2(); break;
    case 3: function3(); break;
    }

    // assembly version
    add program_counter, value
    call function1
    call function2
    call function3
</code>```

You can see that the resulting assembly code is much more compact. Note that the value would need to be transformed in some way to handle other values than 1, 2 and 3. However, this should illustrate the concept.

OwnerDisplayName: Casey

LastEditorDisplayName: Casey

Body:
A switch construct is more easily translated into a jump (or branch) table. This can make switch statements much more efficient than if-else when the case labels are close together. The idea is to place a bunch of jump instructions sequentially in memory and then add the value to the program counter. This replaces a sequence of comparison instructions with an add operation.

Below are some extremely simplified psuedo-assembly examples. First, the if-else version:

    // C version
    if (1 == value)
        function1();
    else if (2 == value)
        function2();
    else if (3 == value)
        function3();

    // assembly version
    compare value, 1
    jump if zero label1
    compare value, 2
    jump if zero label2
    compare value, 3
    jump if zero label3
label1:
    call function1
label2:
    call function2
label3:
    call function3

Next is the switch version:

    // C version
    switch (value) {
    case 1: function1(); break;
    case 2: function2(); break;
    case 3: function3(); break;
    }

    // assembly version
    add program_counter, value
    call function1
    call function2
    call function3

You can see that the resulting assembly code is much more compact. Note that the value would need to be transformed in some way to handle other values than 1, 2 and 3. However, this should illustrate the concept.

OwnerDisplayName: monjardin

LastEditorDisplayName: monjardin


问:
The type or namespace name 'DbContext' could not be found (EF installed)
I am using VS 2012. I installed with Nuget the EntityFramework (version 6.1.1), and add references to the System.Data and System.Data.Entity, but when I open a new class in the solution and refering to DbContext, it says:

"The type or namespace name 'DbContext' could not be found (are you
  missing a using directive or an assembly reference?)"

It's weird beacuse the DbContext is green, like every recognized class, when I press F12 to look into the DbContext class it brings me to the System.Data.Entity.DbContext class as it should be.

```<code>public DbContext MyContex { get; set; }
</code>```

The same happanes with DbSet

```<code>public DbSet<TEntity> MySet { get; set; }
</code>```

What else am I missing?

答: I was getting this error after upgrading from Visual Studio 2015 to 2017. I closed VS, deleted my .suo file, restarted VS, rebuilt the solution, and everything works great now.</p>

Body:
I am using VS 2012. I installed with Nuget the EntityFramework (version 6.1.1), and add references to the System.Data and System.Data.Entity, but when I open a new class in the solution and refering to DbContext, it says:

"The type or namespace name 'DbContext' could not be found (are you
  missing a using directive or an assembly reference?)"

It's weird beacuse the DbContext is green, like every recognized class, when I press F12 to look into the DbContext class it brings me to the System.Data.Entity.DbContext class as it should be.

public DbContext MyContex { get; set; }

The same happanes with DbSet

public DbSet<TEntity> MySet { get; set; }

What else am I missing?


问:
Magento 2 - Reload totals cart after ajax change quantity
I want to use ajax to change the quantity of one item on the cart magento 2 cart page.

I have added this javascript:

```<code>$('.cart.item .qty').on({
    change: function() {
        var post_url = $(this).attr('data-post-url');

        $.post(post_url, $(this).serialize(), function(data) {
            $(".form-cart").replaceWith(data.cart_html);
            $("#cart-totals").replaceWith(data.totals_html);
            $("#cart-totals").trigger('contentUpdated');
        }, "json");
    }
});
</code>```

The value of data.totals_html is

```<code><div id="cart-totals" class="cart-totals" data-bind="scope:'block-totals'">
<!-- ko template: getTemplate() --><!-- /ko -->
<script type="text/x-magento-init">
        {
            "#cart-totals": {
                "Magento_Ui/js/core/app": {"components":{"block-totals":....}
</script>
</code>```

When I change the quantity, the total component content is not refresh..

Anyone have an idea for dynamically update the total component after replace the html code?

答:
You can consult this way to ajax re-load block totals in cart:</p>

```<code>define([
    "jquery",
    'Magento_Checkout/js/action/get-payment-information',
    'Magento_Checkout/js/model/totals'
], function($, getPaymentInformationAction, totals) {
    $('.cart.item .qty').on({
        change: function() {
            var post_url = $(this).attr('data-post-url');
            $.post(post_url, $(this).serialize(), function(data) {
                //custom your update
                $(".form-cart").replaceWith(data.cart_html);
                $("#cart-totals").replaceWith(data.totals_html);
                //reload block total
                var deferred = $.Deferred();
                totals.isLoading(true);
                getPaymentInformationAction(deferred);
                $.when(deferred).done(function() {
                    totals.isLoading(false);
                });
                //end
            }, "json");
        }
    });
});
</code>```

Body:
I want to use ajax to change the quantity of one item on the cart magento 2 cart page.

I have added this javascript:

$('.cart.item .qty').on({
    change: function() {
        var post_url = $(this).attr('data-post-url');

        $.post(post_url, $(this).serialize(), function(data) {
            $(".form-cart").replaceWith(data.cart_html);
            $("#cart-totals").replaceWith(data.totals_html);
            $("#cart-totals").trigger('contentUpdated');
        }, "json");
    }
});

The value of data.totals_html is

When I change the quantity, the total component content is not refresh..

Anyone have an idea for dynamically update the total component after replace the html code?

Body:
You can consult this way to ajax re-load block totals in cart:

define([
    "jquery",
    'Magento_Checkout/js/action/get-payment-information',
    'Magento_Checkout/js/model/totals'
], function($, getPaymentInformationAction, totals) {
    $('.cart.item .qty').on({
        change: function() {
            var post_url = $(this).attr('data-post-url');
            $.post(post_url, $(this).serialize(), function(data) {
                //custom your update
                $(".form-cart").replaceWith(data.cart_html);
                $("#cart-totals").replaceWith(data.totals_html);
                //reload block total
                var deferred = $.Deferred();
                totals.isLoading(true);
                getPaymentInformationAction(deferred);
                $.when(deferred).done(function() {
                    totals.isLoading(false);
                });
                //end
            }, "json");
        }
    });
});


问:
Edge device management using NiFI and MiNiFi
I am looking for device management of Edge devices from Central server remotely.

Example:- I am using number of Raspberry PI devices [say 100] to aggregate sensor data and pushing that data to the central server With MQTT service.

I am looking for some sort managing Raspberry devices remotely from central server. Like upgrade software component / Linux version on all 100 of Raspberry devices.

Can I accomplish these type of use cases by using MiNiFi in Edge device and NiFi in Central server? What is the best way of doing this?

Please share your thoughts.

Thank you.

With Best Regards,
Praveen.B

答: Praveen - good question.  This is in-line with the objectives for MiNiFi in its role of end to end flow management as part of the Apache NiFi project. We're not there yet for code distribution but some of the central command and control aspects are being worked on in the community right now.  Feel free to come join the mailing list and discuss what you'd like to see and contribute as much as you are comfortable.  thanks</p>


问:
Get UIFont for content size category
UIFont provides the +preferredFontForTextStyle: method to get a font instance with the proper size based on the user's selected content size category and the given UIFontTextStyle.

What I would like to do is get a font for a given text style and content size. Something like +fontForContentSizeCategory:andTextStyle:.

Unfortunately I cannot find anything similar to that in the headers for UIFont or UIFontDescriptor.

Any idea on how to achieve this?

Thanks

答:
Since iOS 10.0 this is possible using UITraitCollection:

```<code>let traitCollection = UITraitCollection(preferredContentSizeCategory: contentSizeCategory)
let font = UIFont.preferredFont(forTextStyle: textStyle, compatibleWith: traitCollection)
</code>```

Title: Get UIFont for content size category

Body:
Since iOS 10.0 this is possible using UITraitCollection:

let traitCollection = UITraitCollection(preferredContentSizeCategory: contentSizeCategory)
let font = UIFont.preferredFont(forTextStyle: textStyle, compatibleWith: traitCollection)