问:
Can someone look at code to see if I'm missing anything?
So I am trying to run this code for a scraper I built but I keep getting a syntax error message: unexpected identifier. Could someone help me see what I put in by mistake? or did I not close something? I am trying to build a scraper that will extract the countries that these foreign films are from.

Here is my code

```<code>var util = require("util"),
   async = require("async"),
 config = require(__dirname + "/config.js"),
  _ = require("lodash"),
    cheerio = require("cheerio"),
   request=require("request"),
   models = require(__dirname + "/models/index.js").models.autoLoad();

/* BEGIN SCRAPER HERE */
var request = require('request'),
  cheerio = require('cheerio');

var url = "http://www.imdb.com/list/ls057160363/";

request(url, function ( err, resp, code) {
 var $ = cheerio.load(code);

    request(url, function ( err, resp, code) {
        var $ = cheerio.load(code);
      console.log(url);
        $(".info").each(function() {
          var a = $(this).find("a").eq(0);
          var title = a.text();
          var url = "https://www.imdb.com/" + a.attr("href");

            request(url, function(err, body, code) {details page
              var $ = cheerio.load(code);
               console.log(url);
              var country = $('#titleDetails.txt-block a').html();
              var country = $("#titleDetails div").first().text().trim().split(":");
              var country = $("#titleDetails div").eq(0).text().trim().split(":");
              //check if not empty
              console.log(country);
              if( country.length )
                if(country[0] == "Country")
                  country = country[1].trim();
                else{
                  country = $("#titleDetails div").eq(1).text().trim().split(":");
                  console.log(country);
                  if( country.length )
                    country = country[1].trim();
                  else
                    country = ""
                  };
</code>```

And here is the error:

SyntaxError: Unexpected identifier at createScript (vm.js:80:10) at Object.runInThisContext (vm.js:139:10) at Module._compile (module.js:588:28) at Object.Module._extensions..js (module.js:635:10) at Module.load (module.js:545:32) at tryModuleLoad (module.js:508:12) at Function.Module._load (module.js:500:3) at Function.Module.runMain (module.js:665:10) at startup (bootstrap_node.js:187:16) at bootstrap_node.js:607:3

答:
Try this

```<code>    var util = require("util"),
    async = require("async"),
    config = require(__dirname + "/config.js"),
    _ = require("lodash"),
    cheerio = require("cheerio"),
    request = require("request"),
    models = require(__dirname + "/models/index.js").models.autoLoad();

/* BEGIN SCRAPER HERE */
var request = require('request'),
    cheerio = require('cheerio');

var url = "http://www.imdb.com/list/ls057160363/";

request(url, function (err, resp, code) {
    var $ = cheerio.load(code);

    request(url, function (err, resp, code) {
        var $ = cheerio.load(code);
        console.log(url);
        $(".info").each(function () {
            var a = $(this).find("a").eq(0);
            var title = a.text();
            var url = "https://www.imdb.com/" + a.attr("href");

            request(url, function (err, body, code) {
                //details page
                var $ = cheerio.load(code);
                console.log(url);
                var country = $('#titleDetails.txt-block a').html();
                var country = $("#titleDetails div").first().text().trim().split(":");
                var country = $("#titleDetails div").eq(0).text().trim().split(":");
                //check if not empty
                console.log(country);
                if (country.length)
                    if (country[0] == "Country")
                        country = country[1].trim();
                    else {
                        country = $("#titleDetails div").eq(1).text().trim().split(":");
                        console.log(country);
                        if (country.length)
                            country = country[1].trim();
                        else
                            country = ""
                    }
            });
        });
    });
});
</code>```

You had missed several brackets at the end and "details page" which was supposed to be a comment was not a comment.

Body:
So I am trying to run this code for a scraper I built but I keep getting a syntax error message: unexpected identifier. Could someone help me see what I put in by mistake? or did I not close something? I am trying to build a scraper that will extract the countries that these foreign films are from.

Here is my code

var util = require("util"),
   async = require("async"),
 config = require(__dirname + "/config.js"),
  _ = require("lodash"),
    cheerio = require("cheerio"),
   request=require("request"),
   models = require(__dirname + "/models/index.js").models.autoLoad();

/* BEGIN SCRAPER HERE */
var request = require('request'),
  cheerio = require('cheerio');

var url = "http://www.imdb.com/list/ls057160363/";

