问:
How do I create ColorStateList programmatically?
I am trying to create a ColorStateList programatically  using this:

```<code>ColorStateList stateList = new ColorStateList(states, colors);
</code>```

But I am not sure what are the two parameters.

As per the documentation:

```<code>public ColorStateList (int[][] states, int[] colors)
</code>```

Added in API level 1

Creates a ColorStateList that returns the specified mapping from states to colors.

Can somebody please explain me how to create this?

What is the meaning of two-dimensional array for states?

答:
Sometimes this will be enough:

```<code>int colorInt = getResources().getColor(R.color.ColorVerificaLunes);
ColorStateList csl = ColorStateList.valueOf(colorInt);
</code>```

Kotlin:

```<code>val colorInt: Int = context.getColor(R.color.ColorVerificaLunes)
val csl = ColorStateList.valueOf(colorInt)
</code>```

Body:
I am trying to create a ColorStateList programatically  using this:

ColorStateList stateList = new ColorStateList(states, colors);

But I am not sure what are the two parameters.

As per the documentation:

public ColorStateList (int[][] states, int[] colors)

Added in API level 1

Creates a ColorStateList that returns the specified mapping from states to colors.

Can somebody please explain me how to create this?

What is the meaning of two-dimensional array for states?

Body:
Sometimes this will be enough:

int colorInt = getResources().getColor(R.color.ColorVerificaLunes);
ColorStateList csl = ColorStateList.valueOf(colorInt);

Kotlin:

val colorInt: Int = context.getColor(R.color.ColorVerificaLunes)
val csl = ColorStateList.valueOf(colorInt)

ContentLicense: CC BY-SA 4.0


来源: stackexchange

问:
Build zeppelin-0.7.0 master branch with spark 2.0 failed with 'yarn install --no-lockfile' failed
i tried to build the zeppelin-0.7.0 master branch downloaded from github, but failed .
the build command:

```<code>  mvn  package  -Pyarn -Pbuild-distr -Pspark-2.0 -Dspark.version=2.0.1  -Phadoop-2.6  -Dhadoop.version=2.6.0 -Pscala-2.11 -Ppyspark -DskipTests -X
</code>```

the output stacktrace is:

```<code>[ERROR] error Command failed with exit code 1.
[INFO] info Visit https://yarnpkg.com/en/docs/cli/install for documentation about this command.
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 27.397 s
[INFO] Finished at: 2017-01-14T11:39:00+08:00
[INFO] Final Memory: 19M/228M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal com.github.eirslett:frontend-maven-plugin:1.3:yarn (yarn install) on project zeppelin-web: Failed to run task: 'yarn install --no-lockfile' failed. (error code 1) -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal com.github.eirslett:frontend-maven-plugin:1.3:yarn (yarn install) on project zeppelin-web: Failed to run task
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:212)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:116)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:80)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:51)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:307)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:193)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:106)
    at org.apache.maven.cli.MavenCli.execute(MavenCli.java:863)
    at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:288)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:199)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)
Caused by: org.apache.maven.plugin.MojoFailureException: Failed to run task
    at com.github.eirslett.maven.plugins.frontend.mojo.AbstractFrontendMojo.execute(AbstractFrontendMojo.java:95)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:134)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:207)
    ... 20 more
Caused by: com.github.eirslett.maven.plugins.frontend.lib.TaskRunnerException: 'yarn install --no-lockfile' failed. (error code 1)
    at com.github.eirslett.maven.plugins.frontend.lib.YarnTaskExecutor.execute(YarnTaskExecutor.java:61)
    at com.github.eirslett.maven.plugins.frontend.mojo.YarnMojo.execute(YarnMojo.java:65)
    at com.github.eirslett.maven.plugins.frontend.mojo.AbstractFrontendMojo.execute(AbstractFrontendMojo.java:89)
    ... 22 more
[ERROR]
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException
</code>```

I found a lot but no info about this error. Thanks in advance for helping me figure out the reason.

答:
I hit the same issue-- I ended up installing all the various npm bits that kept failing by running:

```<code>$ sudo npm install -g bower grunt grunt-cli npm-run-all rimraf webpack
</code>```

Also the build attempt didn't like that I ran it initially as sudo/root (on a test machine), so I recursively changed ownership of /opt/zeppelin (where I extracted the zeppelin tarball) to a regular user 'zeppelin', then ran the maven build command as user zeppelin at /opt/zeppelin.  This was able to get me unblocked, hopefully this may help you too.

ContentLicense: CC BY-SA 3.0

Body:
i tried to build the zeppelin-0.7.0 master branch downloaded from github, but failed .
the build command:

  mvn  package  -Pyarn -Pbuild-distr -Pspark-2.0 -Dspark.version=2.0.1  -Phadoop-2.6  -Dhadoop.version=2.6.0 -Pscala-2.11 -Ppyspark -DskipTests -X

the output stacktrace is:

[ERROR] error Command failed with exit code 1.
[INFO] info Visit https://yarnpkg.com/en/docs/cli/install for documentation about this command.
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 27.397 s
[INFO] Finished at: 2017-01-14T11:39:00+08:00
[INFO] Final Memory: 19M/228M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal com.github.eirslett:frontend-maven-plugin:1.3:yarn (yarn install) on project zeppelin-web: Failed to run task: 'yarn install --no-lockfile' failed. (error code 1) -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal com.github.eirslett:frontend-maven-plugin:1.3:yarn (yarn install) on project zeppelin-web: Failed to run task
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:212)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:116)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:80)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:51)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:307)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:193)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:106)
    at org.apache.maven.cli.MavenCli.execute(MavenCli.java:863)
    at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:288)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:199)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)
Caused by: org.apache.maven.plugin.MojoFailureException: Failed to run task
    at com.github.eirslett.maven.plugins.frontend.mojo.AbstractFrontendMojo.execute(AbstractFrontendMojo.java:95)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:134)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:207)
    ... 20 more
Caused by: com.github.eirslett.maven.plugins.frontend.lib.TaskRunnerException: 'yarn install --no-lockfile' failed. (error code 1)
    at com.github.eirslett.maven.plugins.frontend.lib.YarnTaskExecutor.execute(YarnTaskExecutor.java:61)
    at com.github.eirslett.maven.plugins.frontend.mojo.YarnMojo.execute(YarnMojo.java:65)
    at com.github.eirslett.maven.plugins.frontend.mojo.AbstractFrontendMojo.execute(AbstractFrontendMojo.java:89)
    ... 22 more
[ERROR]
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException

I found a lot but no info about this error. Thanks in advance for helping me figure out the reason.

Body:
I hit the same issue-- I ended up installing all the various npm bits that kept failing by running:

$ sudo npm install -g bower grunt grunt-cli npm-run-all rimraf webpack

Also the build attempt didn't like that I ran it initially as sudo/root (on a test machine), so I recursively changed ownership of /opt/zeppelin (where I extracted the zeppelin tarball) to a regular user 'zeppelin', then ran the maven build command as user zeppelin at /opt/zeppelin.  This was able to get me unblocked, hopefully this may help you too.


问:
AF_UNIX usage with SOCK_DGRAM creates a problem with the unix socket name length
my question is about IPC using AF_UNIX and SOCK_DGRAM.
my server code after removing some error checks from the code is:

```<code> sd = socket(AF_UNIX, SOCK_DGRAM, 0);
 memset(&serveraddr, 0, sizeof(serveraddr));
 serveraddr.sun_family = AF_UNIX;
 strcpy(serveraddr.sun_path, SERVER_PATH);
 length = BUFFER_LENGTH;
 rc = setsockopt(sd, SOL_SOCKET, SO_RCVLOWAT, (char *)&length, sizeof(length));
 rc = bind(sd, (struct sockaddr *)&serveraddr, SUN_LEN(&serveraddr));
 rc = recv(sd, buffer, sizeof(buffer), 0));
</code>```

my client code after removing some error checks from the code is:

```<code> sd = socket(AF_UNIX, SOCK_DGRAM, 0);
 memset(&serveraddr, 0, sizeof(serveraddr));
 serveraddr.sun_family = AF_UNIX;
 strcpy(serveraddr.sun_path, SERVER_PATH);
 memset(buffer, 'a', sizeof(buffer));
 socklen_t server_length = sizeof(struct sockaddr);
 sendto(sd, buffer, sizeof(buffer), 0, (struct sockaddr *)&serveraddr, server_length);
</code>```

the weired problem i can see lies in the definition of the SERVER_PATH.
once the length of my SERVER_PATH is more than 14 characters the client send(...) will fail with the error ("No such file or directory").

some points to notice:

i am using redhat 64 bit.

i have defined SERVER_PATH as follows: #define SERVER_PATH     "/tmp/aaaaaaaaaa"

when i change the code to not use SOCK_DGRAM but SOCK_STREAM (after adding the connect, listen and accept methods to the code as shown in http://publib.boulder.ibm.com/infocenter/iseries/v6r1m0/index.jsp?topic=/rzab6/xafunixcl.htm and http://publib.boulder.ibm.com/infocenter/iseries/v5r3/index.jsp?topic=/rzab6/rzab6xafunixsrv.htm there is no issue with the socket name length.

any idea ?

答: I suspect the problem has to do with sizeof(struct sockaddr). On my system that allows 14 characters for the address field. Try sizeof(struct sockaddr_un).

ContentLicense: CC BY-SA 2.5

Body:
my question is about IPC using AF_UNIX and SOCK_DGRAM.
my server code after removing some error checks from the code is:

 sd = socket(AF_UNIX, SOCK_DGRAM, 0);
 memset(&serveraddr, 0, sizeof(serveraddr));
 serveraddr.sun_family = AF_UNIX;
 strcpy(serveraddr.sun_path, SERVER_PATH);
 length = BUFFER_LENGTH;
 rc = setsockopt(sd, SOL_SOCKET, SO_RCVLOWAT, (char *)&length, sizeof(length));
 rc = bind(sd, (struct sockaddr *)&serveraddr, SUN_LEN(&serveraddr));
 rc = recv(sd, buffer, sizeof(buffer), 0));

my client code after removing some error checks from the code is:

 sd = socket(AF_UNIX, SOCK_DGRAM, 0);
 memset(&serveraddr, 0, sizeof(serveraddr));
 serveraddr.sun_family = AF_UNIX;
 strcpy(serveraddr.sun_path, SERVER_PATH);
 memset(buffer, 'a', sizeof(buffer));
 socklen_t server_length = sizeof(struct sockaddr);
 sendto(sd, buffer, sizeof(buffer), 0, (struct sockaddr *)&serveraddr, server_length);

the weired problem i can see lies in the definition of the SERVER_PATH.
once the length of my SERVER_PATH is more than 14 characters the client send(...) will fail with the error ("No such file or directory").

some points to notice:

i am using redhat 64 bit.

i have defined SERVER_PATH as follows: #define SERVER_PATH     "/tmp/aaaaaaaaaa"

when i change the code to not use SOCK_DGRAM but SOCK_STREAM (after adding the connect, listen and accept methods to the code as shown in http://publib.boulder.ibm.com/infocenter/iseries/v6r1m0/index.jsp?topic=/rzab6/xafunixcl.htm and http://publib.boulder.ibm.com/infocenter/iseries/v5r3/index.jsp?topic=/rzab6/rzab6xafunixsrv.htm there is no issue with the socket name length.

any idea ?


问:
Insert into a map as a field of map in golang
I am trying to create a struct, one of whose fields is a map. However, I cannot initialize it with a method and then insert a value with another method. It reports error

panic: assignment to entry in nil map

Coming from a Python background, I am confused on what I missed.

Here is the goal playground snippet

```<code>package main

type profile map[string]float64

type foobar struct {
    foo profile
    bar map[string]profile
}

func (fb foobar) Init() {
    fb.foo = make(profile)
    fb.bar = make(map[string]profile)
}

func (fb foobar) Set() {
    fb.bar["foo1"] = make(profile)
}

func main() {
    test := foobar{}
    test.Init()
    test.Set()
}
</code>```

答:
The Init method receiver (fb foobar) is a value. It should be a pointer (fb *foobar). For example,

```<code>package main

type profile map[string]float64

type foobar struct {
    foo profile
    bar map[string]profile
}

func (fb *foobar) Init() {
    fb.foo = make(profile)
    fb.bar = make(map[string]profile)
}

func (fb foobar) Set() {
    fb.bar["foo1"] = make(profile)
}

func main() {
    test := foobar{}
    test.Init()
    test.Set()
}
</code>```

Reference:

Should I define methods on values or pointers?

Body:
I am trying to create a struct, one of whose fields is a map. However, I cannot initialize it with a method and then insert a value with another method. It reports error

panic: assignment to entry in nil map

Coming from a Python background, I am confused on what I missed.

Here is the goal playground snippet

package main

type profile map[string]float64

type foobar struct {
    foo profile
    bar map[string]profile
}

func (fb foobar) Init() {
    fb.foo = make(profile)
    fb.bar = make(map[string]profile)
}

func (fb foobar) Set() {
    fb.bar["foo1"] = make(profile)
}

func main() {
    test := foobar{}
    test.Init()
    test.Set()
}

Body:
The Init method receiver (fb foobar) is a value. It should be a pointer (fb *foobar). For example,

package main

type profile map[string]float64

type foobar struct {
    foo profile
    bar map[string]profile
}

func (fb *foobar) Init() {
    fb.foo = make(profile)
    fb.bar = make(map[string]profile)
}

func (fb foobar) Set() {
    fb.bar["foo1"] = make(profile)
}

func main() {
    test := foobar{}
    test.Init()
    test.Set()
}

Reference:

Should I define methods on values or pointers?


问:
How to select JSON (dynamic) Parent and Child in PHP?
I have a JSON which looks like this:

```<code>{
    "Meta Data": {
        "1. Information": "Monthly Prices (open, high, low, close) and Volumes",
        "2. Symbol": "AAPL",
        "3. Last Refreshed": "2017-05-31",
        "4. Time Zone": "US/Eastern"
    },
    "Monthly Time Series": {
        "2017-05-31": {
            "1. open": "145.1000",
            "2. high": "156.6500",
            "3. low": "144.2700",
            "4. close": "152.7600",
            "5. volume": "652734610"
        },
        "2017-04-28": {
            "1. open": "143.7100",
            "2. high": "145.4600",
            "3. low": "140.0600",
            "4. close": "143.6500",
            "5. volume": "373272701"
        },
        "2017-03-31": {
            "1. open": "137.8900",
            "2. high": "144.5000",
            "3. low": "137.0500",
            "4. close": "143.6600",
            "5. volume": "562091214"
        }
    }
}
</code>```

I managed to select the "Monthly Time Series" children with this piece of code:

```<code>$url = "http:...";   //some URL
$json = file_get_contents($url);   //get URL content

$data = json_decode($json,true);   //decode JSON
$arr = $data['Monthly Time Series'];   //Ignore the part before 'Monthly Time Series'

$someArray = $arr;   // Loop through the JSON array
  foreach ($someArray as $key => $value) {
    echo "[" .$value["1. open"] . ", " . $value["2. high"] . ", " . $value["3. low"] . ", " . $value["4. close"] . ", " . $value["5. volume"] . "],\n";
  }

echo $somearray;
</code>```

And my output comes like this:

```<code>[145.1000, 156.6500, 144.2700, 152.7600, 652734610],
[143.7100, 145.4600, 140.0600, 143.6500, 373272701],
[137.8900, 144.5000, 137.0500, 143.6600, 562091214]
</code>```

I don't really understand how I can select the dates as well. In fact I need the parent (date) included together with my children (values). And the date needs to be translated into a timestamp. So the result would look like this:

```<code>[1496181600, 145.1000, 156.6500, 144.2700, 152.7600, 652734610],
[1493330400, 143.7100, 145.4600, 140.0600, 143.6500, 373272701],
[1490911200, 137.8900, 144.5000, 137.0500, 143.6600, 562091214]
</code>```

I believe that formatting of the time is done with PHP's

```<code>strtotime
</code>```

but I don't understand how I get the JSON parent into the same array parenthesis with it's children.

Any input from your side is highly appreciated. Please bare in mind that I'm an absolute PHP (and JS) newbee..

答:
Here are two concise ways (one is commented out) to use a foreach() loop to achieve the desired result. (Demo):

```<code>$data=json_decode($json,true);
$arr=$data['Monthly Time Series'];
foreach($arr as $k=>$v){
    $result[]='['.strtotime($k).', '.implode(', ',$v).']';  // avoid naming each element
    // or $result[]='['.implode(', ',[strtotime($k)]+$v).']'; // merge then implode()
}
echo implode(",\n",$result);  // no trailing comma on the final row
</code>```

Output:

```<code>[1496214000, 145.1000, 156.6500, 144.2700, 152.7600, 652734610],
[1493362800, 143.7100, 145.4600, 140.0600, 143.6500, 373272701],
[1490943600, 137.8900, 144.5000, 137.0500, 143.6600, 562091214]
</code>```

Now if you are going to be passing this data to javascript and want to create a JSON array of arrays, you can use the earlier defined $arr with one of these methods:

```<code>foreach($arr as $k=>$a){
    $result[]=[strtotime($k)]+array_values($a);  // merge the reformatted key with the values
}
echo json_encode($result);
</code>```

or a function-based approach with no result array variable declared:

```<code>$json=json_encode(
        array_map(
            function($key,$values){
                return [strtotime($key)]+array_values($values);  // merge
            },
            array_keys($arr),  // the keys
            array_column($arr,null)  // the values
        )
    );
echo $json;
// This method doesn't need to declare $json, it can be directly var_exported.
// I mere declared $json for consistency / comprehension.
</code>```

Both of these json-outputting methods will yield:

```<code>[[1496214000,"156.6500","144.2700","152.7600","652734610"],[1493362800,"145.4600","140.0600","143.6500","373272701"],[1490943600,"144.5000","137.0500","143.6600","562091214"]]
</code>```

Here is a new demo.
Notice the extra [ and ] wrapping the result; this makes the data an array with multiple arrays inside.

Also notice that the values after the strtotime date are double-quoted as strings.  This means future data handling won't accidentally remove any trailing zero -- assuming they are important to keep.

Body:
I have a JSON which looks like this:

{
    "Meta Data": {
        "1. Information": "Monthly Prices (open, high, low, close) and Volumes",
        "2. Symbol": "AAPL",
        "3. Last Refreshed": "2017-05-31",
        "4. Time Zone": "US/Eastern"
    },
    "Monthly Time Series": {
        "2017-05-31": {
            "1. open": "145.1000",
            "2. high": "156.6500",
            "3. low": "144.2700",
            "4. close": "152.7600",
            "5. volume": "652734610"
        },
        "2017-04-28": {
            "1. open": "143.7100",
            "2. high": "145.4600",
            "3. low": "140.0600",
            "4. close": "143.6500",
            "5. volume": "373272701"
        },
        "2017-03-31": {
            "1. open": "137.8900",
            "2. high": "144.5000",
            "3. low": "137.0500",
            "4. close": "143.6600",
            "5. volume": "562091214"
        }
    }
}

I managed to select the "Monthly Time Series" children with this piece of code:

$url = "http:...";   //some URL
$json = file_get_contents($url);   //get URL content

$data = json_decode($json,true);   //decode JSON
$arr = $data['Monthly Time Series'];   //Ignore the part before 'Monthly Time Series'

$someArray = $arr;   // Loop through the JSON array
  foreach ($someArray as $key => $value) {
    echo "[" .$value["1. open"] . ", " . $value["2. high"] . ", " . $value["3. low"] . ", " . $value["4. close"] . ", " . $value["5. volume"] . "],\n";
  }

echo $somearray;

And my output comes like this:

[145.1000, 156.6500, 144.2700, 152.7600, 652734610],
[143.7100, 145.4600, 140.0600, 143.6500, 373272701],
[137.8900, 144.5000, 137.0500, 143.6600, 562091214]

I don't really understand how I can select the dates as well. In fact I need the parent (date) included together with my children (values). And the date needs to be translated into a timestamp. So the result would look like this:

[1496181600, 145.1000, 156.6500, 144.2700, 152.7600, 652734610],
[1493330400, 143.7100, 145.4600, 140.0600, 143.6500, 373272701],
[1490911200, 137.8900, 144.5000, 137.0500, 143.6600, 562091214]

I believe that formatting of the time is done with PHP's

strtotime

but I don't understand how I get the JSON parent into the same array parenthesis with it's children.

Any input from your side is highly appreciated. Please bare in mind that I'm an absolute PHP (and JS) newbee..

Body:
Here are two concise ways (one is commented out) to use a foreach() loop to achieve the desired result. (Demo):

$data=json_decode($json,true);
$arr=$data['Monthly Time Series'];
foreach($arr as $k=>$v){
    $result[]='['.strtotime($k).', '.implode(', ',$v).']';  // avoid naming each element
    // or $result[]='['.implode(', ',[strtotime($k)]+$v).']'; // merge then implode()
}
echo implode(",\n",$result);  // no trailing comma on the final row

Output:

[1496214000, 145.1000, 156.6500, 144.2700, 152.7600, 652734610],
[1493362800, 143.7100, 145.4600, 140.0600, 143.6500, 373272701],
[1490943600, 137.8900, 144.5000, 137.0500, 143.6600, 562091214]

Now if you are going to be passing this data to javascript and want to create a JSON array of arrays, you can use the earlier defined $arr with one of these methods:

foreach($arr as $k=>$a){
    $result[]=[strtotime($k)]+array_values($a);  // merge the reformatted key with the values
}
echo json_encode($result);

or a function-based approach with no result array variable declared:

$json=json_encode(
        array_map(
            function($key,$values){
                return [strtotime($key)]+array_values($values);  // merge
            },
            array_keys($arr),  // the keys
            array_column($arr,null)  // the values
        )
    );
echo $json;
// This method doesn't need to declare $json, it can be directly var_exported.
// I mere declared $json for consistency / comprehension.

Both of these json-outputting methods will yield:

[[1496214000,"156.6500","144.2700","152.7600","652734610"],[1493362800,"145.4600","140.0600","143.6500","373272701"],[1490943600,"144.5000","137.0500","143.6600","562091214"]]

Here is a new demo.
Notice the extra [ and ] wrapping the result; this makes the data an array with multiple arrays inside.

Also notice that the values after the strtotime date are double-quoted as strings.  This means future data handling won't accidentally remove any trailing zero -- assuming they are important to keep.


问:
make a JTextArea scrollable
How would I make the following JTextArea scrollable?

```<code>    private JTextArea getJTextArea1() {
    if (jTextArea1 == null) {
        jTextArea1 = new JTextArea();
        jTextArea1.setBounds(new Rectangle(225, 162, 68, 29));
        jTextArea1.setText("text");
    }
    return jTextArea1;
}
</code>```

答:
Some code:</p>

```<code>JScrollPane scrollPane = new JScrollPane(textArea);
</code>```

Title: make a JTextArea scrollable

Body:
How would I make the following JTextArea scrollable?

    private JTextArea getJTextArea1() {
    if (jTextArea1 == null) {
        jTextArea1 = new JTextArea();
        jTextArea1.setBounds(new Rectangle(225, 162, 68, 29));
        jTextArea1.setText("text");
    }
    return jTextArea1;
}

Body:
Some code:

JScrollPane scrollPane = new JScrollPane(textArea);


问:
update data through j-query popup

i want to retrieve data from database table and make a link to every retrieved field when i click the link a query popup open and in that popup there should be textboxes and a update button

Is it possible to update data in jquery popup.

答:
Have you successfully retrieved the data and displaying the retrieved fields along with the link?

I guess you are able to display the data along with the links to do the editing and you are stuck with edit and update part.

So, I think you are not much experienced with Dom Manipulation. Go through these things specially - .html(),  .text() and practice a few demos.

Then go back to your code and do the following:-

while you are generating the html containing the retrieved data, assign them proper ids.

on clicking a link use .text() or .html() to read the value and again use them to put values to the input field of your popup (you have to use proper ids while generating the popups). Are you doing any such thing? You say on clicking your text box is empty. So, check very properly the ids that you are assigning during the html generation.

Then on submitting, I guess you want the data to be updated in db without a page reload. Then you have to use jQuery.ajax().

Ask with more details if you are still stuck.

Title: update data through j-query popup


问:
Wrong injection of $modalProvider dependency angujarjs
I'm trying to open a dialog box in angularjs using bootstrap but whenever i try i get this error while injecting the right dependencies.

```<code>.controller('login_ctrl', ['$scope','$http','$window','$modal','$log', function($scope,$http,$window,$modal,$log) {

    var modalInstance = $modal.open({
            templateUrl: 'myModalContent.html',
            controller: 'ModalInstanceCtrl',

            //size: size,
            resolve: {
                user: function() {
                    return userData;
                },
                selectedProducts: function() {
                    return userData.selectedProducts;
                },
                products: function () {
                    //console.log($scope.selectedProducts);
                    return $scope.products; // get all available products
                }
            }
        });

}])
</code>```

all the files js and css files are in the head section of my document

```<code><link href="/spree/web/lib/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css">
<link rel="stylesheet" type="text/css" href="css/spree.css">
<script src="/spree/web/lib//angularjs/angular.min.js"></script>
<script src="/spree/web/lib/angularjs/angular-route.min.js"></script>
<script src="/spree/web/js/app.js"></script>
<script src="/spree/web/js/controller.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/2.5.0/ui-bootstrap-tpls.js"></script>
</code>```

and this is how the start of the js looks like

```<code>angular.module('controller', ['ui.bootstrap'])
</code>```

when i preview i get this error in the console

Error: [$injector:unpr] http://errors.angularjs.org/1.4.1/$injector/unpr?p0=%24modalProvider%20%3C-%20%24modal%20%3C-%20login_ctrl

答:
In angular js manual bootstrapping should be the last line of your js file. Add this line to the end of your js file

```<code>angular.module('controller', ['ui.bootstrap'])
</code>```

Hope this works.

Body:
I'm trying to open a dialog box in angularjs using bootstrap but whenever i try i get this error while injecting the right dependencies.

.controller('login_ctrl', ['$scope','$http','$window','$modal','$log', function($scope,$http,$window,$modal,$log) {

    var modalInstance = $modal.open({
            templateUrl: 'myModalContent.html',
            controller: 'ModalInstanceCtrl',

            //size: size,
            resolve: {
                user: function() {
                    return userData;
                },
                selectedProducts: function() {
                    return userData.selectedProducts;
                },
                products: function () {
                    //console.log($scope.selectedProducts);
                    return $scope.products; // get all available products
                }
            }
        });

}])

all the files js and css files are in the head section of my document

<link href="/spree/web/lib/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css">
<link rel="stylesheet" type="text/css" href="css/spree.css">

and this is how the start of the js looks like

angular.module('controller', ['ui.bootstrap'])

when i preview i get this error in the console

Error: [$injector:unpr] http://errors.angularjs.org/1.4.1/$injector/unpr?p0=%24modalProvider%20%3C-%20%24modal%20%3C-%20login_ctrl

Body:
In angular js manual bootstrapping should be the last line of your js file. Add this line to the end of your js file

angular.module('controller', ['ui.bootstrap'])

Hope this works.


问:
Exact Split is not happening using split function in R
https://www.dropbox.com/s/35w66sri5rauv5d/FlightDelays.csv?dl=0

I am reading a dataset from the above link which contains 2201 rows.using split function,i gave the ratio as 0.6.Then i should be getting two datasets conatining 1320 and 881 datasets respectively.Initally it was working fine,but now when i am splitting ,instead of 0.6 the split is happening for 0.53,Even though i specified 0.6 as my ratio in the split.what might be the issue for this sudden change.How to resolve this.Code is given below.

```<code>library(caTools)
originaldata.df<-read.csv("use csv from the link given above")
split<-sample.split(originaldata.df,SplitRatio = 0.6)
Trainingdataset<-subset(originaldata.df,split == "TRUE")
Testingdataset<-subset(originaldata.df,split == "FALSE")

ExpectedOutput:
1320(2201*60/100)
881(2201*40/100)
Actualoutput:
1186
1015
</code>```

答:
Base-R:

You can use indices and assign them by the split ratio;

```<code>indexes = sample(1:nrow(originaldata.df),
size=0.6*nrow(originaldata.df))

Trainingdataset <- originaldata.df[indexes,]
Testingdataset <- originaldata.df[-indexes,]
</code>```

This would be the output:

```<code>> dim(Testingdataset)
# [1] 881  13
> dim(Trainingdataset)
# [1] 1320   13
</code>```

caTools package:

```<code>library(caTools)
#It should be applied on one of column of the data.frame otherwise samples over rows;
split<-sample.split(originaldata.df$schedtime,SplitRatio = 0.6)

Trainingdataset<-subset(originaldata.df,split == "TRUE")
Testingdataset<-subset(originaldata.df,split == "FALSE")
</code>```

And size of subsets (not exactly what you expect;)

```<code>> dim(Trainingdataset)
# [1] 1323   13
> dim(Testingdataset)
# [1] 878  13
</code>```

Body:
https://www.dropbox.com/s/35w66sri5rauv5d/FlightDelays.csv?dl=0

I am reading a dataset from the above link which contains 2201 rows.using split function,i gave the ratio as 0.6.Then i should be getting two datasets conatining 1320 and 881 datasets respectively.Initally it was working fine,but now when i am splitting ,instead of 0.6 the split is happening for 0.53,Even though i specified 0.6 as my ratio in the split.what might be the issue for this sudden change.How to resolve this.Code is given below.

library(caTools)
originaldata.df<-read.csv("use csv from the link given above")
split<-sample.split(originaldata.df,SplitRatio = 0.6)
Trainingdataset<-subset(originaldata.df,split == "TRUE")
Testingdataset<-subset(originaldata.df,split == "FALSE")

ExpectedOutput:
1320(2201*60/100)
881(2201*40/100)
Actualoutput:
1186
1015

Body:
Base-R:

You can use indices and assign them by the split ratio;

indexes = sample(1:nrow(originaldata.df),
size=0.6*nrow(originaldata.df))

Trainingdataset <- originaldata.df[indexes,]
Testingdataset <- originaldata.df[-indexes,]

This would be the output:

> dim(Testingdataset)
# [1] 881  13
> dim(Trainingdataset)
# [1] 1320   13

caTools package:

library(caTools)
#It should be applied on one of column of the data.frame otherwise samples over rows;
split<-sample.split(originaldata.df$schedtime,SplitRatio = 0.6)

Trainingdataset<-subset(originaldata.df,split == "TRUE")
Testingdataset<-subset(originaldata.df,split == "FALSE")

And size of subsets (not exactly what you expect;)

> dim(Trainingdataset)
# [1] 1323   13
> dim(Testingdataset)
# [1] 878  13


问:
How to get the "Application Name" from hWnd for Windows 10 Store Apps (e.g. Edge)
I'm trying to get an understandable "Process Name" for Windows 10 apps. Currently, all of them use ApplicationFrameHost, so I thought I could use either the ModelId or the PackageName, but it seems Windows 10 Store Apps (I tried with Mail, Store and Edge) won't work with the Package query API

Using kernel32.dll, GetApplicationUserModelId returns APPMODEL_ERROR_NO_APPLICATION and GetPackageId returns APPMODEL_ERROR_NO_PACKAGE.

How can I get an identifier for a Windows 10 Store App, so that I can uniquely identify, say, Edge but also any other Windows 10 Store Apps?

Update

I'm getting the process ID from the hWnd (the window handle), so I think my problem is actually how to get the "real" process ID from a window handle. From there, using those methods would probably work.

答:
Below is a similar one for getting the actual process name,
Name of process for active window in Windows 8/10

With Spy++ utility, confirmed that Windows.Core.UI.CoreWindow is a child window of Weather and it is the one that we are interested in. (Verified on Win10 10563)


问:
Merge and split columns in pandas dataframe
I want to know how to merge multiple columns, and split them again.

Input data

```<code>A B C
1 3 5
2 4 6
</code>```

Merge A, B, C to one column X

```<code>X
1
2
3
4
5
6
</code>```

Process something with X, then split X into A, B, C again. The number of rows for A, B, C is same(2).

```<code>A B C
1 3 5
2 4 6
</code>```

Is there any simple way for this work?

答:
Setup

```<code>df=pd.DataFrame({'A': {0: 1, 1: 2}, 'B': {0: 3, 1: 4}, 'C': {0: 5, 1: 6}})

df
Out[684]:
   A  B  C
0  1  3  5
1  2  4  6
</code>```

Solution

Merge df to 1 column:

```<code>df2 = pd.DataFrame(df.values.flatten('F'),columns=['X'])
Out[686]:
   X
0  1
1  2
2  3
3  4
4  5
5  6
</code>```

Split it back to 3 columns:

```<code>pd.DataFrame(df2.values.reshape(-1,3,order='F'),columns=['A','B','C'])
Out[701]:
   A  B  C
0  1  3  5
1  2  4  6
</code>```

Body:
I want to know how to merge multiple columns, and split them again.

Input data

A B C
1 3 5
2 4 6

Merge A, B, C to one column X

X
1
2
3
4
5
6

Process something with X, then split X into A, B, C again. The number of rows for A, B, C is same(2).

A B C
1 3 5
2 4 6

Is there any simple way for this work?

Body:
Setup

df=pd.DataFrame({'A': {0: 1, 1: 2}, 'B': {0: 3, 1: 4}, 'C': {0: 5, 1: 6}})

df
Out[684]:
   A  B  C
0  1  3  5
1  2  4  6

Solution

Merge df to 1 column:

df2 = pd.DataFrame(df.values.flatten('F'),columns=['X'])
Out[686]:
   X
0  1
1  2
2  3
3  4
4  5
5  6

Split it back to 3 columns:

pd.DataFrame(df2.values.reshape(-1,3,order='F'),columns=['A','B','C'])
Out[701]:
   A  B  C
0  1  3  5
1  2  4  6


问:
Grails spring security rest inject tokenGenerator
I have a similar requirement like this post mentioned. :REST spring security - Manually authenticating a new user and getting access token

According to the accepted answer, the codes will be like:

```<code>class RegisterController {

    def springSecurityService
    def tokenGenerator
    def tokenStorageService

    def register() {
         //do stuff
         springSecurityService.reauthenticate(username)
         String tokenValue = tokenGenerator.generateToken()
         tokenStorageService.storeToken(tokenValue, springSecurityService.principal)

         redirect url: "http://example.org/?access_token=${tokenValue}"
    }
}
</code>```

I tried but it didn't work for me. It seems the TokenGenerator implementation class is not injected right. I understand the default implementation in grails-spring-security-rest TokenGenerator will be the JWT but wonder where should I register or config it.

答:
Well if you want to use the "tokenGenerator" then you need to register it under the "resources.groovy" like below

```<code>// creating the bean of token generator
tokenGenerator(SecureRandomTokenGenerator)
</code>```

and then inject it into your controller or service like below

```<code>class RegisterController {

def springSecurityService
def tokenGenerator
def tokenStorageService

    def register() {
         //do stuff
         springSecurityService.reauthenticate(username)
         String tokenValue = tokenGenerator.generateToken()
         tokenStorageService.storeToken(tokenValue, springSecurityService.principal)

         redirect url: "http://example.org/?access_token=${tokenValue}"
    }
}
</code>```

I have followed the same example (with slight modification) and its working as expected.

I have used the "userDetailsService" for generating user instance instead of "springSecurityService.reauthenticate(username)"

So my function looks like below.

```<code>/**
 * For generating the access token for the user
 *
 * @param userName : Holds the username of the user
 *
 * @return : access token
 */
String generateAccessToken(String userName){
    String tokenValue

    try{
        //load user details
        def userDetails = userDetailsService.loadUserByUsername(userName)

        //generate access token
        tokenValue = tokenGenerator.generateAccessToken(userDetails).accessToken

        //store access token
        tokenStorageService.storeToken(tokenValue, userDetails)
    } catch (Exception e){
       //Exception handling code
    }

    return tokenValue
}
</code>```

Body:
I have a similar requirement like this post mentioned. :REST spring security - Manually authenticating a new user and getting access token

According to the accepted answer, the codes will be like:

class RegisterController {

    def springSecurityService
    def tokenGenerator
    def tokenStorageService

    def register() {
         //do stuff
         springSecurityService.reauthenticate(username)
         String tokenValue = tokenGenerator.generateToken()
         tokenStorageService.storeToken(tokenValue, springSecurityService.principal)

         redirect url: "http://example.org/?access_token=${tokenValue}"
    }
}

I tried but it didn't work for me. It seems the TokenGenerator implementation class is not injected right. I understand the default implementation in grails-spring-security-rest TokenGenerator will be the JWT but wonder where should I register or config it.

Body:
Well if you want to use the "tokenGenerator" then you need to register it under the "resources.groovy" like below

// creating the bean of token generator
tokenGenerator(SecureRandomTokenGenerator)

and then inject it into your controller or service like below

class RegisterController {

def springSecurityService
def tokenGenerator
def tokenStorageService

    def register() {
         //do stuff
         springSecurityService.reauthenticate(username)
         String tokenValue = tokenGenerator.generateToken()
         tokenStorageService.storeToken(tokenValue, springSecurityService.principal)

         redirect url: "http://example.org/?access_token=${tokenValue}"
    }
}

I have followed the same example (with slight modification) and its working as expected.

I have used the "userDetailsService" for generating user instance instead of "springSecurityService.reauthenticate(username)"

So my function looks like below.

/**
 * For generating the access token for the user
 *
 * @param userName : Holds the username of the user
 *
 * @return : access token
 */
String generateAccessToken(String userName){
    String tokenValue

    try{
        //load user details
        def userDetails = userDetailsService.loadUserByUsername(userName)

        //generate access token
        tokenValue = tokenGenerator.generateAccessToken(userDetails).accessToken

        //store access token
        tokenStorageService.storeToken(tokenValue, userDetails)
    } catch (Exception e){
       //Exception handling code
    }

    return tokenValue
}


问:
Overlay is expanding outside the viewport
I have an overlay that is supposed to cover the entire page when opened - it works except all of the sudden the overlay is larger than the viewport by about 50px and causes a horizontal scroll. I am not sure how to ensure that the overlay only covered the viewport size? I was using width: 100vw and that worked perfectly and now I can't seem to keep the size inside of the vw of various screen sizes.

```<code>    .modal-footer-large {
      height: 100%;
      background-color: white;
      position: fixed;
      z-index: 1;
      left: 0;
      right: 0;
      top: 40px;
      overflow: hidden;
      padding: 10px 40px;
   }
</code>```

答:
Try using cover size

```<code>background-size:cover;
</code>```

OR:

```<code>width: 100%
</code>```

Body:
I have an overlay that is supposed to cover the entire page when opened - it works except all of the sudden the overlay is larger than the viewport by about 50px and causes a horizontal scroll. I am not sure how to ensure that the overlay only covered the viewport size? I was using width: 100vw and that worked perfectly and now I can't seem to keep the size inside of the vw of various screen sizes.

    .modal-footer-large {
      height: 100%;
      background-color: white;
      position: fixed;
      z-index: 1;
      left: 0;
      right: 0;
      top: 40px;
      overflow: hidden;
      padding: 10px 40px;
   }

Body:
Try using cover size

background-size:cover;

OR:

width: 100%


问:
How to add button tint programmatically
In the new AppCompat library, we can tint the button this way:

```<code><Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@string/follow"
    android:id="@+id/button_follow"
    android:backgroundTint="@color/blue_100"
    />
</code>```

How can I set the tint of the button programmatically in my code?
I'm basically trying to implement a conditional coloring of the button based on some user input.

答:
Seems like views have own mechanics for tint management, so better will be put tint list:</p>

```<code>ViewCompat.setBackgroundTintList(
    editText,
    ColorStateList.valueOf(errorColor));
</code>```

Title: How to add button tint programmatically

Body:
In the new AppCompat library, we can tint the button this way:

<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@string/follow"
    android:id="@+id/button_follow"
    android:backgroundTint="@color/blue_100"
    />

How can I set the tint of the button programmatically in my code?
I'm basically trying to implement a conditional coloring of the button based on some user input.

Body:
Seems like views have own mechanics for tint management, so better will be put tint list:

ViewCompat.setBackgroundTintList(
    editText,
    ColorStateList.valueOf(errorColor));


问:
How to setup Fake Reponsitory using Moq With dependency Injection (Error Casting Queryable)
How can I setup Data Queryable Data Using Moq

I have The Reponsitory (IMediaCoverageReponsitory).

```<code>public interface IMediaCoverageRepository : RepositoryAsync<MediaCoverage>
</code>```

I create Moq IMediaCoverageRepository using Moq

```<code>var mockFactory = new MockRepository(MockBehavior.Strict) {
    DefaultValue = DefaultValue.Mock
};
var mockMediaRepository = mockFactory.Create<IMediaCoverageRepository>();
</code>```

I have a list example:

```<code>var listOfMediaCoverages = new List<MediaCoverage>()
{
    new MediaCoverage { MediaCoverageId = 1, Name = "Media 10", IsActive = true },
    new MediaCoverage {MediaCoverageId = 2, Name = "Media 100", IsActive = true },
    new MediaCoverage {MediaCoverageId = 3, Name = "Media 1000", IsActive = false }
};
</code>```

After that, I setup data using listOfMediaCoverage Fake Into Mock MediaCoverageRepository like this

```<code>var queryableListMediaCoverage = listOfMediaCoverages.ToArray().AsQueryable();
</code>```

```<code>mockMediaRepository.Setup(r => r.Queryable(null).GetEnumerator()).Returns(queryableListMediaCoverage.GetEnumerator());
mockMediaRepository.Setup(r => r.Queryable(null).Provider).Returns(queryableListMediaCoverage.Provider);
mockMediaRepository.Setup(r => r.Queryable(null).ElementType).Returns(queryableListMediaCoverage.ElementType);
mockMediaRepository.Setup(r => r.Queryable(null).Expression).Returns(queryableListMediaCoverage.Expression);
</code>```

==> I get the error:
  **Unable to cast object of type

```<code>'System.Linq.EnumerableQuery`1[Pacman2.Core.Entities.MediaCoverage]' to type 'Moq.IMocked'.**
</code>```

Please Help me solve this problem. I already search on google And  try the solution on this link but won't solve the problem

```<code><links>
     http://davidcondemarin.blogspot.com/2012/07/testing-sarp-lite-repositories-with-moq.html
</links>
</code>```

Notes:

r => r.Queryable(null) Is the method return IQueryable

Body:
How can I setup Data Queryable Data Using Moq

I have The Reponsitory (IMediaCoverageReponsitory).

public interface IMediaCoverageRepository : RepositoryAsync<MediaCoverage>

I create Moq IMediaCoverageRepository using Moq

var mockFactory = new MockRepository(MockBehavior.Strict) {
    DefaultValue = DefaultValue.Mock
};
var mockMediaRepository = mockFactory.Create<IMediaCoverageRepository>();

I have a list example:

var listOfMediaCoverages = new List<MediaCoverage>()
{
    new MediaCoverage { MediaCoverageId = 1, Name = "Media 10", IsActive = true },
    new MediaCoverage {MediaCoverageId = 2, Name = "Media 100", IsActive = true },
    new MediaCoverage {MediaCoverageId = 3, Name = "Media 1000", IsActive = false }
};

After that, I setup data using listOfMediaCoverage Fake Into Mock MediaCoverageRepository like this

var queryableListMediaCoverage = listOfMediaCoverages.ToArray().AsQueryable();

mockMediaRepository.Setup(r => r.Queryable(null).GetEnumerator()).Returns(queryableListMediaCoverage.GetEnumerator());
mockMediaRepository.Setup(r => r.Queryable(null).Provider).Returns(queryableListMediaCoverage.Provider);
mockMediaRepository.Setup(r => r.Queryable(null).ElementType).Returns(queryableListMediaCoverage.ElementType);
mockMediaRepository.Setup(r => r.Queryable(null).Expression).Returns(queryableListMediaCoverage.Expression);

==> I get the error:
  **Unable to cast object of type

'System.Linq.EnumerableQuery`1[Pacman2.Core.Entities.MediaCoverage]' to type 'Moq.IMocked'.**

Please Help me solve this problem. I already search on google And  try the solution on this link but won't solve the problem

<links>
     http://davidcondemarin.blogspot.com/2012/07/testing-sarp-lite-repositories-with-moq.html
</links>

Notes:

r => r.Queryable(null) Is the method return IQueryable

Body:
mockMediaRepository.As<IQueryable<MediaCoverage>>().Setup(m => m.Provider).Returns(queryableListMediaCoverage.Provider);
mockMediaRepository.As<IQueryable<MediaCoverage>>().Setup(m => m.Expression).Returns(queryableListMediaCoverage.Expression);
mockMediaRepository.As<IQueryable<MediaCoverage>>().Setup(m => m.ElementType).Returns(queryableListMediaCoverage.ElementType);
mockMediaRepository.As<IQueryable<MediaCoverage>>().Setup(m => m.GetEnumerator()).Returns(queryableListMediaCoverage.GetEnumerator());


问:
PHP simultaneous TCP connections from same browser
I have a PHP script which opens a socket connection(using fsockopen) and takes about 15secs to complete/return the result to the browser. Mean while, if the browser sends a second request it is serialized. This is giving a bad user experience because if the user clicks 3 times, then the third request which gets sent after 30sec is the one that gets the response -- the first 2 requests from browser prespective are getting lost.

I do not have any session in my script, but tried putting session_write_close() at the beginning of my script which didnt help.

Also session.auto_start in the php.ini = 0.

Any ideas as to how to make the client requests from the same browser parallel??

Thanks
Gary

答:
You should if at all possible install(*nix) redis.

To install just do simple

```<code>make
</code>```

With lpush/brpop you can handle this stuff asynchronously and keep order intact. If you spawn couple of worker threads you could even handle multiple requests simultaneous. the predis client library is pretty solid

Body:
You should if at all possible install(*nix) redis.

To install just do simple

make

With lpush/brpop you can handle this stuff asynchronously and keep order intact. If you spawn couple of worker threads you could even handle multiple requests simultaneous. the predis client library is pretty solid


问:
How to parse a weirdly formatted data file?
How to read a weirdly formatted data file?

For example if there are different types of seperators (, : |) all used together?

Looking at a dataframe example, something along these lines:

答:
parse has a nice interface and might be good option for pulling data such as this out:

```<code>>>> import parse
>>> format_spec='{}: {}'
>>> string='Hobbies: Cooking'
>>> parse.parse(format_spec, string).fixed
('Hobbies', 'Cooking')
</code>```

Use compile if you will parse the same spec over and over:

```<code>>>> other_parser = parse.compile(format_spec)
>>> other_parser.parse(string).fixed
('Hobbies', 'Cooking')
>>> other_parser.parse('Maiden Name: Rubin').fixed
('Maiden Name', 'Rubin')
</code>```

The fixed property returns the parsed arguments as a tuple. Using these tuples we can just create a bunch of dictionaries, feed them into pd.DataFrame, and merge with the first df:

```<code>import parse
import pandas as pd

# slice first two columns from original dataframe
first_df = pd.read_csv(filepath, sep='t').ix[:,0:2]

# make the parser
other_parser = parse.compile('{}: {}')

# parse remaining columns to a new dataframe
with open(filepath) as f:
    # a generator of dict objects is fed into DataFrame
    # the dict keys are column names
    others_df = pd.DataFrame(dict(other_parser.parse(substr).fixed for substr in line.split('\t')[2:]) for line in f)

# merge on the indexes
df = pd.merge(first_df, others_df, left_index=True, right_index=True)
</code>```

Body:
parse has a nice interface and might be good option for pulling data such as this out:

>>> import parse
>>> format_spec='{}: {}'
>>> string='Hobbies: Cooking'
>>> parse.parse(format_spec, string).fixed
('Hobbies', 'Cooking')

Use compile if you will parse the same spec over and over:

>>> other_parser = parse.compile(format_spec)
>>> other_parser.parse(string).fixed
('Hobbies', 'Cooking')
>>> other_parser.parse('Maiden Name: Rubin').fixed
('Maiden Name', 'Rubin')

The fixed property returns the parsed arguments as a tuple. Using these tuples we can just create a bunch of dictionaries, feed them into pd.DataFrame, and merge with the first df:

import parse
import pandas as pd

# slice first two columns from original dataframe
first_df = pd.read_csv(filepath, sep='t').ix[:,0:2]

# make the parser
other_parser = parse.compile('{}: {}')

# parse remaining columns to a new dataframe
with open(filepath) as f:
    # a generator of dict objects is fed into DataFrame
    # the dict keys are column names
    others_df = pd.DataFrame(dict(other_parser.parse(substr).fixed for substr in line.split('\t')[2:]) for line in f)

# merge on the indexes
df = pd.merge(first_df, others_df, left_index=True, right_index=True)


问:
How to track trajectory of moving object openCV C++
I am fairly new to openCV libraries and I am trying to do real time object detection for a school project on an android app. followed this tutorial (https://www.youtube.com/watch?v=bSeFrPrqZ2A) and I am able to detect object by color on my android phone. Now I am trying to map out the trajectory of the object just like in this video (https://www.youtube.com/watch?v=QTYSRZD4vyI).

Following is some of the source code provided in the first youtube video.

```<code>void searchForMovement(int& x, int& y, Mat& mRgb1, Mat& threshold){

morphOps(threshold);

Mat temp;
threshold.copyTo(temp);
//these two vectors needed for output of findContours
vector< vector<Point> > contours;
vector<Vec4i> hierarchy;
//find contours of filtered image using openCV findContours function
//In OpenCV, finding contours is like finding white object from black background.
// So remember, object to be found should be white and background should be black.
//CV_CHAIN_APPROX_SIMPLE to draw 4 points of the contour
findContours(temp,contours,hierarchy,CV_RETR_CCOMP,CV_CHAIN_APPROX_SIMPLE );

double refArea = 0;
bool objectFound = false;
if (hierarchy.size() > 0) {
    int numObjects = hierarchy.size();
    //if number of objects greater than MAX_NUM_OBJECTS we have a noisy filter
    if(numObjects<MAX_NUM_OBJECTS){
        for (int index = 0; index >= 0; index = hierarchy[index][0]) {

            Moments moment = moments((cv::Mat)contours[index]);
            double area = moment.m00;

            //if the area is less than 20 px by 20px then it is probably just noise
            //if the area is the same as the 3/2 of the image size, probably just a bad filter
            //we only want the object with the largest area so we safe a reference area each
            //iteration and compare it to the area in the next iteration.
            if(area>MIN_OBJECT_AREA && area<MAX_OBJECT_AREA && area>refArea){
                x = moment.m10/area;
                y = moment.m01/area;
                objectFound = true;
                refArea = area;
            }else objectFound = false;

        }
        //let user know you found an object
        if(objectFound ==true){
            putText(mRgb1,"Tracking Object",Point(0,50),2,1,Scalar(0,255,0),2);
            //draw object location on screen
            drawObject(x,y,mRgb1);}

    }else putText(mRgb1,"TOO MUCH NOISE! ADJUST FILTER",Point(0,50),1,2,Scalar(0,0,255),2);
}
</code>```

}

```<code>void drawObject(int x, int y,Mat &frame){
Mat traj;
traj = frame;
//use some of the openCV drawing functions to draw crosshairs
//on your tracked image!

//UPDATE:JUNE 18TH, 2013
//added 'if' and 'else' statements to prevent
//memory errors from writing off the screen (ie. (-25,-25) is not within the window!)

circle(frame,Point(x,y),20,Scalar(0,255,0),2);
if(y-25>0)
    line(frame,Point(x,y),Point(x,y-25),Scalar(0,255,0),2);
else line(traj,Point(x,y),Point(x,0),Scalar(0,255,0),2);
if(y+25<FRAME_HEIGHT)
    line(frame,Point(x,y),Point(x,y+25),Scalar(0,255,0),2);
else line(frame,Point(x,y),Point(x,FRAME_HEIGHT),Scalar(0,255,0),2);
if(x-25>0)
    line(traj,Point(x,y),Point(x-25,y),Scalar(0,255,0),2);
else line(frame,Point(x,y),Point(0,y),Scalar(0,255,0),2);
if(x+25<FRAME_WIDTH)
    line(frame,Point(x,y),Point(x+25,y),Scalar(0,255,0),2);
else line(frame,Point(x,y),Point(FRAME_WIDTH,y),Scalar(0,255,0),2);
</code>```

// add(traj, frame, frame);

 putText(frame,intToString(x)+","+intToString(y),Point(x,y+30),1,1,Scalar(0,255,0),2);
}