request(url, function ( err, resp, code) {
 var $ = cheerio.load(code);

    request(url, function ( err, resp, code) {
        var $ = cheerio.load(code);
      console.log(url);
        $(".info").each(function() {
          var a = $(this).find("a").eq(0);
          var title = a.text();
          var url = "https://www.imdb.com/" + a.attr("href");

            request(url, function(err, body, code) {details page
              var $ = cheerio.load(code);
               console.log(url);
              var country = $('#titleDetails.txt-block a').html();
              var country = $("#titleDetails div").first().text().trim().split(":");
              var country = $("#titleDetails div").eq(0).text().trim().split(":");
              //check if not empty
              console.log(country);
              if( country.length )
                if(country[0] == "Country")
                  country = country[1].trim();
                else{
                  country = $("#titleDetails div").eq(1).text().trim().split(":");
                  console.log(country);
                  if( country.length )
                    country = country[1].trim();
                  else
                    country = ""
                  };

And here is the error:

SyntaxError: Unexpected identifier at createScript (vm.js:80:10) at Object.runInThisContext (vm.js:139:10) at Module._compile (module.js:588:28) at Object.Module._extensions..js (module.js:635:10) at Module.load (module.js:545:32) at tryModuleLoad (module.js:508:12) at Function.Module._load (module.js:500:3) at Function.Module.runMain (module.js:665:10) at startup (bootstrap_node.js:187:16) at bootstrap_node.js:607:3

Body:
Try this

    var util = require("util"),
    async = require("async"),
    config = require(__dirname + "/config.js"),
    _ = require("lodash"),
    cheerio = require("cheerio"),
    request = require("request"),
    models = require(__dirname + "/models/index.js").models.autoLoad();

/* BEGIN SCRAPER HERE */
var request = require('request'),
    cheerio = require('cheerio');

var url = "http://www.imdb.com/list/ls057160363/";

request(url, function (err, resp, code) {
    var $ = cheerio.load(code);

    request(url, function (err, resp, code) {
        var $ = cheerio.load(code);
        console.log(url);
        $(".info").each(function () {
            var a = $(this).find("a").eq(0);
            var title = a.text();
            var url = "https://www.imdb.com/" + a.attr("href");

            request(url, function (err, body, code) {
                //details page
                var $ = cheerio.load(code);
                console.log(url);
                var country = $('#titleDetails.txt-block a').html();
                var country = $("#titleDetails div").first().text().trim().split(":");
                var country = $("#titleDetails div").eq(0).text().trim().split(":");
                //check if not empty
                console.log(country);
                if (country.length)
                    if (country[0] == "Country")
                        country = country[1].trim();
                    else {
                        country = $("#titleDetails div").eq(1).text().trim().split(":");
                        console.log(country);
                        if (country.length)
                            country = country[1].trim();
                        else
                            country = ""
                    }
            });
        });
    });
});

You had missed several brackets at the end and "details page" which was supposed to be a comment was not a comment.


来源: stackexchange

问:
Do you have any good examples of "architecture for architecture's sake"?
Just listening to this week's podcast and thought it would be nice to group together some of your experiences where you've seen the "architecture" side of design dominate things a little more than it should.

Java often gets a bad press in this respect, and an increasingly bad press as the perceived complexity of Java EE increases. My Java experience against time graph nose-dives significantly after 2004 so I don't feel qualified to comment.

My most recent experience is with an architect desperately trying to accurately represent an object model in a set of (relational) database tables (happened to be Oracle). The result is a database schema that's impossible to query efficiently without first pre-joining a bunch of tables (in materialized views).

答: A really good parable appeared on Joel's discussion group on this topic a few years ago.  The story is called Why I Hate Frameworks.</p>

OwnerDisplayName: Nick Pierpoint

ContentLicense: CC BY-SA 4.0

LastEditorDisplayName: Nick Pierpoint

OwnerDisplayName: Bill the Lizard

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Bill the Lizard


问:
Set DataTemplate to Attributes in Xml Binding
I need to build a form to edit XML node attributes.
Unfortunately I don't know the number and the names of the attributes.

Suppose I wanto to edit the attributes of the first node MYNODE:

```<code><MYROOT>
   <MYPARENTNODE1 Name = MyName1>
      <MYNODE Attr1 = Val1 Attr2 = Val2 ... Attr_N = Val_N />
   </MYPARENTNODE1>

   <MYPARENTNODE2 Name = MyName2>
      <MYNODE Attr1 = Val1 Attr2 = Val2 ... Attr_M = Val_M />
   </MYPARENTNODE2>

</MYROOT>
</code>```

First I select the node attributes:

```<code><XmlDataProvider
  x:Key="dataprovider" Source="myfile.xml"
  XPath="/MYROOT/MYPARENTNODE[@Name='MyName1']/MYNODE/@*"
 />
</code>```

Now, if I bind this to a listbox, I get all the attribute values as the list items. What I need is to apply a datatemplate to them so that I can have LABEL-EDITCONTROL couple for each attribute in order to edit it.

Something like:

```<code><DataTemplate DataType="{ ??? }">
        <StackPanel Orientation="Horizontal">
            <Label Content="{Binding Name}" />
            <TextBox Text="{Binding Value}" />
        </StackPanel>
</DataTemplate>
</code>```

Really I can't find any useful example both on Microsoft or Google!

Thans for any help,
Simone

答: If you need the same DataTemplate for all attributes, it is not necessary to specify DataType.</p>

Body:
I need to build a form to edit XML node attributes.
Unfortunately I don't know the number and the names of the attributes.

Suppose I wanto to edit the attributes of the first node MYNODE:

<MYROOT>
   <MYPARENTNODE1 Name = MyName1>
      <MYNODE Attr1 = Val1 Attr2 = Val2 ... Attr_N = Val_N />
   </MYPARENTNODE1>

   <MYPARENTNODE2 Name = MyName2>
      <MYNODE Attr1 = Val1 Attr2 = Val2 ... Attr_M = Val_M />
   </MYPARENTNODE2>

</MYROOT>

First I select the node attributes:

<XmlDataProvider
  x:Key="dataprovider" Source="myfile.xml"
  XPath="/MYROOT/MYPARENTNODE[@Name='MyName1']/MYNODE/@*"
 />

Now, if I bind this to a listbox, I get all the attribute values as the list items. What I need is to apply a datatemplate to them so that I can have LABEL-EDITCONTROL couple for each attribute in order to edit it.

Something like:

<DataTemplate DataType="{ ??? }">
        <StackPanel Orientation="Horizontal">

            <TextBox Text="{Binding Value}" />
        </StackPanel>
</DataTemplate>

Really I can't find any useful example both on Microsoft or Google!

Thans for any help,
Simone


问:
Multilabel binarizer - getting the inverse transform
I am stuck on using the Multilabel binarizer and One-vs-all classifier in scikit-learn . My challenge is once I obtain the predictions,
to obtain the original labels. (I trained and pickled the one-vs-rest classifier and vectorizer separately)

```<code>_labels = load_labels()
mlb = MultiLabelBinarizer()
mlb.fit_transform(_labels)
print mlb.classes_ # this prints the binarized labels

_clf,_vect = load_pickle('./pickles')

for q in queries:
    #query vector q
    X = vect.transform([q])
    res = clf.predict_proba(X)
    print res #[[ 0.00164113  0.00706595  0.00683465 .... 0.00837984]]

    #this is where I am stuck on what to pass into the inverse_transform to obtain
    preds = mlb.inverse_transform(??)
    print preds
</code>```

Thanks for your help in advance!

答:
Output of mlb.fit_transform(_labels) will be the input to the inverse_transform.

More on it is here: Multilabel Binarizer

ContentLicense: CC BY-SA 3.0

Body:
I am stuck on using the Multilabel binarizer and One-vs-all classifier in scikit-learn . My challenge is once I obtain the predictions,
to obtain the original labels. (I trained and pickled the one-vs-rest classifier and vectorizer separately)

_labels = load_labels()
mlb = MultiLabelBinarizer()
mlb.fit_transform(_labels)
print mlb.classes_ # this prints the binarized labels

_clf,_vect = load_pickle('./pickles')

for q in queries:
    #query vector q
    X = vect.transform([q])
    res = clf.predict_proba(X)
    print res #[[ 0.00164113  0.00706595  0.00683465 .... 0.00837984]]

    #this is where I am stuck on what to pass into the inverse_transform to obtain
    preds = mlb.inverse_transform(??)
    print preds

Thanks for your help in advance!


问:
Mathjax in C++ console
I am making an console application in C++ to find derivative of a mathematical function for my school project, but the results are hard to understand for example like

((sin(x)/cos(log(x^3 - 2*x))*3*x-2sqrt(x))

so, is there any way to get a better output. I would really like something like:

I know mathjax is not for c++ console but can i do something like to print it Mathjax format and use other applications maybe like chrome to display it properly? and can I do it offline?

答:
Make an HTML page that displays an equation using MathJAX. Copy most of that page (except for the part with the actual equation) into your C++ program and put it in a static const char [] like this:

```<code>static const char htmlhead[] =
     "<html><body>\n"
     "<p>Some random text.</p>";

static const char htmltail[] =
     "</body></html>";
</code>```

Then you can output the head, write some custom C++ to print out the equation in MathJAX then print out the tail. Use an ::std::ofstream to send all that to a file ending in .html. Then you can load that file up on Chrome with a file:/// URL.

Title: Mathjax in C++ console

Body:
Make an HTML page that displays an equation using MathJAX. Copy most of that page (except for the part with the actual equation) into your C++ program and put it in a static const char [] like this:

static const char htmlhead[] =
     "<html><body>\n"
     "<p>Some random text.</p>";

static const char htmltail[] =
     "</body></html>";

Then you can output the head, write some custom C++ to print out the equation in MathJAX then print out the tail. Use an ::std::ofstream to send all that to a file ending in .html. Then you can load that file up on Chrome with a file:/// URL.


问:
How can I set up a gradle task to extract dex jar and c libraries?
I have a android project with a single android library module, but I don't want to use it in a conventional way.

What I do right now is assemble the library (with the assemble gradle task) and post-process the resulting *.aar file.

I'd like to create a gradle task that:

build the classes.jar and dexs it (similar to dex --dx ...);

build the native libraries;

move everything in a folder I can choose.

Unfortunately, I only found a way to just build the native libraries (with the embedded gradle task externalNativeBuildRelease).

Can anybody help me with this groovy gradle problem?

答:
Here's a build.gradle file that does most if not all of what you want extracted from this.
I used it in this answer.
Also see The Gradle build system- Tutorial and Writing Custom Tasks.

Here are the defined tasks:

task copyClasses

task assembleExternalJar

task copyJarToOutputs

It should give you the inspiration to do what you want:

```<code>import org.apache.tools.ant.taskdefs.condition.Os

//jrg
apply plugin: 'com.android.library'
//apply plugin: 'com.android.application'

android {
    compileSdkVersion Integer.parseInt(COMPILE_SDK)
    buildToolsVersion BUILD_TOOLS_VERSION

    defaultConfig {
        targetSdkVersion Integer.parseInt(TARGET_SDK)
        minSdkVersion Integer.parseInt(MIN_SDK)
    }
}
// Add the main project as a dependency for our library
dependencies {
    compile project(':app')
}
// Define some tasks which are used in the build process
task copyClasses(type: Copy) { // Copy the assembled *.class files for only the current namespace into a new directory
    // get directory for current namespace
    def namespacePath = PLUGIN_NAMESPACE.replaceAll("\\.","/")
    // set source and destination directories
    from "build/intermediates/classes/release/${namespacePath}/"
    into "build/intermediates/dex/${namespacePath}/"

    // exclude classes which don't have a corresponding entry in the source directory
    def remExt = { name -> name.lastIndexOf('.').with {it != -1 ? name[0..<it] : name} }
    eachFile {details ->
        def thisFile = new File("${projectDir}/src/main/java/${namespacePath}/", remExt(details.name)+".java")
        if (!(thisFile.exists())) {
            details.exclude()
        }
    }
}

task assembleExternalJar << {
    // Get the location of the Android SDK
    ext.androidSdkDir = System.env.ANDROID_HOME
    if(androidSdkDir == null) {
        Properties localProps = new Properties()
        localProps.load(new FileInputStream(file('local.properties')))
        ext.androidSdkDir = localProps['sdk.dir']
    }
    // Make sure no existing jar file exists as this will cause dx to fail
    new File("${buildDir}/intermediates/dex/${PLUGIN_NAMESPACE}.jar").delete();
    // Use command line dx utility to convert *.class files into classes.dex inside jar archive
    String cmdExt = Os.isFamily(Os.FAMILY_WINDOWS) ? '.bat' : ''
    exec {
        commandLine "${androidSdkDir}/build-tools/${BUILD_TOOLS_VERSION}/dx${cmdExt}", '--dex',
                    "--output=${buildDir}/intermediates/dex/${PLUGIN_NAMESPACE}.jar",
                    "${buildDir}/intermediates/dex/"
    }
    copyJarToOutputs.execute()
}

task copyJarToOutputs(type: Copy) {
    // Copy the built jar archive to the outputs folder
    from 'build/intermediates/dex/'
    into 'build/outputs/'
    include '*.jar'
}

// Set the dependencies of the build tasks so that assembleExternalJar does a complete build
copyClasses.dependsOn(assemble)
assembleExternalJar.dependsOn(copyClasses)
</code>```

Body:
Here's a build.gradle file that does most if not all of what you want extracted from this.
I used it in this answer.
Also see The Gradle build system- Tutorial and Writing Custom Tasks.

Here are the defined tasks:

task copyClasses

task assembleExternalJar

task copyJarToOutputs

It should give you the inspiration to do what you want:

import org.apache.tools.ant.taskdefs.condition.Os

//jrg
apply plugin: 'com.android.library'
//apply plugin: 'com.android.application'

android {
    compileSdkVersion Integer.parseInt(COMPILE_SDK)
    buildToolsVersion BUILD_TOOLS_VERSION

    defaultConfig {
        targetSdkVersion Integer.parseInt(TARGET_SDK)
        minSdkVersion Integer.parseInt(MIN_SDK)
    }
}
// Add the main project as a dependency for our library
dependencies {
    compile project(':app')
}
// Define some tasks which are used in the build process
task copyClasses(type: Copy) { // Copy the assembled *.class files for only the current namespace into a new directory
    // get directory for current namespace
    def namespacePath = PLUGIN_NAMESPACE.replaceAll("\\.","/")
    // set source and destination directories
    from "build/intermediates/classes/release/${namespacePath}/"
    into "build/intermediates/dex/${namespacePath}/"

    // exclude classes which don't have a corresponding entry in the source directory
    def remExt = { name -> name.lastIndexOf('.').with {it != -1 ? name[0..<it] : name} }
    eachFile {details ->
        def thisFile = new File("${projectDir}/src/main/java/${namespacePath}/", remExt(details.name)+".java")
        if (!(thisFile.exists())) {
            details.exclude()
        }
    }
}

task assembleExternalJar << {
    // Get the location of the Android SDK
    ext.androidSdkDir = System.env.ANDROID_HOME
    if(androidSdkDir == null) {
        Properties localProps = new Properties()
        localProps.load(new FileInputStream(file('local.properties')))
        ext.androidSdkDir = localProps['sdk.dir']
    }
    // Make sure no existing jar file exists as this will cause dx to fail
    new File("${buildDir}/intermediates/dex/${PLUGIN_NAMESPACE}.jar").delete();
    // Use command line dx utility to convert *.class files into classes.dex inside jar archive
    String cmdExt = Os.isFamily(Os.FAMILY_WINDOWS) ? '.bat' : ''
    exec {
        commandLine "${androidSdkDir}/build-tools/${BUILD_TOOLS_VERSION}/dx${cmdExt}", '--dex',
                    "--output=${buildDir}/intermediates/dex/${PLUGIN_NAMESPACE}.jar",
                    "${buildDir}/intermediates/dex/"
    }
    copyJarToOutputs.execute()
}

task copyJarToOutputs(type: Copy) {
    // Copy the built jar archive to the outputs folder
    from 'build/intermediates/dex/'
    into 'build/outputs/'
    include '*.jar'
}

// Set the dependencies of the build tasks so that assembleExternalJar does a complete build
copyClasses.dependsOn(assemble)
assembleExternalJar.dependsOn(copyClasses)


问:
Program gets stuck in an infinite loop when using entering default during switch statement
So I am currently writing a program in C that using a switch statement can allow a string to be entered then depending on the value you choose from the menu determine what to do with it.

Here is my code,

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

int main()
{
    int menu, end, i;
    char string[100];
    end = 0;

    do
    {
        printf("Welcome to the string operations program.\n\n");

        printf("1 - Enter a string\n");
        printf("2 - Display the message using the string\n");
        printf("3 - Count the number of characters in the string\n");
        printf("4 - Display the string backwards\n");
        printf("5 - Exit\n\n");

        printf("Option: ");
        scanf("%d", &menu);

        switch (menu)
        {
            case 1:
                printf("String: ");
                scanf("%s", string);
                break;

            case 2:
                printf("This is a message: Hello %s\n", string);
                break;

            case 3:
                printf("There are %d characters in %s\n", strlen(string), string);
                break;

            case 4:
                printf("string reversed gives: ");
                for (i = strlen(string) - 1; i >= 0; i--)
                    printf("%c", string[i]);
                printf("\n");
                break;

            case 5:
                printf("Exit");
                return 1;
                break;

            default:
                printf("Invalid input, try again.\n");
                break;

        }
    }while (end != 1);
    return 0;
}
</code>```

It seems to work for everything when I run it through 1,2,3,4,5 as that is the requirement for the question. However when i enter a letter for example 't' it goes to the default section as expected. When it enters this it goes into an infinite loop.

Can anyone help me and show me how to not make this an infinite loop but just have it return to the start as the user input was not allowed?

答:
there are several problems with the posted code:

does not handle the scenario when the use has not entered a string

displays the welcome message more than once

does not properly handle menu selection 5

does not 'compare apples to apples'

does not empty stdin before trying input a string

does not allow any white space in the input string

....

The following proposed code:

corrects all the above listed problems

cleanly compiles

properly checks for and reports errors

contains a default string so the program does not have undefined behavior

includes the needed header files and documents why each header file is being included

And now the proposed code:

```<code>#include <stdio.h>   // printf(), scanf(), fprintf()
#include <stdlib.h>  // exit(), EXIT_FAILURE
#include <string.h>  // strlen()

int main()
{
    int menu;
    int end;
   //int i;
    char string[100] = "no string entered";
    end = 0;

    printf("Welcome to the string operations program.\n\n");

    do
    {
        printf("1 - Enter a string\n");
        printf("2 - Display the message using the string\n");
        printf("3 - Count the number of characters in the string\n");
        printf("4 - Display the string backwards\n");
        printf("5 - Exit\n\n");

        printf("Option: ");
        if( 1 != scanf("%d", &menu) )
        {
            fprintf( stderr, "scanf for menu selection failed\n" );
            exit( EXIT_FAILURE );
        }

        // implied else, scanf successful

        switch (menu)
        {
            case 1:
                // note leading space in format string to consume leftover newline in 'stdin'
                printf("String: ");
                if( 1 != scanf(" %99[^\n]", string) )
                {
                    fprintf( stderr, "scanf for input string failed\n" );
                    exit( EXIT_FAILURE );
                }

                // implied else, scanf successful
                break;

            case 2:
                printf("This is the string entered: <%s>\n", string);
                break;

            case 3:
                // note appropriate format specifier for `size_t` from `strlen()`
                printf("There are %lu characters in <%s>\n", strlen(string), string);
                break;

            case 4:
                printf("string reversed gives: ");
                for (size_t i = strlen(string); i; i--)
                    printf("%c", string[i-1]);

                printf("\n");
                break;

            case 5:
                printf("Exit");
                end = 1;
                break;

            default:
                printf("Invalid input, try again.\n");
                break;
        }
    } while (end != 1);
    return 0;
}
</code>```

A run of the program results in the following output:

```<code>Welcome to the string operations program.

1 - Enter a string
2 - Display the message using the string
3 - Count the number of characters in the string
4 - Display the string backwards
5 - Exit

Option: 2
This is the string entered: <no string entered>
1 - Enter a string
2 - Display the message using the string
3 - Count the number of characters in the string
4 - Display the string backwards
5 - Exit

Option: 1
String: this is a string with spaces
1 - Enter a string
2 - Display the message using the string
3 - Count the number of characters in the string
4 - Display the string backwards
5 - Exit

Option: 2
This is the string entered: <this is a string with spaces>
1 - Enter a string
2 - Display the message using the string
3 - Count the number of characters in the string
4 - Display the string backwards
5 - Exit

Option: 3
There are 28 characters in <this is a string with spaces>
1 - Enter a string
2 - Display the message using the string
3 - Count the number of characters in the string
4 - Display the string backwards
5 - Exit

Option: 4
string reversed gives: secaps htiw gnirts a si siht
1 - Enter a string
2 - Display the message using the string
3 - Count the number of characters in the string
4 - Display the string backwards
5 - Exit

Option: 6
Invalid input, try again.
1 - Enter a string
2 - Display the message using the string
3 - Count the number of characters in the string
4 - Display the string backwards
5 - Exit

Option: 5
Exit
</code>```

Body:
So I am currently writing a program in C that using a switch statement can allow a string to be entered then depending on the value you choose from the menu determine what to do with it.

Here is my code,

#include <stdio.h>

int main()
{
    int menu, end, i;
    char string[100];
    end = 0;

    do
    {
        printf("Welcome to the string operations program.\n\n");

        printf("1 - Enter a string\n");
        printf("2 - Display the message using the string\n");
        printf("3 - Count the number of characters in the string\n");
        printf("4 - Display the string backwards\n");
        printf("5 - Exit\n\n");

        printf("Option: ");
        scanf("%d", &menu);

        switch (menu)
        {
            case 1:
                printf("String: ");
                scanf("%s", string);
                break;

            case 2:
                printf("This is a message: Hello %s\n", string);
                break;

            case 3:
                printf("There are %d characters in %s\n", strlen(string), string);
                break;

            case 4:
                printf("string reversed gives: ");
                for (i = strlen(string) - 1; i >= 0; i--)
                    printf("%c", string[i]);
                printf("\n");
                break;

            case 5:
                printf("Exit");
                return 1;
                break;

            default:
                printf("Invalid input, try again.\n");
                break;

        }
    }while (end != 1);
    return 0;
}

It seems to work for everything when I run it through 1,2,3,4,5 as that is the requirement for the question. However when i enter a letter for example 't' it goes to the default section as expected. When it enters this it goes into an infinite loop.

Can anyone help me and show me how to not make this an infinite loop but just have it return to the start as the user input was not allowed?

Body:
there are several problems with the posted code:

does not handle the scenario when the use has not entered a string

displays the welcome message more than once

does not properly handle menu selection 5

does not 'compare apples to apples'

does not empty stdin before trying input a string

does not allow any white space in the input string

....

The following proposed code:

corrects all the above listed problems

cleanly compiles

properly checks for and reports errors

contains a default string so the program does not have undefined behavior

includes the needed header files and documents why each header file is being included

And now the proposed code:

#include <stdio.h>   // printf(), scanf(), fprintf()
#include <stdlib.h>  // exit(), EXIT_FAILURE
#include <string.h>  // strlen()

int main()
{
    int menu;
    int end;
   //int i;
    char string[100] = "no string entered";
    end = 0;

    printf("Welcome to the string operations program.\n\n");

    do
    {
        printf("1 - Enter a string\n");
        printf("2 - Display the message using the string\n");
        printf("3 - Count the number of characters in the string\n");
        printf("4 - Display the string backwards\n");
        printf("5 - Exit\n\n");

        printf("Option: ");
        if( 1 != scanf("%d", &menu) )
        {
            fprintf( stderr, "scanf for menu selection failed\n" );
            exit( EXIT_FAILURE );
        }

        // implied else, scanf successful

        switch (menu)
        {
            case 1:
                // note leading space in format string to consume leftover newline in 'stdin'
                printf("String: ");
                if( 1 != scanf(" %99[^\n]", string) )
                {
                    fprintf( stderr, "scanf for input string failed\n" );
                    exit( EXIT_FAILURE );
                }

                // implied else, scanf successful
                break;

            case 2:
                printf("This is the string entered: <%s>\n", string);
                break;

            case 3:
                // note appropriate format specifier for `size_t` from `strlen()`
                printf("There are %lu characters in <%s>\n", strlen(string), string);
                break;

            case 4:
                printf("string reversed gives: ");
                for (size_t i = strlen(string); i; i--)
                    printf("%c", string[i-1]);

                printf("\n");
                break;

            case 5:
                printf("Exit");
                end = 1;
                break;

            default:
                printf("Invalid input, try again.\n");
                break;
        }
    } while (end != 1);
    return 0;
}

A run of the program results in the following output:

Welcome to the string operations program.

1 - Enter a string
2 - Display the message using the string
3 - Count the number of characters in the string
4 - Display the string backwards
5 - Exit

Option: 2
This is the string entered: <no string entered>
1 - Enter a string
2 - Display the message using the string
3 - Count the number of characters in the string
4 - Display the string backwards
5 - Exit

Option: 1
String: this is a string with spaces
1 - Enter a string
2 - Display the message using the string
3 - Count the number of characters in the string
4 - Display the string backwards
5 - Exit

Option: 2
This is the string entered: <this is a string with spaces>
1 - Enter a string
2 - Display the message using the string
3 - Count the number of characters in the string
4 - Display the string backwards
5 - Exit

Option: 3
There are 28 characters in <this is a string with spaces>
1 - Enter a string
2 - Display the message using the string
3 - Count the number of characters in the string
4 - Display the string backwards
5 - Exit

Option: 4
string reversed gives: secaps htiw gnirts a si siht
1 - Enter a string
2 - Display the message using the string
3 - Count the number of characters in the string
4 - Display the string backwards
5 - Exit

Option: 6
Invalid input, try again.
1 - Enter a string
2 - Display the message using the string
3 - Count the number of characters in the string
4 - Display the string backwards
5 - Exit

Option: 5
Exit


问:
Does Observable.race for two observables work more than one time?
Tasks is: I have two effects (ngrx/store), let's say ef1$ and ef2$, which are Observables. In angular component I would like to detect which one is triggered. I added the following code:

```<code> Observable.race(ef1$, ef2$)
     .subscribe((payload) => {
          if (payload.type == ThreadActions.THREAD_READY_TO_BE_RENDERED) {
            // do one thing
          }
          else if (payload.type == ThreadActions.THREAD_ITEM_READY_TO_BE_RENDERED) {
            // do another thing
          }
        });
</code>```

But it looks like that after first emit of any effects Observable.race is going to be dead and no reaction more on additional emits, despite of I sure that effect executes again and again.

答:
It's hard to tell what is you desired functionality but if you want to use the race operator multiple times you'll need to complete the chain when it emits a resubscribe immediately:

```<code>Observable.defer(() => Observable.race(ef1$, ef2$))
  .take(1)
  .repeat()
  .subscribe(...);
</code>```

Body:
Tasks is: I have two effects (ngrx/store), let's say ef1$ and ef2$, which are Observables. In angular component I would like to detect which one is triggered. I added the following code:

 Observable.race(ef1$, ef2$)
     .subscribe((payload) => {
          if (payload.type == ThreadActions.THREAD_READY_TO_BE_RENDERED) {
            // do one thing
          }
          else if (payload.type == ThreadActions.THREAD_ITEM_READY_TO_BE_RENDERED) {
            // do another thing
          }
        });

But it looks like that after first emit of any effects Observable.race is going to be dead and no reaction more on additional emits, despite of I sure that effect executes again and again.

Body:
It's hard to tell what is you desired functionality but if you want to use the race operator multiple times you'll need to complete the chain when it emits a resubscribe immediately:

Observable.defer(() => Observable.race(ef1$, ef2$))
  .take(1)
  .repeat()
  .subscribe(...);


问:
Is there a way to check for empty arrays returned from ActiveRecord queries?
I want to write an activerecord query that behaves something like this:

```<code>User.joins(:comment).where(comments: {replies: []})
</code>```

which returns Users where their comments have no replies.

```<code>User.first.comment.first.replies => [] returns an empty array
</code>```

I need this to be an activerecord relation only, so using ruby code won't work. Is there a way to check for empty arrays using activerecord?

Edit:
Example schema

```<code>create_table "users", force: :cascade do |t|
t.string "email",
t.string "password"
end

create_table "comments" do |t|
t.string "content"
end

create_table "replies" do |t|
t.string "content"
end
</code>```

User.rb

```<code>class User < ActiveRecord::Base
has_many :comments
end
</code>```

Comment.rb

```<code>class Comment < ActiveRecord::Base
belongs_to :user
has_many :replies
end
</code>```

Reply.rb

```<code>class Reply < ActiveRecord::Base
belongs_to :comment
belongs_to :user
end
</code>```

These are just example models but this should illustrate the problem with models associated this these.

So if a user(with id of 1) has made 3 comments, and only 1 of those 3 comments has a reply on it, how would I get the other 2 comments in an activerecord relation?

答:
You can make design more simple by using counter_cache

Add counter_cache in replies

```<code>class Reply < ActiveRecord::Base
belongs_to :comment, counter_cache: true
belongs_to :user
end
</code>```

Add counter column in comment table

```<code>create_table "comments" do |t|
t.string "content"
t.integer "replies_count"
end
</code>```

Simple use condition for replies_count

```<code>User.joins(:comment).where(comments: {replies_count: 0})
</code>```

For more info refer to rails doc

Body:
I want to write an activerecord query that behaves something like this:

User.joins(:comment).where(comments: {replies: []})

which returns Users where their comments have no replies.

User.first.comment.first.replies => [] returns an empty array

I need this to be an activerecord relation only, so using ruby code won't work. Is there a way to check for empty arrays using activerecord?

Edit:
Example schema

create_table "users", force: :cascade do |t|
t.string "email",
t.string "password"
end

create_table "comments" do |t|
t.string "content"
end

create_table "replies" do |t|
t.string "content"
end

User.rb

class User < ActiveRecord::Base
has_many :comments
end

Comment.rb

class Comment < ActiveRecord::Base
belongs_to :user
has_many :replies
end

Reply.rb

class Reply < ActiveRecord::Base
belongs_to :comment
belongs_to :user
end

These are just example models but this should illustrate the problem with models associated this these.

So if a user(with id of 1) has made 3 comments, and only 1 of those 3 comments has a reply on it, how would I get the other 2 comments in an activerecord relation?

Body:
You can make design more simple by using counter_cache

Add counter_cache in replies

class Reply < ActiveRecord::Base
belongs_to :comment, counter_cache: true
belongs_to :user
end

Add counter column in comment table

create_table "comments" do |t|
t.string "content"
t.integer "replies_count"
end

Simple use condition for replies_count

User.joins(:comment).where(comments: {replies_count: 0})

For more info refer to rails doc


问:
Asp.net Google Sign In
I'm trying to implement Google Sign In in my ASP.net application.
I have implemented the javascript code from Integrating Google Sign-In into your web app and that works but I need to store a Google User ID in my Database for identification in future logins.

The page states that I shouldn't use the profile.getId but I should send the googleUser.getAuthResponse().id_token to the backend and validate this token.

Well I've sent this huge bundle of characters to the backend but I can't seem to figure out how to validate this bundle of characters and retrieve a useful identification ID (which should stay the same for a Google User) from this data bundle.

I've taken a look at:

```<code>protected void Page_Load(object sender, EventArgs e)
{
 System.Threading.Tasks.Task<Google.Apis.Auth.GoogleJsonWebSignature.Payload> Sig = Google.Apis.Auth.GoogleJsonWebSignature.ValidateAsync(Request.Form["idToken"], null, true);
 Sig.Wait();
}
</code>```

But this just hangs in my Page_Load method.

Has anyone got this working?

答:
I'm not sure how you setup your javascript, but the way I have my setup the page already loaded, so I have an API on the backend that receives the token from the client, then do this to get the payload:

```<code>GoogleJsonWebSignature.Payload payload = await GoogleJsonWebSignature.ValidateAsync(Token);
</code>```

The payload will give you all the user's information.

Title: Asp.net Google Sign In

Body:
I'm trying to implement Google Sign In in my ASP.net application.
I have implemented the javascript code from Integrating Google Sign-In into your web app and that works but I need to store a Google User ID in my Database for identification in future logins.

The page states that I shouldn't use the profile.getId but I should send the googleUser.getAuthResponse().id_token to the backend and validate this token.

Well I've sent this huge bundle of characters to the backend but I can't seem to figure out how to validate this bundle of characters and retrieve a useful identification ID (which should stay the same for a Google User) from this data bundle.

I've taken a look at:

protected void Page_Load(object sender, EventArgs e)
{
 System.Threading.Tasks.Task<Google.Apis.Auth.GoogleJsonWebSignature.Payload> Sig = Google.Apis.Auth.GoogleJsonWebSignature.ValidateAsync(Request.Form["idToken"], null, true);
 Sig.Wait();
}

But this just hangs in my Page_Load method.

Has anyone got this working?

Body:
I'm not sure how you setup your javascript, but the way I have my setup the page already loaded, so I have an API on the backend that receives the token from the client, then do this to get the payload:

GoogleJsonWebSignature.Payload payload = await GoogleJsonWebSignature.ValidateAsync(Token);

The payload will give you all the user's information.


问:
Publishing ASP.NET Core 2.0 API to .NET 4.6.x to host in IIS
I have built an API using ASP.NET Core 2.0 and I am looking to publish it to run and host it in IIS 8 (Windows Server 2012). I have found the following article that explains publishing it to IIS:

https://stackify.com/how-to-deploy-asp-net-core-to-iis/

But it requires the .NET Core Windows Server Hosting Bundle to be installed on the hosting machine, which I would prefer not to have to install on the hosting machines.

I am wondering if there is a way to publish the ASP.NET Core 2.0 application to a "pure" .NET 4.6.1 or 4.6.2 application such that I can run it in IIS without having to install additional .NET Core hosting dependencies.

答:
Short answer: no. Your project itself must target the full framework. This in effect publishes it for the full framework, since the target affects the build. The point is that if you're thinking you can keep it targeting .NET Core, but somehow publish to .NET 4.6, no that cannot be done.

That said, I think you're going down a bad path. The only good reason to target .NET 4.6 is if you need something specific in the full framework that you can't get from .NET Core. Even if you intend to publish to IIS today, having the ability to publish to Nginx or another webserver, instead, or even to a Mac or Linux is worth its weight in gold. Just install the hosting bundle. What's the big deal, anyways?


问:
Class does not exist symfony
I'm having a problem recovering my entities, the entities are in the AppBundle / Entity folder, but symfony can not find it ...

Here is the error: Class 'Product' does not exist

Here is the function myManager () present in a controller

```<code>public function myManager(){
$isDevMode = true;
$config = Setup::createAnnotationMetadataConfiguration(array(__DIR__."/AppBundle/Entity"), $isDevMode);

// database configuration parameters
        $conn = array(
            'dbname' => 'teste',
            'user' => 'root',
            'password' => '',
            'host' => '127.0.0.1',
            'driver' => 'pdo_mysql',
        );

$entityManager = EntityManager::create($conn, $config);
return $entityManager;
}
</code>```

the function testAction () that calls the manager and tries to load the Product entity

```<code>public function testAction(){
    $em = $this->myManager()->getRepository('Product');
    return $this->render('toto.html.twig');
}
</code>```

link of documentation : Doctrine

答:
You need to use the correct notation to make a reference to your entity:</p>

```<code>$manager->getRepository('MyBundleName:Product')
</code>```

Title: Class does not exist symfony

Body:
I'm having a problem recovering my entities, the entities are in the AppBundle / Entity folder, but symfony can not find it ...

Here is the error: Class 'Product' does not exist

Here is the function myManager () present in a controller

public function myManager(){
$isDevMode = true;
$config = Setup::createAnnotationMetadataConfiguration(array(__DIR__."/AppBundle/Entity"), $isDevMode);

// database configuration parameters
        $conn = array(
            'dbname' => 'teste',
            'user' => 'root',
            'password' => '',
            'host' => '127.0.0.1',
            'driver' => 'pdo_mysql',
        );

$entityManager = EntityManager::create($conn, $config);
return $entityManager;
}

the function testAction () that calls the manager and tries to load the Product entity

public function testAction(){
    $em = $this->myManager()->getRepository('Product');
    return $this->render('toto.html.twig');
}

link of documentation : Doctrine

Body:
You need to use the correct notation to make a reference to your entity:

$manager->getRepository('MyBundleName:Product')


问:
Is it advisable to call Web Services on cellForRowAtIndexPath for large datasets?
If the data set is too large and I want to show the data on a table View. What should be the best possible approach ?

First Approach-
I call the API in cellForRowAtIndexPath. This would make the request everytime I scroll which would mean hitting the service again and again. May be I can cache the data as well but still I think it is not the best possible approach.

Second Approach-
First, Save all the data locally and then show it. This would mean occupying more of the internal storage.

Which approach is better or is there any better approach available ?

答:
Creating too many connections is not a good idea.

You should get all of them and show in a single page for few items.

But since there is too much data, you have 2 option. Combining them is better as a 3rd option.

Don’t show any data, implement a search bar, request data with search text. Now you requested a subset of the data according to search text.

Request a subset of data (first 20 for example) and imlement load more button (instead of button you can use scrollview’s delegate too) or pagination.

If response have image links, you should download the images in cellForRowAtIndexpath. If you start to download them before, user will wait too much.


问:
Calculating total lines added/deleted after a merge?
I recently took a branch with a lot of commits and merged it back into my master branch. If I needed to go back and see how many lines were added or deleted because of that merge, how would I go about doing that?</p>

答:
^ (carat) gets you parent rev, so you could:

git diff --shortstat abc123^ abc123


问:
Change the XPath-root of an XmlDocument in .net (C#)?
When selecting from an XmlDocument by e.g. the XPath-method SelectSingleNode we get an XmlNode that consist of the first matching node, lets call it <node1>. If we do further selection on <node1> then one might expect that the XPath-root now is this node, but this is incorrect, the root is still the same as in the original XmlDocument. Here's an example:

```<code>XmlDocument xd = new XmlDocument();
xd.LoadXml(@"<root>
                 <subroot>
                     <elm>test1</elm>
                     <elm>test2</elm>
                     <elm>test3</elm>
                 </subroot>
             </root>");
XmlNode xnSubRoot = xd.SelectSingleNode("/root/subroot");

//This is the XPath I want to be able to use, but it returns null.
XmlNode xnElm = xnSubRoot.SelectSingleNode("/subroot/elm");

//This works, but the XPath-root is the same as in the original document.
xnElm = xnSubRoot.SelectSingleNode("/root/subroot/elm");
</code>```

Is there any way to "fix" the root of xnSubRoot so that I can use the XPath I want? The reason for my question is because I have a case where I'm calling a webservice that returns an XmlNode where the OuterXml-property shows a structure of "/Data/SubElement/..." and so on, but when running XPath "/Data" then null is returned, only "/SubElement" works, i.e. the XPath-root seems to be one level lower than the actual document-root.

I'm sure there is a perfectly reasonable explanation for this, or that I'm missing something vital. However I really can't seem to find anything, even though I've read http://msdn.microsoft.com/en-us/library/d271ytdx(VS.80).aspx.

N.B. I do realize that it would be possible to use the XPath "//subroot/elm", but then I might also get other elements further down in the XML structure.

答:
Since your selecting from the Root/SubElement Try this:

```<code>XmlNode xnElm = xnSubRoot.SelectSingleNode("elm");
</code>```

It will return the first child elm node of the current node.

Edit (from additionals informations provided in comments):

In this specific case, you are obtaning a XmlNode (which is your Data node) from a WebService call. All XPath requests on that XmlNode will be relative to it.

I would suggest that you modify all your XPaths to use a selector like webServiceNode.SelectSingleNode("SubElement/SubSubElement"); . There is no reason to specify absolute XPaths queries here.

Body:
When selecting from an XmlDocument by e.g. the XPath-method SelectSingleNode we get an XmlNode that consist of the first matching node, lets call it <node1>. If we do further selection on <node1> then one might expect that the XPath-root now is this node, but this is incorrect, the root is still the same as in the original XmlDocument. Here's an example:

XmlDocument xd = new XmlDocument();
xd.LoadXml(@"<root>
                 <subroot>
                     <elm>test1</elm>
                     <elm>test2</elm>
                     <elm>test3</elm>
                 </subroot>
             </root>");
XmlNode xnSubRoot = xd.SelectSingleNode("/root/subroot");

//This is the XPath I want to be able to use, but it returns null.
XmlNode xnElm = xnSubRoot.SelectSingleNode("/subroot/elm");

//This works, but the XPath-root is the same as in the original document.
xnElm = xnSubRoot.SelectSingleNode("/root/subroot/elm");

Is there any way to "fix" the root of xnSubRoot so that I can use the XPath I want? The reason for my question is because I have a case where I'm calling a webservice that returns an XmlNode where the OuterXml-property shows a structure of "/Data/SubElement/..." and so on, but when running XPath "/Data" then null is returned, only "/SubElement" works, i.e. the XPath-root seems to be one level lower than the actual document-root.

I'm sure there is a perfectly reasonable explanation for this, or that I'm missing something vital. However I really can't seem to find anything, even though I've read http://msdn.microsoft.com/en-us/library/d271ytdx(VS.80).aspx.

N.B. I do realize that it would be possible to use the XPath "//subroot/elm", but then I might also get other elements further down in the XML structure.

Body:
Since your selecting from the Root/SubElement Try this:

XmlNode xnElm = xnSubRoot.SelectSingleNode("elm");

It will return the first child elm node of the current node.

Edit (from additionals informations provided in comments):

In this specific case, you are obtaning a XmlNode (which is your Data node) from a WebService call. All XPath requests on that XmlNode will be relative to it.

I would suggest that you modify all your XPaths to use a selector like webServiceNode.SelectSingleNode("SubElement/SubSubElement"); . There is no reason to specify absolute XPaths queries here.


问:
How to create a release signed apk file using Gradle?
I would like to have my Gradle build to create a release signed apk file using Gradle.

I'm not sure if the code is correct or if I'm missing a parameter when doing gradle build?

This is some of the code in my build.gradle/build.gradle.kts file:

```<code>android {
    ...
    signingConfigs {
        release {
            storeFile(file("release.keystore"))
            storePassword("******")
            keyAlias("******")
            keyPassword("******")
        }
    }
}
</code>```

The Gradle build finishes SUCCESSFUL, and in my build/apk folder I only see the ...-release-unsigned.apk and ...-debug-unaligned.apk files.

Any suggestions on how to solve this?

答:
If you have the keystore file already, it can be as simple as adding a few parameters to your build command:

```<code>./gradlew assembleRelease \
 -Pandroid.injected.signing.store.file=$KEYFILE \
 -Pandroid.injected.signing.store.password=$STORE_PASSWORD \
 -Pandroid.injected.signing.key.alias=$KEY_ALIAS \
 -Pandroid.injected.signing.key.password=$KEY_PASSWORD
</code>```

No permanent changes to your Android project necessary.

Source: http://www.tinmith.net/wayne/blog/2014/08/gradle-sign-command-line.htm

Body:
I would like to have my Gradle build to create a release signed apk file using Gradle.

I'm not sure if the code is correct or if I'm missing a parameter when doing gradle build?

This is some of the code in my build.gradle/build.gradle.kts file:

android {
    ...
    signingConfigs {
        release {
            storeFile(file("release.keystore"))
            storePassword("******")
            keyAlias("******")
            keyPassword("******")
        }
    }
}

The Gradle build finishes SUCCESSFUL, and in my build/apk folder I only see the ...-release-unsigned.apk and ...-debug-unaligned.apk files.

Any suggestions on how to solve this?

Body:
If you have the keystore file already, it can be as simple as adding a few parameters to your build command:

./gradlew assembleRelease \
 -Pandroid.injected.signing.store.file=$KEYFILE \
 -Pandroid.injected.signing.store.password=$STORE_PASSWORD \
 -Pandroid.injected.signing.key.alias=$KEY_ALIAS \
 -Pandroid.injected.signing.key.password=$KEY_PASSWORD

No permanent changes to your Android project necessary.

Source: http://www.tinmith.net/wayne/blog/2014/08/gradle-sign-command-line.htm


问:
How can I achieve below in nodejs? Need to display output of function in JSON format
I have created a variable, which I have used to calculate the output of a Linux command (gets the number of users). Later I would like to pass that as input with JSON format.

But everytime, it prints 0 instead of the number of users. I tried to look at many posts related to callback, but couldn't relate with the situation. Please help.

```<code>var child;
var count = 0;

child = exec('users | wc -w', function (error, stdout, stderr) {
    console.log(stdout); count = stdout});
    exercise_1_Message = { numberUsers: count };
    res.json(test_1_Message);
});
</code>```

答:
Place exercise_1_Message = { numberUsers: count };res.json(test_1_Message); inside the callback function :

```<code>var child;
let exercise_1_Message;

child = exec('users | wc -w', function (error, stdout, stderr) {
    exercise_1_Message = { numberUsers: stdout.match(/\d+/g)[0] };
    console.log(exercise_1_Message);
    res.json(test_1_Message)
});
</code>```

Body:
I have created a variable, which I have used to calculate the output of a Linux command (gets the number of users). Later I would like to pass that as input with JSON format.

But everytime, it prints 0 instead of the number of users. I tried to look at many posts related to callback, but couldn't relate with the situation. Please help.

var child;
var count = 0;

child = exec('users | wc -w', function (error, stdout, stderr) {
    console.log(stdout); count = stdout});
    exercise_1_Message = { numberUsers: count };
    res.json(test_1_Message);
});

Body:
Place exercise_1_Message = { numberUsers: count };res.json(test_1_Message); inside the callback function :

var child;
let exercise_1_Message;

child = exec('users | wc -w', function (error, stdout, stderr) {
    exercise_1_Message = { numberUsers: stdout.match(/\d+/g)[0] };
    console.log(exercise_1_Message);
    res.json(test_1_Message)
});


问:
Loop through foreach without knowing the index
I would like to Loop throught services but I don't know the index name. They come randomly, example I got 8 and 9 but I do not know them.

```<code>"2": {
    "first_name": "khalfan",
    "last_name": "mussa",
    "date": "2017-06-06 09:21:36",
    "gender": "male",
    "services": {
        "8": {
            "name": "See a Doctor",
            "results": ""
    },
         "9": {
            "name": "Kichocho",
            "results": "FD- 73"
              }
    }
},
</code>```

答:
From @Alive to Die answer, I made some changes and I think this code will loop in your services no matter the index. </p>

```<code> $array = json_decode($json, true);
foreach ($array as $values) {
    foreach ($values as $keys => $value) {
        if (is_array($value)) {
            foreach ($value as $key => $val) {
                if (is_array($val)) {
                    foreach ($val as $k => $v) {
                        echo $k . ":" . $v . "\n";
                    }
                }
            }
        }
    }
}
</code>```

Body:
I would like to Loop throught services but I don't know the index name. They come randomly, example I got 8 and 9 but I do not know them.

"2": {
    "first_name": "khalfan",
    "last_name": "mussa",
    "date": "2017-06-06 09:21:36",
    "gender": "male",
    "services": {
        "8": {
            "name": "See a Doctor",
            "results": ""
    },
         "9": {
            "name": "Kichocho",
            "results": "FD- 73"
              }
    }
},

Body:
From @Alive to Die answer, I made some changes and I think this code will loop in your services no matter the index.

 $array = json_decode($json, true);
foreach ($array as $values) {
    foreach ($values as $keys => $value) {
        if (is_array($value)) {
            foreach ($value as $key => $val) {
                if (is_array($val)) {
                    foreach ($val as $k => $v) {
                        echo $k . ":" . $v . "\n";
                    }
                }
            }
        }
    }
}


问:
Convert MIDI file to audio file using an SF2 soundfont library with audiokit
Is it possible to convert a MIDI file to an audio file (e.g. MP3) using "audiokit" for iOS and an existing soundfont library (SF2)? Thanks for all answers.</p>

答:
Yes, its possible. Use AKMIDI, AKMIDISampler, loadSoundFont, and renderToFile to make this happen.

http://audiokit.io/docs/Classes/AKMIDI.html

http://audiokit.io/docs/Classes/AKSampler.html

https://github.com/AudioKit/AudioKit/blob/master/AudioKit/Common/Nodes/Playback/Sampler/AKSampler%2BSoundFont.swift#L33

https://github.com/AudioKit/AudioKit/blob/develop/AudioKit/Common/Internals/AudioKit.swift#L558


问:
Set Default date 1 year out from insert date
I currently have a table with the following layout:

```<code>create table x (
   insert_date date DEFAULT sysdate,
   last_update_date date,
   expiration_date date
)
</code>```

If I write to this table the value for insert_date will be obviously the exact time in which it was written. My Question is, is there a way to set a default value for expiration_date that is literally just "sysdate + 1 year" ?

答:
You could use the ADD_MONTHS function.

Example:

```<code>create table x2 (
   insert_date date DEFAULT sysdate,
   LAST_UPDATE_DATE date,
   EXPIRATION_DATE date DEFAULT add_months(sysdate, 12)
);

insert into x2 (LAST_UPDATE_DATE) values (TO_DATE('2017-11-17', 'YYYY-MM-DD'));
commit;
</code>```

Here is an example using a trigger.

```<code>create or replace trigger x2_TX
    before insert on x2 for each row
begin
   :new.EXPIRATION_DATE := ADD_MONTHS(sysdate, 12);
end;
</code>```

Stilgar has a great point about my first example not being "developer safe" relative to the second.  I would have suggested the former in the interest of simplicity, now I would do what is considered best practice on your team.

Body:
I currently have a table with the following layout:

create table x (
   insert_date date DEFAULT sysdate,
   last_update_date date,
   expiration_date date
)

If I write to this table the value for insert_date will be obviously the exact time in which it was written. My Question is, is there a way to set a default value for expiration_date that is literally just "sysdate + 1 year" ?

Body:
You could use the ADD_MONTHS function.

Example:

create table x2 (
   insert_date date DEFAULT sysdate,
   LAST_UPDATE_DATE date,
   EXPIRATION_DATE date DEFAULT add_months(sysdate, 12)
);

insert into x2 (LAST_UPDATE_DATE) values (TO_DATE('2017-11-17', 'YYYY-MM-DD'));
commit;

Here is an example using a trigger.

create or replace trigger x2_TX
    before insert on x2 for each row
begin
   :new.EXPIRATION_DATE := ADD_MONTHS(sysdate, 12);
end;

Stilgar has a great point about my first example not being "developer safe" relative to the second.  I would have suggested the former in the interest of simplicity, now I would do what is considered best practice on your team.


问:
fix matplotlib 'not installed as framework' error w/out changing .matplotlib config in $HOME
context

machine: 64-bit Mac

OS: macOS 10.10.5

error msg

following course [Jerry Kurata 'Tensorflow: Getting Started'] ran the following:

```<code>import tensorflow as tf
import numpy as np
import math
import matplotlib.pyplot as plt
import matplotlib.animation as animation

num_house = 160
np.random.seed(42)
house_size = np.random.randint(low=1000, high=3500, size=num_house)

np.random.seed(42)
house_price = house_size * 100.0 + np.random.randint(low=20000, high=70000, size=num_house)

plt.plot(house_size, house_price, "bx")
plt.xlabel("price")
plt.ylabel("size")
plt.show
</code>```

received this error

**RuntimeError**: Python is not installed as a framework. The Mac OS X backend will not be able to function correctly if Python is not installed as a framework.

attempt to fix

have consulted this answer [https://stackoverflow.com/a/21789908/6813490] but concerned to change anything related to global matplotlib settings in a way that would affect other projects outside this virtual environment

答:
see the above answer Installation Issue with matplotlib Python and reference one of the comments:

Some users may not want to change the backend for all of their
  scripts. This page --
  matplotlib.org/faq/usage_faq.html#what-is-a-backend -- tells another
  way: include the statement import matplotlib as mpl then
  mpl.use('TkAgg') right after that, then do the import for pyplot.

and set the matplotlib backend in the imports, like so

```<code>import tensorflow as tf
import numpy as np
import math

## SET BACKEND
import matplotlib as mpl
mpl.use('TkAgg')

import matplotlib.pyplot as plt
import matplotlib.animation as animation

num_house = 160
np.random.seed(42)
house_size = np.random.randint(low=1000, high=3500, size=num_house)

np.random.seed(42)
house_price = house_size * 100.0 + np.random.randint(low=20000, high=70000, size=num_house)

plt.plot(house_size, house_price, "bx")
plt.xlabel("price")
plt.ylabel("size")
plt.show
</code>```

in this way, you won't need to touch the matplotlib in $HOME

Body:
context

machine: 64-bit Mac

OS: macOS 10.10.5

error msg

following course [Jerry Kurata 'Tensorflow: Getting Started'] ran the following:

import tensorflow as tf
import numpy as np
import math
import matplotlib.pyplot as plt
import matplotlib.animation as animation

num_house = 160
np.random.seed(42)
house_size = np.random.randint(low=1000, high=3500, size=num_house)

np.random.seed(42)
house_price = house_size * 100.0 + np.random.randint(low=20000, high=70000, size=num_house)

plt.plot(house_size, house_price, "bx")
plt.xlabel("price")
plt.ylabel("size")
plt.show

received this error

**RuntimeError**: Python is not installed as a framework. The Mac OS X backend will not be able to function correctly if Python is not installed as a framework.

attempt to fix

have consulted this answer [https://stackoverflow.com/a/21789908/6813490] but concerned to change anything related to global matplotlib settings in a way that would affect other projects outside this virtual environment

Body:
see the above answer Installation Issue with matplotlib Python and reference one of the comments:

Some users may not want to change the backend for all of their
  scripts. This page --
  matplotlib.org/faq/usage_faq.html#what-is-a-backend -- tells another
  way: include the statement import matplotlib as mpl then
  mpl.use('TkAgg') right after that, then do the import for pyplot.

and set the matplotlib backend in the imports, like so

import tensorflow as tf
import numpy as np
import math

## SET BACKEND
import matplotlib as mpl
mpl.use('TkAgg')

import matplotlib.pyplot as plt
import matplotlib.animation as animation

num_house = 160
np.random.seed(42)
house_size = np.random.randint(low=1000, high=3500, size=num_house)

np.random.seed(42)
house_price = house_size * 100.0 + np.random.randint(low=20000, high=70000, size=num_house)

plt.plot(house_size, house_price, "bx")
plt.xlabel("price")
plt.ylabel("size")
plt.show

in this way, you won't need to touch the matplotlib in $HOME


问:
Running Java 9 application with docker doesn't work - UnsupportedClassVersionError
I changed my application from Java 8 to Java 9.
Changed the Windows system environment variable (path) and the JAVA_HOME to Java 9 (jdk-9.0.1).

When running the application in the IDE (IntelliJ) it works fine. It also compiles without problems with sbt. Just running the application with docker doesn't work.

The application seems to be compiled successfully with Java 9 but docker tries to run it with Java 8 (this is what I read from the exception message).

Commands:

```<code>sbt docker:publish

docker run --rm -p 9000:9000 eu.gcr.io/the-repository-name/the-image-name:1.0
</code>```

I get the following error:

```<code>Exception in thread "main" java.lang.UnsupportedClassVersionError:
    Module has been compiled by a more recent version of the
    Java Runtime (class file version 53.0), this version of the
    Java Runtime only recognizes class file versions up to 52.0
        at java.lang.ClassLoader.defineClass1(Native Method)
        at java.lang.ClassLoader.defineClass(ClassLoader.java:763)
        at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
        at java.net.URLClassLoader.defineClass(URLClassLoader.java:467)
        at java.net.URLClassLoader.access$100(URLClassLoader.java:73)
        at java.net.URLClassLoader$1.run(URLClassLoader.java:368)
        at java.net.URLClassLoader$1.run(URLClassLoader.java:362)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:361)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
        at play.api.inject.Modules$.locate(Module.scala:119)
        at play.api.inject.guice.GuiceableModule$.loadModules(GuiceInjectorBuilder.scala:276)
        at play.api.inject.guice.GuiceApplicationBuilder$.$anonfun$$lessinit$greater$default$9$1(GuiceApplicationBuilder.scala:30)
        at play.api.inject.guice.GuiceApplicationBuilder.applicationModule(GuiceApplicationBuilder.scala:102)
        at play.api.inject.guice.GuiceBuilder.injector(GuiceInjectorBuilder.scala:185)
        at play.api.inject.guice.GuiceApplicationBuilder.build(GuiceApplicationBuilder.scala:137)
        at play.api.inject.guice.GuiceApplicationLoader.load(GuiceApplicationLoader.scala:21)
        at play.core.server.ProdServerStart$.start(ProdServerStart.scala:51)
        at play.core.server.ProdServerStart$.main(ProdServerStart.scala:25)
        at play.core.server.ProdServerStart.main(ProdServerStart.scala)
</code>```

What do I have to do, that Docker uses Java 9?

```<code>java --version
java 9.0.1
Java(TM) SE Runtime Environment (build 9.0.1+11)
Java HotSpot(TM) 64-Bit Server VM (build 9.0.1+11, mixed mode)

docker version
Client:
 Version:      17.10.0-ce
 API version:  1.33
 Go version:   go1.8.3
 Git commit:   f4ffd25
 Built:        Tue Oct 17 19:00:02 2017
 OS/Arch:      windows/amd64

Server:
 Version:      17.10.0-ce
 API version:  1.33 (minimum version 1.12)
 Go version:   go1.8.3
 Git commit:   f4ffd25
 Built:        Tue Oct 17 19:05:23 2017
 OS/Arch:      linux/amd64
 Experimental: true
</code>```

Play Version: 2.6.7

Scala Version 2.12.4

SBT Version: 1.0.2

sbt-native-packager: 1.3.1

答:
The error means that you are trying to run code compiled using a newer version of Java (9 which has class version 53.0) in an older version of Java (8 which has class version 52.0). So, your docker image probably has Java 8 installed. Let's do some detective work. :-)

If I understand correctly, you are using sbt-native-packager to generate your Docker image. If so, sbt-native-packager is using openjdk:latest image as the base image, as you can see here:

https://github.com/sbt/sbt-native-packager/blob/v1.3.1/src/main/scala/com/typesafe/sbt/packager/docker/DockerPlugin.scala#L69

Version 1.3.1 is the version used by Play 2.6.7, as you can also see here:

https://github.com/playframework/playframework/blob/2.6.7/framework/project/plugins.sbt#L8

The problem is that openjdk:latest image uses Java 8. You can confirm that by looking at the latest code linked at the image page. Here is the code:

https://github.com/docker-library/openjdk/blob/a893fe3cd82757e7bccc0948c88bfee09bd916c3/8-jdk/Dockerfile#L38-L43

Given that, you may want to change dockerBaseImage to use a base image that uses Java 9, for example:

```<code>dockerBaseImage := "9-jdk"
</code>```

You can see a complete list of image versions here: https://hub.docker.com/_/openjdk/

Body:
I changed my application from Java 8 to Java 9.
Changed the Windows system environment variable (path) and the JAVA_HOME to Java 9 (jdk-9.0.1).

When running the application in the IDE (IntelliJ) it works fine. It also compiles without problems with sbt. Just running the application with docker doesn't work.

The application seems to be compiled successfully with Java 9 but docker tries to run it with Java 8 (this is what I read from the exception message).

Commands:

sbt docker:publish

docker run --rm -p 9000:9000 eu.gcr.io/the-repository-name/the-image-name:1.0

I get the following error:

Exception in thread "main" java.lang.UnsupportedClassVersionError:
    Module has been compiled by a more recent version of the
    Java Runtime (class file version 53.0), this version of the
    Java Runtime only recognizes class file versions up to 52.0
        at java.lang.ClassLoader.defineClass1(Native Method)
        at java.lang.ClassLoader.defineClass(ClassLoader.java:763)
        at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
        at java.net.URLClassLoader.defineClass(URLClassLoader.java:467)
        at java.net.URLClassLoader.access$100(URLClassLoader.java:73)
        at java.net.URLClassLoader$1.run(URLClassLoader.java:368)
        at java.net.URLClassLoader$1.run(URLClassLoader.java:362)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:361)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
        at play.api.inject.Modules$.locate(Module.scala:119)
        at play.api.inject.guice.GuiceableModule$.loadModules(GuiceInjectorBuilder.scala:276)
        at play.api.inject.guice.GuiceApplicationBuilder$.$anonfun$$lessinit$greater$default$9$1(GuiceApplicationBuilder.scala:30)
        at play.api.inject.guice.GuiceApplicationBuilder.applicationModule(GuiceApplicationBuilder.scala:102)
        at play.api.inject.guice.GuiceBuilder.injector(GuiceInjectorBuilder.scala:185)
        at play.api.inject.guice.GuiceApplicationBuilder.build(GuiceApplicationBuilder.scala:137)
        at play.api.inject.guice.GuiceApplicationLoader.load(GuiceApplicationLoader.scala:21)
        at play.core.server.ProdServerStart$.start(ProdServerStart.scala:51)
        at play.core.server.ProdServerStart$.main(ProdServerStart.scala:25)
        at play.core.server.ProdServerStart.main(ProdServerStart.scala)

What do I have to do, that Docker uses Java 9?

java --version
java 9.0.1
Java(TM) SE Runtime Environment (build 9.0.1+11)
Java HotSpot(TM) 64-Bit Server VM (build 9.0.1+11, mixed mode)

docker version
Client:
 Version:      17.10.0-ce
 API version:  1.33
 Go version:   go1.8.3
 Git commit:   f4ffd25
 Built:        Tue Oct 17 19:00:02 2017
 OS/Arch:      windows/amd64

Server:
 Version:      17.10.0-ce
 API version:  1.33 (minimum version 1.12)
 Go version:   go1.8.3
 Git commit:   f4ffd25
 Built:        Tue Oct 17 19:05:23 2017
 OS/Arch:      linux/amd64
 Experimental: true

Play Version: 2.6.7

Scala Version 2.12.4

SBT Version: 1.0.2

sbt-native-packager: 1.3.1

Body:
The error means that you are trying to run code compiled using a newer version of Java (9 which has class version 53.0) in an older version of Java (8 which has class version 52.0). So, your docker image probably has Java 8 installed. Let's do some detective work. :-)

If I understand correctly, you are using sbt-native-packager to generate your Docker image. If so, sbt-native-packager is using openjdk:latest image as the base image, as you can see here:

https://github.com/sbt/sbt-native-packager/blob/v1.3.1/src/main/scala/com/typesafe/sbt/packager/docker/DockerPlugin.scala#L69

Version 1.3.1 is the version used by Play 2.6.7, as you can also see here:

https://github.com/playframework/playframework/blob/2.6.7/framework/project/plugins.sbt#L8

The problem is that openjdk:latest image uses Java 8. You can confirm that by looking at the latest code linked at the image page. Here is the code:

https://github.com/docker-library/openjdk/blob/a893fe3cd82757e7bccc0948c88bfee09bd916c3/8-jdk/Dockerfile#L38-L43

Given that, you may want to change dockerBaseImage to use a base image that uses Java 9, for example:

dockerBaseImage := "9-jdk"

You can see a complete list of image versions here: https://hub.docker.com/_/openjdk/


问:
Efficient way to store array to persistent memory in python
Let's say we have a long one dimensional array like this with millions of elements:

[0,1,1,1,1,2,1,1,1,1,1,1,1,...,1,2,2,2,2,2,2,2,4,4,4,4,4,4,4,4,4,3,4,1,1,1,1]

If there was just one repeating element we could use a sparse array but since it can be any kind of integer value (or a set of nominal elements), this does not do the trick I suppose (or am I wrong there?).

I read about PyTables being able to compress data like this on the fly, based on HDF5 files, as far as I could see, this seems like the go to option for python.

Has someone experience with it and can tell whether that is an adequate route to go or are there other ways, that are even more efficient in terms of cpu as well as memory usage (trading the least amount of CPU cycles into decreased memory size).

答:
Quoting this wonderful answer, that helped me a few years ago:

Python-standard shelve module provides dict-like interface for persistent objects. It works with many database backends and is not limited by RAM. The advantage of using shelve over direct work with databases is that most of your existing code remains as it was. This comes at the cost of speed (compared to in-RAM dicts) and at the cost of flexibility (compared to working directly with databases).

If I understand your question correctly(storing is the concern, not the reading), shelve is absolutely the way to go.

Will be monitoring the thread for any other creating answers on the topic. :-)


问:
qmake touch function on windows
The qmake manual documents a touch function to update the time stamp of a file, see: touch(filename, reference_filename). It is recommended here to update the timestamp on a file, e.g.:

```<code>version.commands = touch $$version.target
</code>```

Note: the qmake manual documents two parameters, e.g.:

```<code>version.commands = touch $$version.target $$version.depends
</code>```

However, I can't get the touch function to work on Windows using either call. I suspect that qmake is simply calling the linux touch command, since it works fine on Fedora 23.

A workaround is to create a touch.cmd command file on Windows, e.g.:

```<code>@COPY /B %1+,, %1
</code>```

and use the following in the .pro file:

```<code>version.commands = $$system(touch $$version.target)
</code>```

But I would prefer to use the qmake touch function...

What is the correct way to invoke it in a .pro file so that it works on Windows?

答:
In using qmake, it's critical to remember what things are happening on invocation of qmake and what's happening during the subsequent make/nmake call.

Anything that's specified after version.commands = is going to be executed when make gets invoked.

On the other hand, touch() is a qmake function that will get invoked when you run qmake.

Looking in the Qt source code dev branch as of today, there are just 4 uses of touch() within Qt itself, all in the qtbase/mkspecs/features directory, and none in the context of a .commands construct.

Title: qmake touch function on windows

Body:
The qmake manual documents a touch function to update the time stamp of a file, see: touch(filename, reference_filename). It is recommended here to update the timestamp on a file, e.g.:

version.commands = touch $$version.target

Note: the qmake manual documents two parameters, e.g.:

version.commands = touch $$version.target $$version.depends

However, I can't get the touch function to work on Windows using either call. I suspect that qmake is simply calling the linux touch command, since it works fine on Fedora 23.

A workaround is to create a touch.cmd command file on Windows, e.g.:

@COPY /B %1+,, %1

and use the following in the .pro file:

version.commands = $$system(touch $$version.target)

But I would prefer to use the qmake touch function...

What is the correct way to invoke it in a .pro file so that it works on Windows?


问:
How to find the mean of certain values in a large dataframe using loop
In R, I have a data frame that looks like this:

```<code>         Female.ID    Mate.ID  relatedness
    1           A1         C1       0.0000
    2           A1         D1       0.0000
    3           A1         E1       0.5062
    4           A1         F1           NA
    5           B1         G1       0.0425
    6           B1         H1       0.0000
    7           B1         I1       0.0349
    8           B1         J1       0.0000
    9           B1         K1       0.0000
    10          B1         L1       0.0887
    11          B1         M1       0.1106
    12          B1         N1       0.0000
</code>```

I want to create a new dataframe and find the mean relatedness of all the mates for female.ID A1 and the mean relatedness for all the mates of female.ID
B1, etc.

I want something like this:

```<code>    Female.ID    mean.relatedness
           A1              0.1687
           B1              0.0346
</code>```

This dataframe is much bigger than this example one, which is why I'm not just subsetting for the female one by one and finding the mean relatedness. I was thinking of doing some kind of for loop, but I'm not sure how to start it off.

答:
The idea is:

to do a group by "Female.ID"

then summarize using the mean while ignoring the NA.

If the data is too large you may need to use a faster package like data.table (which is a fast package with a simple syntax). for more details please take a look at this link data.table vs dplyr: can one do something well the other can't or does poorly?

In general looping is not optimized in R. It can be kept as a final solution only if the treatment can't be supported by the package.

Here the syntax using data.table (df being the initial data.frame)

```<code>library(data.table)

dt<- as.data.table(df)
dt1 <- dt[, .(mean.relatedness= mean(relatedness, na.rm = TRUE)),
            by="Female.ID"]
>dt1
 Female.ID mean.relatedness
1:        A1        0.1687333
2:        B1        0.0345875
</code>```

note that the grouping-by can be done over a multi-variables vector, the summarizing function can be other than the mean, and na.rm = TRUE is needed to ignore the NA while summarizing.

Body:
In R, I have a data frame that looks like this:

         Female.ID    Mate.ID  relatedness
    1           A1         C1       0.0000
    2           A1         D1       0.0000
    3           A1         E1       0.5062
    4           A1         F1           NA
    5           B1         G1       0.0425
    6           B1         H1       0.0000
    7           B1         I1       0.0349
    8           B1         J1       0.0000
    9           B1         K1       0.0000
    10          B1         L1       0.0887
    11          B1         M1       0.1106
    12          B1         N1       0.0000

I want to create a new dataframe and find the mean relatedness of all the mates for female.ID A1 and the mean relatedness for all the mates of female.ID
B1, etc.

I want something like this:

    Female.ID    mean.relatedness
           A1              0.1687
           B1              0.0346

This dataframe is much bigger than this example one, which is why I'm not just subsetting for the female one by one and finding the mean relatedness. I was thinking of doing some kind of for loop, but I'm not sure how to start it off.

Body:
The idea is:

to do a group by "Female.ID"

then summarize using the mean while ignoring the NA.

If the data is too large you may need to use a faster package like data.table (which is a fast package with a simple syntax). for more details please take a look at this link data.table vs dplyr: can one do something well the other can't or does poorly?

In general looping is not optimized in R. It can be kept as a final solution only if the treatment can't be supported by the package.

Here the syntax using data.table (df being the initial data.frame)

library(data.table)

dt<- as.data.table(df)
dt1 <- dt[, .(mean.relatedness= mean(relatedness, na.rm = TRUE)),
            by="Female.ID"]
>dt1
 Female.ID mean.relatedness
1:        A1        0.1687333
2:        B1        0.0345875

note that the grouping-by can be done over a multi-variables vector, the summarizing function can be other than the mean, and na.rm = TRUE is needed to ignore the NA while summarizing.


问:
How to change the order in which variables are printed in prolog?
This is a homework problem, but I just need a simple question answered.  I am supposed to print all the possible ways a knight can jump on a chess board from it's position.  I am getting the correct numbers but I don't seem to get the correct output that I want.  For example:

```<code> ?- knight(8,1,R,C)
</code>```

is supposed to print out the output as:

```<code>C = 3
R = 7;
C = 2
R = 6;
</code>```

But I get the exact opposite as in:

```<code>R = 7,
C = 3;
R = 6,
C = 2.
</code>```

here is my code:

```<code>knight(C, R, C2, R2):-
      C2 is C - 1,R2 is R + 2,
      withinBoard(C2,R2)
   ;  C2 is C + 1,R2 is R + 2,
      withinBoard(C2,R2)
   ;  C2 is C + 2, R2 is R + 1,
      withinBoard(C2,R2)
   ;  C2 is C + 2, R2 is R - 1,
      withinBoard(C2,R2)
   ;  C2 is C + 1, R2 is R - 2,
      withinBoard(C2,R2)
   ;  C2 is C - 1, R2 is R - 2,
      withinBoard(C2,R2)
   ;  C2 is C - 2, R2 is R - 1,
      withinBoard(C2,R2)
   ;  C2 is C - 2, R2 is R + 1,
      withinBoard(C2,R2).

 withinBoard(Col,Row):-
        Row < 9, Row > 0, Col < 9, Col > 0.
</code>```

答:
```<code>?- C=C,knight(8,1,R,C).
   C = 3, R = 7
;  C = 2, R = 6.
</code>```

Both orders are fine and mean exactly the same.

Many current Prolog systems print variables in the very order determined by read_term(Query, [variable_names(VN_list)]). which they use to read a term. So the variable that occurs leftmost is the first to print its answer substitution.

In the past, some systems ordered VN_list by the name of the variables. Which actually did make sense as the order was left unspecified by the standard. In the meantime, this has been corrected in Cor.3. It seems your homework dates from an earlier time since 'C' @< 'R'. To get the very precise order, you now need to add an artificial goal in front. I took C=C which is always true.

All that said, I do not believe that your instructor will insist on the very precise order.

Body:
This is a homework problem, but I just need a simple question answered.  I am supposed to print all the possible ways a knight can jump on a chess board from it's position.  I am getting the correct numbers but I don't seem to get the correct output that I want.  For example:

 ?- knight(8,1,R,C)

is supposed to print out the output as:

C = 3
R = 7;
C = 2
R = 6;

But I get the exact opposite as in:

R = 7,
C = 3;
R = 6,
C = 2.

here is my code:

knight(C, R, C2, R2):-
      C2 is C - 1,R2 is R + 2,
      withinBoard(C2,R2)
   ;  C2 is C + 1,R2 is R + 2,
      withinBoard(C2,R2)
   ;  C2 is C + 2, R2 is R + 1,
      withinBoard(C2,R2)
   ;  C2 is C + 2, R2 is R - 1,
      withinBoard(C2,R2)
   ;  C2 is C + 1, R2 is R - 2,
      withinBoard(C2,R2)
   ;  C2 is C - 1, R2 is R - 2,
      withinBoard(C2,R2)
   ;  C2 is C - 2, R2 is R - 1,
      withinBoard(C2,R2)
   ;  C2 is C - 2, R2 is R + 1,
      withinBoard(C2,R2).

 withinBoard(Col,Row):-
        Row < 9, Row > 0, Col < 9, Col > 0.

Body:
?- C=C,knight(8,1,R,C).
   C = 3, R = 7
;  C = 2, R = 6.

Both orders are fine and mean exactly the same.

Many current Prolog systems print variables in the very order determined by read_term(Query, [variable_names(VN_list)]). which they use to read a term. So the variable that occurs leftmost is the first to print its answer substitution.

In the past, some systems ordered VN_list by the name of the variables. Which actually did make sense as the order was left unspecified by the standard. In the meantime, this has been corrected in Cor.3. It seems your homework dates from an earlier time since 'C' @< 'R'. To get the very precise order, you now need to add an artificial goal in front. I took C=C which is always true.

All that said, I do not believe that your instructor will insist on the very precise order.


问:
Can I configure tomcat to use different JREs for different WARs?
I'm currently running tomcat7 on ubuntu but this question goes for any version. </p>

答:
I don't believe there's any way to use multiple JREs in the same Java process;  but it is (ultimately) possible to run different webapps in different Java processes and nevertheless make them appear (to the user) to be the same site.

You could, for example, run 2 Tomcat processes -- on 2 different ports -- and use a single Apache HTTPD in front of them (with 2 AJP connectors).


问:
jQuery hover effect uses opacity, which IE doesn't support
Below is my code for use on this page: here

```<code>$(document).ready(function(){
$('.jcarousel-skin-tango a').hover(
        function() {
            $(this).find('.rollover').stop().fadeTo(500, 1);

        },
        function() {
            $(this).find('.rollover').stop().fadeTo(500, 0);

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

The problem lies within IE 8 and below. When you hover over any of the slide images, the hover turns to black (because IE doesn't support 'opacity'). I basically need a new way of writing this so the same effect is achieved without a grey/black box appearing in IE.  Any ideas ?

答:
AFAIK, there is no way to deal with IE's problem, at least not in your case.
Internet Explorer doesn't play well with javascript/jQuery opacity changes (alpha blending generally, show(); function included), especially when using (semi)transparent images.
IE can't grasp fading of an alpha-blended element.

My suggestion: use slideDown/slideUp/other functions, or .animate on element properties to get the closest effect without using alpha blending.

good luck.

Body:
Below is my code for use on this page: here

$(document).ready(function(){
$('.jcarousel-skin-tango a').hover(
        function() {
            $(this).find('.rollover').stop().fadeTo(500, 1);

        },
        function() {
            $(this).find('.rollover').stop().fadeTo(500, 0);

        }
    )
});

The problem lies within IE 8 and below. When you hover over any of the slide images, the hover turns to black (because IE doesn't support 'opacity'). I basically need a new way of writing this so the same effect is achieved without a grey/black box appearing in IE.  Any ideas ?


问:
In Haskell how can you multiply a list of string?
I'm trying to write a function that takes a list of Strings and an Int and returns that list of strings in which every string is "int" times. That is:

```<code>duplicate :: [String] -> Int -> [String]
duplicate ["ab","ac","yt","hfg","lkj","poi"] 2
</code>```

the output should be

```<code>["ab","ab","ac","ac","yt","yt","hfg","hfg","lkj","lkj","poi","poi"]
</code>```

答:
```<code>duplicate = (. replicate) . (>>=)
</code>```

or more basic

```<code>duplicate xs n = concatMap (replicate n) xs
</code>```

if you want to have list multiplication by notation as well

```<code>> let (**) :: [a] -> Int -> [a]
|     (**) = (. replicate) . (>>=)

> ["a","b"]**3
["a","a","a","b","b","b"]
</code>```

Body:
I'm trying to write a function that takes a list of Strings and an Int and returns that list of strings in which every string is "int" times. That is:

duplicate :: [String] -> Int -> [String]
duplicate ["ab","ac","yt","hfg","lkj","poi"] 2

the output should be

["ab","ab","ac","ac","yt","yt","hfg","hfg","lkj","lkj","poi","poi"]

Body:
duplicate = (. replicate) . (>>=)

or more basic

duplicate xs n = concatMap (replicate n) xs

if you want to have list multiplication by notation as well

> let (**) :: [a] -> Int -> [a]
|     (**) = (. replicate) . (>>=)

> ["a","b"]**3
["a","a","a","b","b","b"]


问:
The module has been successfully installed but then it's not found when imported? - Python
I'm trying to use the graphviz Python module and I've run into this problem:
I pip installed it in my command prompt, but it's not showing up in IPython.  I have additionally a Python 3.5 (32-bit) interpreter where it IS showing up, but I'm trying to figure out how to have it installed so it works in IPython.

I've been recommended to include the sys.path for each of the interpreters.

Anyone have any ideas as to how I'd change it?

答:
Try this:

```<code>conda install -c conda-forge python-graphviz
</code>```

Or this:
Conda comes with its own pip. Do

```<code>conda install pip
</code>```

Then find the pip executable and run that directly (i.e /path/to/anacondapip install graphviz)

Body:
Try this:

conda install -c conda-forge python-graphviz

Or this:
Conda comes with its own pip. Do

conda install pip

Then find the pip executable and run that directly (i.e /path/to/anacondapip install graphviz)


问:
Select option with value="" gets replaced by the text
I am working on a HTML code which has Select tag used in it. I am trying to add below given code to get the placeholder text for Select list but somehow in the generated HTML on web page I see that value="" gets replaced by value="Select"

```<code><select id="call_quality_issue_type" required="true">
    <option value="">Select</option>
</select>
</code>```

As a result I am not able to use the .invalid property on select in the css to get the placeholder behavior working

答:
if you are looking for a placeholder, you may want use disabled on the option tag :

<select id="call_quality_issue_type" required="true">
    <option disabled selected value> -- select an option -- </option>
    <option>Option 1</option>
    <option>Option 2</option>
    <option>Option 3</option>
</select>```

Body:
I am working on a HTML code which has Select tag used in it. I am trying to add below given code to get the placeholder text for Select list but somehow in the generated HTML on web page I see that value="" gets replaced by value="Select"

<select id="call_quality_issue_type" required="true">
    <option value="">Select</option>
</select>

As a result I am not able to use the .invalid property on select in the css to get the placeholder behavior working


问:
How do I have mails to a specific address trigger actions on a web server?
What I'm trying to do is figure up how I can configure a mail server such that mails to a specific address will trigger certain actions- e.g. inserting the subject line into a MySQL database, etc. This is for a web app in LAMP- basically I want people to be able to add things automatically via email if they'd rather do that than use the web interface. Kind of like how e.g. with Evernote you can send a mail to your custom address to add a note that way.

I realize this is a pretty vague question, what I'm looking for is a general place to start looking and learning. I'm reasonably familiar with website tech but when it comes to mail servers I'm completely clueless.  I'm not looking for any specific implementation: Rather I just want to know what are the basics I need familiarize myself to be able to attack the problem.

答: This is traditionally handled on unix-like systems using fetchmail and/or procmail.</p>


问:
How to get substring between nth and n+1th occurrence of pipe '|' in shell script
I have a large text file (20 million records) with all rows in below format

```<code>task|action||r1_c1|r1_c2|r1_c3
task|action||r2_c1|r2_c2|r2_c3
task|action||r3_c1|r3_c2|r3_c3
task|action||r4_c1|r4_c2|r4_c3
</code>```

My requirement is to print column 2 from nth row where n is my input. Column number is fixed but row number will change based on input.

Expected Output  if Input parameter (Line Number) is 3 -

```<code>r3_c2
</code>```

I can read file line by line and read nth line in variable

```<code>LineOfInterest=$(awk 'NR == n' n=$line $InputFile)
</code>```

Next I need to print values between 4th and 5th occurrence of pipe.

I believe it can be achieved using sed but now sure how to write pattern for same.

Body:
I have a large text file (20 million records) with all rows in below format

task|action||r1_c1|r1_c2|r1_c3
task|action||r2_c1|r2_c2|r2_c3
task|action||r3_c1|r3_c2|r3_c3
task|action||r4_c1|r4_c2|r4_c3

My requirement is to print column 2 from nth row where n is my input. Column number is fixed but row number will change based on input.

Expected Output  if Input parameter (Line Number) is 3 -

r3_c2

I can read file line by line and read nth line in variable

LineOfInterest=$(awk 'NR == n' n=$line $InputFile)

Next I need to print values between 4th and 5th occurrence of pipe.

I believe it can be achieved using sed but now sure how to write pattern for same.

Body:
You ask for sed so you can try

n=3;sed -n "$n"'s/\([^|]*|\)\{4\}\([^|]*\).*/\2/p' infile


问:
Scikit-learn balanced subsampling
I'm trying to create N balanced random subsamples of my large unbalanced dataset. Is there a way to do this simply with scikit-learn / pandas or do I have to implement it myself? Any pointers to code that does this?

These subsamples should be random and can be overlapping as I feed each to separate classifier in a very large ensemble of classifiers.

In Weka there is tool called spreadsubsample, is there equivalent in sklearn?
http://wiki.pentaho.com/display/DATAMINING/SpreadSubsample

(I know about weighting but that's not what I'm looking for.)

答: There now exists a full-blown python package to address imbalanced data. It is available as a sklearn-contrib package at https://github.com/scikit-learn-contrib/imbalanced-learn</p>

Title: Scikit-learn balanced subsampling