How can I add onto this code to get the trajectory of an object showed in the 2nd video? Any suggestion would be much appreciated. Thank you.

答:
http://opencv-srf.blogspot.co.uk/2010/09/object-detection-using-color-seperation.html

Found it. When doing it in android, need to make sure the lastX and lastY are updating as well.

Body:
I am fairly new to openCV libraries and I am trying to do real time object detection for a school project on an android app. followed this tutorial (https://www.youtube.com/watch?v=bSeFrPrqZ2A) and I am able to detect object by color on my android phone. Now I am trying to map out the trajectory of the object just like in this video (https://www.youtube.com/watch?v=QTYSRZD4vyI).

Following is some of the source code provided in the first youtube video.

void searchForMovement(int& x, int& y, Mat& mRgb1, Mat& threshold){

morphOps(threshold);

Mat temp;
threshold.copyTo(temp);
//these two vectors needed for output of findContours
vector< vector<Point> > contours;
vector<Vec4i> hierarchy;
//find contours of filtered image using openCV findContours function
//In OpenCV, finding contours is like finding white object from black background.
// So remember, object to be found should be white and background should be black.
//CV_CHAIN_APPROX_SIMPLE to draw 4 points of the contour
findContours(temp,contours,hierarchy,CV_RETR_CCOMP,CV_CHAIN_APPROX_SIMPLE );

double refArea = 0;
bool objectFound = false;
if (hierarchy.size() > 0) {
    int numObjects = hierarchy.size();
    //if number of objects greater than MAX_NUM_OBJECTS we have a noisy filter
    if(numObjects<MAX_NUM_OBJECTS){
        for (int index = 0; index >= 0; index = hierarchy[index][0]) {

            Moments moment = moments((cv::Mat)contours[index]);
            double area = moment.m00;

            //if the area is less than 20 px by 20px then it is probably just noise
            //if the area is the same as the 3/2 of the image size, probably just a bad filter
            //we only want the object with the largest area so we safe a reference area each
            //iteration and compare it to the area in the next iteration.
            if(area>MIN_OBJECT_AREA && area<MAX_OBJECT_AREA && area>refArea){
                x = moment.m10/area;
                y = moment.m01/area;
                objectFound = true;
                refArea = area;
            }else objectFound = false;

        }
        //let user know you found an object
        if(objectFound ==true){
            putText(mRgb1,"Tracking Object",Point(0,50),2,1,Scalar(0,255,0),2);
            //draw object location on screen
            drawObject(x,y,mRgb1);}

    }else putText(mRgb1,"TOO MUCH NOISE! ADJUST FILTER",Point(0,50),1,2,Scalar(0,0,255),2);
}

}

void drawObject(int x, int y,Mat &frame){
Mat traj;
traj = frame;
//use some of the openCV drawing functions to draw crosshairs
//on your tracked image!

//UPDATE:JUNE 18TH, 2013
//added 'if' and 'else' statements to prevent
//memory errors from writing off the screen (ie. (-25,-25) is not within the window!)

circle(frame,Point(x,y),20,Scalar(0,255,0),2);
if(y-25>0)
    line(frame,Point(x,y),Point(x,y-25),Scalar(0,255,0),2);
else line(traj,Point(x,y),Point(x,0),Scalar(0,255,0),2);
if(y+25<FRAME_HEIGHT)
    line(frame,Point(x,y),Point(x,y+25),Scalar(0,255,0),2);
else line(frame,Point(x,y),Point(x,FRAME_HEIGHT),Scalar(0,255,0),2);
if(x-25>0)
    line(traj,Point(x,y),Point(x-25,y),Scalar(0,255,0),2);
else line(frame,Point(x,y),Point(0,y),Scalar(0,255,0),2);
if(x+25<FRAME_WIDTH)
    line(frame,Point(x,y),Point(x+25,y),Scalar(0,255,0),2);
else line(frame,Point(x,y),Point(FRAME_WIDTH,y),Scalar(0,255,0),2);

// add(traj, frame, frame);

 putText(frame,intToString(x)+","+intToString(y),Point(x,y+30),1,1,Scalar(0,255,0),2);
}

How can I add onto this code to get the trajectory of an object showed in the 2nd video? Any suggestion would be much appreciated. Thank you.


问:
error while loading shared libraries: libgsl.so.0: cannot open shared object file: No such file or directory
I use gsl.
After I compiled my .cpp file and run it, I faced with below error:

error while loading shared libraries: libgsl.so.0: cannot open shared object file: No such file or directory

I found same as this problem in:
https://groups.google.com/forum/#!topic/cortex_var/6vluX7pP0Sk
&
Linux error while loading shared libraries: cannot open shared object file: No such file or directory
&
http://www.gnu.org/software/gsl/manual/html_node/Shared-Libraries.html

And I have done as in the above links wrote but the error is still remained.
Can anyone help me?

答: You can use gsl-config --libs in you makefile or in the command line when you link the gsl library. Just type gsl-config you can find the options it offers to you. Choose the options you need, you will find compile and link process much easier than before. As a result, when I type gsl-config --libs in my terminal, I get -L/usr/local/lib -lgsl -lgslcblas -lm. Although it is very simple, first you should know where you gsl is installed. You can add the directory to the PATH environment variable or use the absolute path to execute gsl-config .


问:
Changing an image on hover but only if hovered for a set period of time (jQuery)
I'm trying to change an image, but ony if hovered for a set period of time. I've tried using delay(), which kinda works, but the problem is that the hover animation is still triggered, after the mouse has been moved off the element.

Here's my code

```<code>$('.pack-list li').hover(function() {

  $(this).find('.pack-icon img').delay(1000).animate({
    width: 0,
    height: 0
  }, 100, function() {
    // Animation complete.
    $(this).attr('src','images/download-icon.png');

    $(this).animate({
      width: 30 + "px",
      height: 36 + "px"
    }, 100, function() {
      // Animation complete.
    });
  });

}, function() {
  $(this).find('.pack-icon img').attr('src','images/pack-icon.png');
});
</code>```

答:
It is possible by using CSS3 animations without JavaScript.

.container {
  height: 100px;
  width: 100%;
  background-color: green;
}

.rise {
  display: inline-block;
  height: 0;
  width: 0;
  background-color: red;

}

.container:hover .rise {
  animation: example 0.5s ease 1s forwards;
  -webkit-animation: example 0.5s ease 1s forwards;
  -o-animation: example 0.5s ease 1s forwards;
  -moz-animation: example 0.5s ease 1s forwards;
}
.container:hover .rise:nth-child(2) {
  animation: example 0.5s ease 2s forwards;
  -webkit-animation: example 0.5s ease 2s forwards;
  -o-animation: example 0.5s ease 2s forwards;
  -moz-animation: example 0.5s ease 2s forwards;
}
.container:hover .rise:nth-child(3) {
  animation: example 0.5s ease 1s forwards;
  -webkit-animation: example 0.5s ease 3s forwards;
  -o-animation: example 0.5s ease 3s forwards;
  -moz-animation: example 0.5s ease 3s forwards;
}

@keyframes example {
  0% {
     height: 100px;
     width: 0;
  }
  100% {
     height: 100px;
     width: 100px;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="rise"></div>
  <div class="rise"></div>
  <div class="rise"></div>
</div></code>```

The red squares will be shown in sequence while the coursor is covering the green block within 1, 2 and 3 seconds.

Body:
I'm trying to change an image, but ony if hovered for a set period of time. I've tried using delay(), which kinda works, but the problem is that the hover animation is still triggered, after the mouse has been moved off the element.

Here's my code

$('.pack-list li').hover(function() {

  $(this).find('.pack-icon img').delay(1000).animate({
    width: 0,
    height: 0
  }, 100, function() {
    // Animation complete.
    $(this).attr('src','images/download-icon.png');

    $(this).animate({
      width: 30 + "px",
      height: 36 + "px"
    }, 100, function() {
      // Animation complete.
    });
  });

}, function() {
  $(this).find('.pack-icon img').attr('src','images/pack-icon.png');
});

Body:
It is possible by using CSS3 animations without JavaScript.

.container {
  height: 100px;
  width: 100%;
  background-color: green;
}

.rise {
  display: inline-block;
  height: 0;
  width: 0;
  background-color: red;

}

.container:hover .rise {
  animation: example 0.5s ease 1s forwards;
  -webkit-animation: example 0.5s ease 1s forwards;
  -o-animation: example 0.5s ease 1s forwards;
  -moz-animation: example 0.5s ease 1s forwards;
}
.container:hover .rise:nth-child(2) {
  animation: example 0.5s ease 2s forwards;
  -webkit-animation: example 0.5s ease 2s forwards;
  -o-animation: example 0.5s ease 2s forwards;
  -moz-animation: example 0.5s ease 2s forwards;
}
.container:hover .rise:nth-child(3) {
  animation: example 0.5s ease 1s forwards;
  -webkit-animation: example 0.5s ease 3s forwards;
  -o-animation: example 0.5s ease 3s forwards;
  -moz-animation: example 0.5s ease 3s forwards;
}

@keyframes example {
  0% {
     height: 100px;
     width: 0;
  }
  100% {
     height: 100px;
     width: 100px;
  }
}

<div class="container">
  <div class="rise"></div>
  <div class="rise"></div>
  <div class="rise"></div>
</div>

The red squares will be shown in sequence while the coursor is covering the green block within 1, 2 and 3 seconds.


问:
Indexing and searching a list of list inside a pandas dataframe
Let say we have a list of lists like this:

```<code>lst = [[[[1,2]]],[[[2,3]]],[[[3,4]]]]
</code>```

and then we make a panda data frame here:

```<code>import pandas as pd
import numpy as np
df = pd.DataFrame(lst, columns = ['col'])
print df
</code>```

and returns

```<code>        col
0  [[1, 2]]
1  [[2, 3]]
2  [[3, 4]]
</code>```

what I want is replacing col with green when the interior list includes 1 and red if not. I tried this:

```<code>df['col'] = np.where(1 in df['col'], 'green', 'red')
print df
</code>```

but does not return correct answer!!!

```<code>     col
0  green
1  green
2  green
</code>```

I think the problem is that each element of data frame is a list of lists.

答:
You can use apply method; Also you have a list of list of list, you can either use str[0] to extract the first element (of list type) out or you can extract it from x in apply:

```<code>df['col'].str[0].apply(lambda x: 'green' if 1 in x else 'red')

#0    green
#1      red
#2      red
#Name: col, dtype: object
</code>```

Another option:

```<code>df['col'].apply(lambda x: 'green' if 1 in x[0] else 'red')

#0    green
#1      red
#2      red
#Name: col, dtype: object
</code>```

Body:
Let say we have a list of lists like this:

lst = [[[[1,2]]],[[[2,3]]],[[[3,4]]]]

and then we make a panda data frame here:

import pandas as pd
import numpy as np
df = pd.DataFrame(lst, columns = ['col'])
print df

and returns

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

what I want is replacing col with green when the interior list includes 1 and red if not. I tried this:

df['col'] = np.where(1 in df['col'], 'green', 'red')
print df

but does not return correct answer!!!

     col
0  green
1  green
2  green

I think the problem is that each element of data frame is a list of lists.

Body:
You can use apply method; Also you have a list of list of list, you can either use str[0] to extract the first element (of list type) out or you can extract it from x in apply:

df['col'].str[0].apply(lambda x: 'green' if 1 in x else 'red')

#0    green
#1      red
#2      red
#Name: col, dtype: object

Another option:

df['col'].apply(lambda x: 'green' if 1 in x[0] else 'red')

#0    green
#1      red
#2      red
#Name: col, dtype: object


问:
Can't execute a MySQL stored procedure from Java
I am connecting to a MySQL (5.08) database running on a linux machine from a web application running in tomcat.

I get the following exception when I try to execute a stored procedure:

```<code>com.hp.hpl.chaos.web.exception.DBException: getNextValue for operatorinstance[Additional Information from SQL Exception][SQLErrorCode: 0 SQLState: S1000
    at com.hp.hpl.chaos.web.util.SQLUtil.getNextValue(SQLUtil.java:207)
        ..............

Caused by: java.sql.SQLException: User does not have access to metadata required to determine stored procedure parameter types. If rights can not be granted, configure connection with "noAccessToProcedureBodies=true" to have driver generate parameters that represent INOUT strings irregardless of actual parameter types.
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:910)
at com.mysql.jdbc.DatabaseMetaData.getCallStmtParameterTypes(DatabaseMetaData.java:1619)
at com.mysql.jdbc.DatabaseMetaData.getProcedureColumns(DatabaseMetaData.java:4034)
at com.mysql.jdbc.CallableStatement.determineParameterTypes(CallableStatement.java:709)
at com.mysql.jdbc.CallableStatement.<init>(CallableStatement.java:513)
at com.mysql.jdbc.Connection.parseCallableStatement(Connection.java:4583)
at com.mysql.jdbc.Connection.prepareCall(Connection.java:4657)
at com.mysql.jdbc.Connection.prepareCall(Connection.java:4631)
at com.hp.hpl.chaos.web.util.SQLUtil.getNextValue(SQLUtil.java:196)
... 17 more
</code>```

After installing mysql on the machine. I have given the follwing grant options to root

```<code>mysql> GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'pass';
Query OK, 0 rows affected (0.00 sec)

mysql> FLUSH PRIVILEGES;
Query OK, 0 rows affected (0.00 sec)
</code>```

In the java class..

I am connecting to the db as follows:

```<code>String url = "jdbc:mysql://ipaddress:3306/test";
                con = DriverManager.getConnection(url,"root", "pass");
</code>```

I have also tried the url with the noAccessToProcedureBodies=true option included.

Can someone tell me what is wrong here? Is there anything I need to check?

答:
Running below queries should fix your issue.</p>

```<code>GRANT <SELECT, CREATE, UPDATE, DELETE, ALL> PRIVILEGES ON mysql.proc TO '<user>'@'%';
FLUSH PRIVILEGES;
</code>```

OwnerDisplayName: CGP

Body:
I am connecting to a MySQL (5.08) database running on a linux machine from a web application running in tomcat.

I get the following exception when I try to execute a stored procedure:

com.hp.hpl.chaos.web.exception.DBException: getNextValue for operatorinstance[Additional Information from SQL Exception][SQLErrorCode: 0 SQLState: S1000
    at com.hp.hpl.chaos.web.util.SQLUtil.getNextValue(SQLUtil.java:207)
        ..............

Caused by: java.sql.SQLException: User does not have access to metadata required to determine stored procedure parameter types. If rights can not be granted, configure connection with "noAccessToProcedureBodies=true" to have driver generate parameters that represent INOUT strings irregardless of actual parameter types.
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:910)
at com.mysql.jdbc.DatabaseMetaData.getCallStmtParameterTypes(DatabaseMetaData.java:1619)
at com.mysql.jdbc.DatabaseMetaData.getProcedureColumns(DatabaseMetaData.java:4034)
at com.mysql.jdbc.CallableStatement.determineParameterTypes(CallableStatement.java:709)
at com.mysql.jdbc.CallableStatement.<init>(CallableStatement.java:513)
at com.mysql.jdbc.Connection.parseCallableStatement(Connection.java:4583)
at com.mysql.jdbc.Connection.prepareCall(Connection.java:4657)
at com.mysql.jdbc.Connection.prepareCall(Connection.java:4631)
at com.hp.hpl.chaos.web.util.SQLUtil.getNextValue(SQLUtil.java:196)
... 17 more

After installing mysql on the machine. I have given the follwing grant options to root

mysql> GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'pass';
Query OK, 0 rows affected (0.00 sec)

mysql> FLUSH PRIVILEGES;
Query OK, 0 rows affected (0.00 sec)

In the java class..

I am connecting to the db as follows:

String url = "jdbc:mysql://ipaddress:3306/test";
                con = DriverManager.getConnection(url,"root", "pass");

I have also tried the url with the noAccessToProcedureBodies=true option included.

Can someone tell me what is wrong here? Is there anything I need to check?

Body:
Running below queries should fix your issue.

GRANT <SELECT, CREATE, UPDATE, DELETE, ALL> PRIVILEGES ON mysql.proc TO '<user>'@'%';
FLUSH PRIVILEGES;


问:
Google Sign in not working properly
I have integrated sign in with google in my android application, now issue is that in some device its not working,but in my emulator and in some device it is working fine,what is the issue?

https://developers.google.com/identity/sign-in/android/

http://www.androidhive.info/2014/02/android-login-with-google-plus-account-1/

this two tutorials to sign in, but when i run my app, and try to login it allows to select account,but when i click on that in my logcat it shows

```<code>System.out: Google logout
</code>```

CODE

```<code>private void handleSignInResult(GoogleSignInResult result) {
        Log.d("", "handleSignInResult:" + result.isSuccess());
        if (result.isSuccess()) {
            // Signed in successfully, show authenticated UI.
            GoogleSignInAccount acct = result.getSignInAccount();

            Log.e("", "display name: " + acct.getDisplayName());

            personName = acct.getDisplayName();
            personPhotoUrl = String.valueOf(acct.getPhotoUrl());
            ggoleemail = acct.getEmail();
            googleid = "G" + acct.getId();
          //  String baday = String.valueOf(acct.getAccount());

            Log.e(TAG, "Name: " + personName + googleid  + ", email: " + ggoleemail
                    + ", Image: " + personPhotoUrl);
          /*  txtName.setText(personName);
            txtEmail.setText(email);
            Glide.with(getApplicationContext()).load(personPhotoUrl)
                    .thumbnail(0.5f)
                    .crossFade()
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .into(imgProfilePic);
*/
            googleslogins();
          //  updateUI(true);

        } else {
            // Signed out, show unauthenticated UI.
            //updateUI(false);
            System.out.println("Google logout");
        }
    }
</code>```

答:
There are a few things you are not doing. Firstly, you are losing a lot of information about why the connection is not successful because you are no inspecting the cause of the connection failure coming in the GoogleSignInResult parameter...

```<code>private void handleSignInResult(GoogleSignInResult result) {
}
</code>```

Reading status codes

That parameter has useful information you are ignoring. You can retrieve the error status code if the sign-in is not successful...

```<code>private void handleSignInResult(GoogleSignInResult result) {
    if(!result.isSuccess()){

        Status status = result.getStatus();
    }
}
</code>```

With that status, you can check why the sign-in failed by checking the status code

```<code>int code = status.getStatusCode();

if(code == GoogleSignInStatusCodes.SIGN_IN_REQUIRED){
}
else if(code == GoogleSignInStatusCodes.NETWORK_ERROR){
}
</code>```

All the constants can be found in the GoogleSignInStatusCode documentation here...

https://developers.google.com/android/reference/com/google/android/gms/auth/api/signin/GoogleSignInStatusCodes

and here...

https://developers.google.com/android/reference/com/google/android/gms/common/api/CommonStatusCodes

Resolving the sign-in issue

You could even attempt to resolve the problem by tdetermining if the error has resolution...

```<code>private void handleSignInResult(GoogleSignInResult result) {
    if(!result.isSuccess()){

        Status status = result.getStatus();

        if(status.hasResolution()){
            status.startResolutionForActivity(this, SIGN_IN_RESOLUTION_REQUEST_CODE);
        }
    }
}
</code>```

which will start an intent that could probably resolve the issue for the user. Then you can check the result of that resolution on the onActivityResult method...

```<code>@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if(requestCode == SIGN_IN_RESOLUTION_REQUEST_CODE){
    }
}
</code>```

Google API Availability

If all the above fails. The next thing you can do is check for Google API availability on the user's device.
Basically, in one comment you admitted that your solution is INDEED working in SOME devices.
If that is the case, then I'm inclined to point out that some Google Libraries require a specific version of Google Play services

The best way to know what exactly the problem is...it's by doing a Google API availability check and then output as much info as you can to logcat...you can do that easily, see below...

```<code>private boolean checkPlayServices(){
    GoogleApiAvailability gaa = GoogleApiAvailability.getInstance();
    int result = gaa.isGooglePlayServicesAvailable(getApplicationContext());
    Log.d("isGooglePlayServicesAvailable returned %d", result);

    if(result != ConnectionResult.SUCCESS){
        if(gaa.isUserResolvableError(result)){
            gaa.getErrorDialog(this,result, REQUEST_PLAY_SERVICES_RESOLUTION).show();
        }

        return false;
    }

    return true;
}
</code>```

isGooglePlayServicesAvailable will return an integer constant that can be translated to one of the ConnectionResult constants. The list of constants and it's meaning is quite large to cover here.

Another key part of the code snippet above is that you could attempt to have the system resolve the error for you if the error is easily resolvable, for example, if the user needs to update Google Play Services on their device because the current version is outdated

Where would you use the above method?

Anywhere make the first connection attempt to Google APIs. For example, using your original code snippet...

```<code>private void handleSignInResult(GoogleSignInResult result) {

    if (result.isSuccess()) {
        //code block omitted
    } else {
        checkPlayServices();
    }
}
</code>```

Title: Google Sign in not working properly

Body:
I have integrated sign in with google in my android application, now issue is that in some device its not working,but in my emulator and in some device it is working fine,what is the issue?

https://developers.google.com/identity/sign-in/android/

http://www.androidhive.info/2014/02/android-login-with-google-plus-account-1/

this two tutorials to sign in, but when i run my app, and try to login it allows to select account,but when i click on that in my logcat it shows

System.out: Google logout

CODE

private void handleSignInResult(GoogleSignInResult result) {
        Log.d("", "handleSignInResult:" + result.isSuccess());
        if (result.isSuccess()) {
            // Signed in successfully, show authenticated UI.
            GoogleSignInAccount acct = result.getSignInAccount();

            Log.e("", "display name: " + acct.getDisplayName());

            personName = acct.getDisplayName();
            personPhotoUrl = String.valueOf(acct.getPhotoUrl());
            ggoleemail = acct.getEmail();
            googleid = "G" + acct.getId();
          //  String baday = String.valueOf(acct.getAccount());

            Log.e(TAG, "Name: " + personName + googleid  + ", email: " + ggoleemail
                    + ", Image: " + personPhotoUrl);
          /*  txtName.setText(personName);
            txtEmail.setText(email);
            Glide.with(getApplicationContext()).load(personPhotoUrl)
                    .thumbnail(0.5f)
                    .crossFade()
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .into(imgProfilePic);
*/
            googleslogins();
          //  updateUI(true);

        } else {
            // Signed out, show unauthenticated UI.
            //updateUI(false);
            System.out.println("Google logout");
        }
    }

Body:
There are a few things you are not doing. Firstly, you are losing a lot of information about why the connection is not successful because you are no inspecting the cause of the connection failure coming in the GoogleSignInResult parameter...

private void handleSignInResult(GoogleSignInResult result) {
}

Reading status codes

That parameter has useful information you are ignoring. You can retrieve the error status code if the sign-in is not successful...

private void handleSignInResult(GoogleSignInResult result) {
    if(!result.isSuccess()){

        Status status = result.getStatus();
    }
}

With that status, you can check why the sign-in failed by checking the status code

int code = status.getStatusCode();

if(code == GoogleSignInStatusCodes.SIGN_IN_REQUIRED){
}
else if(code == GoogleSignInStatusCodes.NETWORK_ERROR){
}

All the constants can be found in the GoogleSignInStatusCode documentation here...

https://developers.google.com/android/reference/com/google/android/gms/auth/api/signin/GoogleSignInStatusCodes

and here...

https://developers.google.com/android/reference/com/google/android/gms/common/api/CommonStatusCodes

Resolving the sign-in issue

You could even attempt to resolve the problem by tdetermining if the error has resolution...

private void handleSignInResult(GoogleSignInResult result) {
    if(!result.isSuccess()){

        Status status = result.getStatus();

        if(status.hasResolution()){
            status.startResolutionForActivity(this, SIGN_IN_RESOLUTION_REQUEST_CODE);
        }
    }
}

which will start an intent that could probably resolve the issue for the user. Then you can check the result of that resolution on the onActivityResult method...

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if(requestCode == SIGN_IN_RESOLUTION_REQUEST_CODE){
    }
}

Google API Availability

If all the above fails. The next thing you can do is check for Google API availability on the user's device.
Basically, in one comment you admitted that your solution is INDEED working in SOME devices.
If that is the case, then I'm inclined to point out that some Google Libraries require a specific version of Google Play services

The best way to know what exactly the problem is...it's by doing a Google API availability check and then output as much info as you can to logcat...you can do that easily, see below...

private boolean checkPlayServices(){
    GoogleApiAvailability gaa = GoogleApiAvailability.getInstance();
    int result = gaa.isGooglePlayServicesAvailable(getApplicationContext());
    Log.d("isGooglePlayServicesAvailable returned %d", result);

    if(result != ConnectionResult.SUCCESS){
        if(gaa.isUserResolvableError(result)){
            gaa.getErrorDialog(this,result, REQUEST_PLAY_SERVICES_RESOLUTION).show();
        }

        return false;
    }

    return true;
}

isGooglePlayServicesAvailable will return an integer constant that can be translated to one of the ConnectionResult constants. The list of constants and it's meaning is quite large to cover here.

Another key part of the code snippet above is that you could attempt to have the system resolve the error for you if the error is easily resolvable, for example, if the user needs to update Google Play Services on their device because the current version is outdated

Where would you use the above method?

Anywhere make the first connection attempt to Google APIs. For example, using your original code snippet...

private void handleSignInResult(GoogleSignInResult result) {

    if (result.isSuccess()) {
        //code block omitted
    } else {
        checkPlayServices();
    }
}


问:
Splitting a large sql file on statement boundaries?
I need to import a large SQL table from an Oracle database to a mySQL database. I "dumped" the Oracle table using RazorSQL so that I now have a large (2.5 GB) .sql file, with many INSERT statements.

This file is too big and I want to split it so that I import it in chunks. What would be a clever way to split such a file?

using the split command would work except some string values contains newlines characters so that there is a high risk of split splitting mid-statement.

a Perl quickie using a regexp to split on ";\n" (end of statement) would work, but there is still the remote possibility that such a character sequence could be found in the data.

Of course I can always write a parser to understand string quoting. I am wondering though whether there is anything smarter?

Similar questions have been asked. eg:

How do I split the output from mysqldump into smaller files?

But the only splitting solution has been a suggestion for some Windows software. Windows is not an option for me. I run Unix, namely Mac OS X.

To give some background, the reason I want to do that is that I have an error when importing the file into mySQL. Localizing the error is painful if only because it's time consuming, and because opening such large text files for editing is non trivial at best with most text editors. Some of my SQL tools don't even report the location of the error in the file, which would strongly suggest a dichotomy approach to zeroing on to the error by splitting number of times. Automatizing this would be useful.

Thanks for any idea.

答:
Not exactly an answer to your question, but maybe a solution to your problem:

Install Navicat (MySQL GUI). It has an oracle=>mysql migration tool, that might help you, because, most likely, errors you get come from syntax differences. It will be a hard task to convert one SQL dialect to another by hand.


问:
VBA Dynamic Regex Pattern Within "If"
I'm working on a tool to pull multiple forms of reference numbers from text and I'm struggling to think of a smart way to iterate through different RegEx patterns. Example of what I'm after is something like (pseudocode for what I'm after in curly braces):

```<code>Dim regEx as New RegExp
Dim someinput as String

regEx.Pattern = "201[67]\W?\d{6}"

If regEx.Test(someinput) = True Then
   foo
Elseif {with regEx.pattern="AB\W?\d{10}"  regEx.Test(someinput)} Then
   bar
...
</code>```

This is going to be several levels deep as we've got around a dozen possible formats to check through. All I can think of at the moment is defining a new regEx item for each, setting the patterns for each, then running through the If->ElseIfs one by one, but there must be a better way... I hope!

Thanks much

Edit Just to pre-empt, foo and bar will be different depending on the input, so I can't just make (for instance) an array of possible patterns and run through checking each one and then returning a final "True/False"

答:
Personally, I would do this in a loop:</p>

```<code>Dim regEx As New RegExp
Dim someinput As String
Dim patterns
Dim i As Long
Dim match As Long
patterns = Array("201[67]\W?\d{6}", _
                 "AB\W?\d{10}")

match = -1
For i = LBound(patterns) To UBound(patterns)
    regEx.Pattern = patterns(i)
    If regEx.Test(someinput) Then
        match = i - LBound(patterns)  ' subtract the lower bound to force zero-base
        Exit For
    End If
Next

Select Case match
    Case 0: foo
    Case 1: bar
    Case Else: MsgBox "No match found"
End Select
</code>```

Title: VBA Dynamic Regex Pattern Within "If"

Body:
I'm working on a tool to pull multiple forms of reference numbers from text and I'm struggling to think of a smart way to iterate through different RegEx patterns. Example of what I'm after is something like (pseudocode for what I'm after in curly braces):

Dim regEx as New RegExp
Dim someinput as String

regEx.Pattern = "201[67]\W?\d{6}"

If regEx.Test(someinput) = True Then
   foo
Elseif {with regEx.pattern="AB\W?\d{10}"  regEx.Test(someinput)} Then
   bar
...

This is going to be several levels deep as we've got around a dozen possible formats to check through. All I can think of at the moment is defining a new regEx item for each, setting the patterns for each, then running through the If->ElseIfs one by one, but there must be a better way... I hope!

Thanks much

Edit Just to pre-empt, foo and bar will be different depending on the input, so I can't just make (for instance) an array of possible patterns and run through checking each one and then returning a final "True/False"

Body:
Personally, I would do this in a loop:

Dim regEx As New RegExp
Dim someinput As String
Dim patterns
Dim i As Long
Dim match As Long
patterns = Array("201[67]\W?\d{6}", _
                 "AB\W?\d{10}")

match = -1
For i = LBound(patterns) To UBound(patterns)
    regEx.Pattern = patterns(i)
    If regEx.Test(someinput) Then
        match = i - LBound(patterns)  ' subtract the lower bound to force zero-base
        Exit For
    End If
Next

Select Case match
    Case 0: foo
    Case 1: bar
    Case Else: MsgBox "No match found"
End Select


问:
React Native componentWillMount / componentDidMount not going triggered after pop navigating and navigate again
I am new in React Native ...just want ask nub question, my App wont triggered componentWillMount and componentDidMount when navigate back to other page,
I use react-native-router-flux for navigator

```<code>componentWillMount() {
 this.props.searchRequest();
}
</code>```

exp: I have homescreen and categories, from home I want go to categories: on categories I have that code, but sometime when I back to previouse page (homescreen) and back again on categories componentWillMount not triggered sometime,

I think my categories scene not unmounted

答:
We can detect props change with

componentWillReceiveProps()

but we need set state to accommodate new props value,

Body:
I am new in React Native ...just want ask nub question, my App wont triggered componentWillMount and componentDidMount when navigate back to other page,
I use react-native-router-flux for navigator

componentWillMount() {
 this.props.searchRequest();
}

exp: I have homescreen and categories, from home I want go to categories: on categories I have that code, but sometime when I back to previouse page (homescreen) and back again on categories componentWillMount not triggered sometime,

I think my categories scene not unmounted


问:
'TypeError: Expected String or Unicode' when trying to convert json to pandas dataframe
I have a json file:

```<code>['abc', 'bcd', 'chg', 'sdf', 'bvd', 'wer', 'ewe', 'sbc', 'osc']

>type(json_data)
>list
</code>```

I am trying to convert it to a dataframe and add a column with an index:

```<code>df = pd.read_json(json_data)
</code>```

I am getting an error:

```<code>TypeError: Expected String or Unicode
</code>```

What am I doing wrong?

答:
Is this what you are after? json_data is a list so there's no need to call read_json.</p>

```<code>pd.DataFrame(json_data)
Out[715]:
     0
0  abc
1  bcd
2  chg
3  sdf
4  bvd
5  wer
6  ewe
7  sbc
8  osc
</code>```

Body:
I have a json file:

['abc', 'bcd', 'chg', 'sdf', 'bvd', 'wer', 'ewe', 'sbc', 'osc']

>type(json_data)
>list

I am trying to convert it to a dataframe and add a column with an index:

df = pd.read_json(json_data)

I am getting an error:

TypeError: Expected String or Unicode

What am I doing wrong?

Body:
Is this what you are after? json_data is a list so there's no need to call read_json.

pd.DataFrame(json_data)
Out[715]:
     0
0  abc
1  bcd
2  chg
3  sdf
4  bvd
5  wer
6  ewe
7  sbc
8  osc


问:
How do I create an HTML table with a fixed/frozen left column and a scrollable body?
I need a simple solution. I know it's similar to some other questions, like:

HTML table with fixed headers and a fixed column?

How can I lock the first row and first column of a table when scrolling, possibly using JavaScript and CSS?

But I need just a single left column to be frozen and I would prefer a simple and script-less solution.

答:
Here is another modification of the most popular answer, but with handling of variable length of text in the first column labels:
http://jsfiddle.net/ozx56n41/

Basically, I'm using the second column for creating row height, like was mentioned. But my fiddle actually works unlike most mentioned above.

HTML:

```<code><div id="outerdiv">
    <div id="innerdiv">
        <table>
            <tr>
                <td class="headcol"><div>This is a long label</div></td>
                <td class="hiddenheadcol"><div>This is a long label</div></td>
                <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
                <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
            </tr>
            <tr>
                <td class="headcol"><div>Short label</div></td>
                <td class="hiddenheadcol"><div>Short label</div></td>
                <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
                <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
            </tr>
        </table>
    </div>
</div>
</code>```

CSS:

```<code>body {
    font: 16px Calibri;
}
#outerdiv {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    width: 100%;
    border-top: 1px solid grey;
}
#innerdiv {
    overflow-x: scroll;
    margin-left: 100px;
    overflow-y: visible;
    padding-bottom: 1px;
}
table {
    border-collapse:separate;
}
td {
    margin: 0;
    border: 1px solid grey;
    border-top-width: 0;
    border-left-width: 0px;
    padding: 10px;
}
td.headcol {
    /* Frozen 1st column */
    position: absolute;
    left: 0;
    top: auto;
    border-bottom-width: 1px;
    padding: 0;
    border-left-width: 1px;
}
td.hiddenheadcol {
    /* Hidden 2nd column to create height */
    max-width: 0;
    visibility: hidden;
    padding: 0;
}
td.headcol div {
    /* Text container in the 1st column */
    width: 100px;
    max-width: 100px;
    background: lightblue;
    padding: 10px;
    box-sizing: border-box;
}
td.hiddenheadcol div {
    /* Text container in the 2nd column */
    width: 100px;
    max-width: 100px;
    background: red;
    padding: 10px;
}
td.long {
    background:yellow;
    letter-spacing:1em;
}
</code>```

Body:
Here is another modification of the most popular answer, but with handling of variable length of text in the first column labels:
http://jsfiddle.net/ozx56n41/

Basically, I'm using the second column for creating row height, like was mentioned. But my fiddle actually works unlike most mentioned above.

HTML:

<div id="outerdiv">
    <div id="innerdiv">
        <table>
            <tr>
                <td class="headcol"><div>This is a long label</div></td>
                <td class="hiddenheadcol"><div>This is a long label</div></td>
                <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
                <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
            </tr>
            <tr>
                <td class="headcol"><div>Short label</div></td>
                <td class="hiddenheadcol"><div>Short label</div></td>
                <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
                <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
            </tr>
        </table>
    </div>
</div>

CSS:

body {
    font: 16px Calibri;
}
#outerdiv {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    width: 100%;
    border-top: 1px solid grey;
}
#innerdiv {
    overflow-x: scroll;
    margin-left: 100px;
    overflow-y: visible;
    padding-bottom: 1px;
}
table {
    border-collapse:separate;
}
td {
    margin: 0;
    border: 1px solid grey;
    border-top-width: 0;
    border-left-width: 0px;
    padding: 10px;
}
td.headcol {
    /* Frozen 1st column */
    position: absolute;
    left: 0;
    top: auto;
    border-bottom-width: 1px;
    padding: 0;
    border-left-width: 1px;
}
td.hiddenheadcol {
    /* Hidden 2nd column to create height */
    max-width: 0;
    visibility: hidden;
    padding: 0;
}
td.headcol div {
    /* Text container in the 1st column */
    width: 100px;
    max-width: 100px;
    background: lightblue;
    padding: 10px;
    box-sizing: border-box;
}
td.hiddenheadcol div {
    /* Text container in the 2nd column */
    width: 100px;
    max-width: 100px;
    background: red;
    padding: 10px;
}
td.long {
    background:yellow;
    letter-spacing:1em;
}


问:
Iterate over subclasses of a given class in a given module
In Python, given a module X and a class Y, how can I iterate or generate a list of all subclasses of Y that exist in module X?</p>

答:
Here's one way to do it:</p>

```<code>import inspect

def get_subclasses(mod, cls):
    """Yield the classes in module ``mod`` that inherit from ``cls``"""
    for name, obj in inspect.getmembers(mod):
        if hasattr(obj, "__bases__") and cls in obj.__bases__:
            yield obj
</code>```

OwnerDisplayName: Mark Roddy

Body:
Here's one way to do it:

import inspect

def get_subclasses(mod, cls):
    """Yield the classes in module ``mod`` that inherit from ``cls``"""
    for name, obj in inspect.getmembers(mod):
        if hasattr(obj, "__bases__") and cls in obj.__bases__:
            yield obj

OwnerDisplayName: catlee