问:
Regex - everything except string
I would like to replace every char that is not a string for a given char like | or ; or whatever.
I have simple regex patern: ([a-zA-Z])\w+

...and the problem is to replace everything except matches of that pattern.

Example: qwerty 123456 ;,.'[]?/ asd

Result: qwerty|||||||||||||||||asd

Thanks in advance.

答:
For this input:

qwerty 123456 ;,.'[]?/ asd

You want to match all non-word plus digits, so you can use [\W\d]

But since you want to replace them one-by-one not all them at once you no need to use quantifier +

Also you can use: build-in-character class if your engine or your language has them. For example:

```<code>[:alnum:]       all letters and digits
[:alpha:]       all letters
[:blank:]       all horizontal whitespace
[:cntrl:]       all control characters
[:digit:]       all digits
[:graph:]       all printable characters, not including space
[:lower:]       all lower case letters
[:print:]       all printable characters, including space
[:punct:]       all punctuation characters
[:space:]       all horizontal or vertical whitespace
[:upper:]       all upper case letters
[:xdigit:]      all hexadecimal digits
</code>```

See a fest test with Perl

```<code>echo "qwerty 123456 ;,.'[]?/ asd" | perl -lpe 's/[[:cntrl:][:punct:]\d ]/|/g'
</code>```

or:

```<code>echo "qwerty 123456 ;,.'[]?/ asd" | perl -lpe 's/[\W\d]/|/g'
</code>```

has the same output:

```<code>qwerty|||||||||||||||||asd
</code>```

NOTE:

For more detail you can see: Regular Expression Reference: Shorthand Character Classes

Title: Regex - everything except string

Body:
For this input:

qwerty 123456 ;,.'[]?/ asd

You want to match all non-word plus digits, so you can use [\W\d]

But since you want to replace them one-by-one not all them at once you no need to use quantifier +

Also you can use: build-in-character class if your engine or your language has them. For example:

[:alnum:]       all letters and digits
[:alpha:]       all letters
[:blank:]       all horizontal whitespace
[:cntrl:]       all control characters
[:digit:]       all digits
[:graph:]       all printable characters, not including space
[:lower:]       all lower case letters
[:print:]       all printable characters, including space
[:punct:]       all punctuation characters
[:space:]       all horizontal or vertical whitespace
[:upper:]       all upper case letters
[:xdigit:]      all hexadecimal digits

See a fest test with Perl

echo "qwerty 123456 ;,.'[]?/ asd" | perl -lpe 's/[[:cntrl:][:punct:]\d ]/|/g'

or:

echo "qwerty 123456 ;,.'[]?/ asd" | perl -lpe 's/[\W\d]/|/g'

has the same output:

qwerty|||||||||||||||||asd

NOTE:

For more detail you can see: Regular Expression Reference: Shorthand Character Classes


来源: stackexchange

问:
Bitbucket notify on start failed
```
Bitbucket notify on start failed: Root URL isn't configured yet. Cannot compute absolute URL.
java.lang.IllegalStateException: Root URL isn't configured yet. Cannot compute absolute URL.
    at hudson.model.AbstractItem.getAbsoluteUrl(AbstractItem.java:486)
    at org.jenkinsci.plugins.bitbucket.BitbucketBuildStatusHelper.buildUrlFromBuild(BitbucketBuildStatusHelper.java:182)
    at org.jenkinsci.plugins.bitbucket.BitbucketBuildStatusHelper.createBitbucketBuildStatusFromBuild(BitbucketBuildStatusHelper.java:197)
    at org.jenkinsci.plugins.bitbucket.BitbucketBuildStatusHelper.notifyBuildStatus(BitbucketBuildStatusHelper.java:224)
    at org.jenkinsci.plugins.bitbucket.BitbucketBuildStatusNotifier.prebuild(BitbucketBuildStatusNotifier.java:109)
    at hudson.model.AbstractBuild$AbstractBuildExecution.preBuild(AbstractBuild.java:789)
    at hudson.model.AbstractBuild$AbstractBuildExecution.preBuild(AbstractBuild.java:784)
    at hudson.model.Build$BuildExecution.doRun(Build.java:145)
    at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:490)
    at hudson.model.Run.execute(Run.java:1735)
    at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)
    at hudson.model.ResourceController.execute(ResourceController.java:97)
    at hudson.model.Executor.run(Executor.java:405)
```

I got that error when I was trying to use the Bitbucket Build Status Notifier Plugin ( https://wiki.jenkins.io/display/JENKINS/Bitbucket+Cloud+Build+Status+Notifier+Plugin ) on Jenkins CI. I followed this tutorial: https://www.youtube.com/watch?v=uu5XcU4EPzQ but I don't know what the problem is.

答:
The answer is simpler than I thought, but I couldn't find it anywhere. On BitBucket in the user profile settings and in OAuth, the consumer you create have to have the Callback URL ending with /. For example:
Before was: http://jenkinsUrl:8080 and it was throwing that error, now I just added the / and it worked: http://jenkinsUrl:8080/

ContentLicense: CC BY-SA 3.0

Title: Bitbucket notify on start failed

Body:
Bitbucket notify on start failed: Root URL isn't configured yet. Cannot compute absolute URL.
java.lang.IllegalStateException: Root URL isn't configured yet. Cannot compute absolute URL.
    at hudson.model.AbstractItem.getAbsoluteUrl(AbstractItem.java:486)
    at org.jenkinsci.plugins.bitbucket.BitbucketBuildStatusHelper.buildUrlFromBuild(BitbucketBuildStatusHelper.java:182)
    at org.jenkinsci.plugins.bitbucket.BitbucketBuildStatusHelper.createBitbucketBuildStatusFromBuild(BitbucketBuildStatusHelper.java:197)
    at org.jenkinsci.plugins.bitbucket.BitbucketBuildStatusHelper.notifyBuildStatus(BitbucketBuildStatusHelper.java:224)
    at org.jenkinsci.plugins.bitbucket.BitbucketBuildStatusNotifier.prebuild(BitbucketBuildStatusNotifier.java:109)
    at hudson.model.AbstractBuild$AbstractBuildExecution.preBuild(AbstractBuild.java:789)
    at hudson.model.AbstractBuild$AbstractBuildExecution.preBuild(AbstractBuild.java:784)
    at hudson.model.Build$BuildExecution.doRun(Build.java:145)
    at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:490)
    at hudson.model.Run.execute(Run.java:1735)
    at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)
    at hudson.model.ResourceController.execute(ResourceController.java:97)
    at hudson.model.Executor.run(Executor.java:405)

I got that error when I was trying to use the Bitbucket Build Status Notifier Plugin ( https://wiki.jenkins.io/display/JENKINS/Bitbucket+Cloud+Build+Status+Notifier+Plugin ) on Jenkins CI. I followed this tutorial: https://www.youtube.com/watch?v=uu5XcU4EPzQ but I don't know what the problem is.


问:
Load external environment parameters in Symfony 3.2 using env() at runtime return unresolved values
I have a parameters file in an application using symfony 3.2 console, config and YAML component , and i try to set external Parameters from environment variable in the Service Container parameters.

I create container builder.

```<code>$container = new ContainerBuilder();
</code>```

Am using file locator to locate resources :

```<code>$container = new ContainerBuilder();
</code>```

Loader resolver to load resources

```<code>LoaderResolver();
</code>```

And using load method :

```<code>$this->load('parameters.yml');
</code>```

parameters.yml file:

```<code>parameters:
  database:
    driver: pdo_mysql
    host: 127.0.0.1
    dbname: dbname
    user: env(VAL1)
    password: env(VAL2)
  Local: us-en
</code>```

After compiling the container and try to check get values from parameters bag :

```<code>$container->getParameterBag()->all()
</code>```

its return me values like this :

env_VAL1_3ec776edc429c1734ed780a29a0af538 , env_VAL2_3ec776edc429c1734ed780a29a0af538

I think the container can't resolve those values from the environment .

Note : i set the environment variable using :

```<code>$ export VAL1='SOME TEXT'
</code>```

Anyone has an idea why ?

答:
If you use Symfony\Bundle\FrameworkBundle\Test\WebTestCase instead of \PHPUnit_Framework_TestCase Symfony3 do the magic for you.

```<code>$client = static::createClient();
$this->container = $client->getContainer();
$user = $container->getParameter('user'); // $user = 'abc'
</code>```

take a look on
http://symfony.com/doc/current/testing.html#your-first-functional-test

With this method you will able to tweak also Symfony configurations using *_test.yml specific files.

I think this is the right way.

Body:
I have a parameters file in an application using symfony 3.2 console, config and YAML component , and i try to set external Parameters from environment variable in the Service Container parameters.

I create container builder.

$container = new ContainerBuilder();

Am using file locator to locate resources :

$container = new ContainerBuilder();

Loader resolver to load resources

LoaderResolver();

And using load method :

$this->load('parameters.yml');

parameters.yml file:

parameters:
  database:
    driver: pdo_mysql
    host: 127.0.0.1
    dbname: dbname
    user: env(VAL1)
    password: env(VAL2)
  Local: us-en

After compiling the container and try to check get values from parameters bag :

$container->getParameterBag()->all()

its return me values like this :

env_VAL1_3ec776edc429c1734ed780a29a0af538 , env_VAL2_3ec776edc429c1734ed780a29a0af538

I think the container can't resolve those values from the environment .

Note : i set the environment variable using :

$ export VAL1='SOME TEXT'

Anyone has an idea why ?

Body:
If you use Symfony\Bundle\FrameworkBundle\Test\WebTestCase instead of \PHPUnit_Framework_TestCase Symfony3 do the magic for you.

$client = static::createClient();
$this->container = $client->getContainer();
$user = $container->getParameter('user'); // $user = 'abc'

take a look on
http://symfony.com/doc/current/testing.html#your-first-functional-test

With this method you will able to tweak also Symfony configurations using *_test.yml specific files.

I think this is the right way.


问:
Jasypt with the Bouncy Castle JCE SHA512 encryption
I need:
password based encryption using sha512 digesting and 256 bit AES encryption with cbc and bc flags set.

Seems that algorithm should be like this: PBEWithSHA512AndAES256-CBC-BC

but in my local env I get error: org.jasypt.exceptions.EncryptionInitializationException: java.security.NoSuchAlgorithmException: no such algorithm: PBEWithSHA512AndAES256-CBC-BC for provider BC

my test code:

```<code>import java.security.Security;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;

public class App {

static {
    Security.addProvider(new BouncyCastleProvider());
}

public static void main(String[] args) {
    StandardPBEStringEncryptor mySecondEncryptor = new StandardPBEStringEncryptor();
    mySecondEncryptor.setProviderName("BC");
    // mySecondEncryptor.setAlgorithm("PBEWITHSHA256AND128BITAES-CBC-BC");
    mySecondEncryptor.setAlgorithm("PBEWithSHA512AndAES256-CBC-BC");
    mySecondEncryptor.setPassword("pass");

    String myText = "Mindaugas";
    String mySecondEncryptedText = mySecondEncryptor.encrypt(myText);

    System.out.println(mySecondEncryptedText);
    System.out.println(mySecondEncryptor.decrypt(mySecondEncryptedText));
}
}
</code>```

PBEWITHSHA256AND128BITAES-CBC-BC - this algorithm works fine but I need sha512 and 256 bit AES...

I have installed extensions form: http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html

but still get this error: no such algorithm

答:
Since the list of algorithms on the bouncycastle website is not updated, looking at the code in the constructor in the Java file BouncyCastleProvider.java, you can find an exhaustive list of algorithms which are supported by bcprov-jdk16. A small list (of the type of algorithms/functions you were looking for) supported is -</p>

```<code>PBEWITHSHAAND128BITAES-CBC-BC
PBEWITHSHAAND192BITAES-CBC-BC
PBEWITHSHAAND256BITAES-CBC-BC
PBEWITHSHA256AND128BITAES-CBC-BC
PBEWITHSHA256AND192BITAES-CBC-BC
PBEWITHSHA256AND256BITAES-CBC-BC
PBEWITHSHA1AND128BITAES-CBC-BC
PBEWITHSHA1AND192BITAES-CBC-BC
PBEWITHSHA1AND256BITAES-CBC-BC
PBEWITHSHA-1AND128BITAES-CBC-BC
PBEWITHSHA-1AND192BITAES-CBC-BC
PBEWITHSHA-1AND256BITAES-CBC-BC
PBEWITHSHA-256AND128BITAES-CBC-BC
PBEWITHSHA-256AND192BITAES-CBC-BC
PBEWITHSHA-256AND256BITAES-CBC-BC
</code>```

Body:
I need:
password based encryption using sha512 digesting and 256 bit AES encryption with cbc and bc flags set.

Seems that algorithm should be like this: PBEWithSHA512AndAES256-CBC-BC

but in my local env I get error: org.jasypt.exceptions.EncryptionInitializationException: java.security.NoSuchAlgorithmException: no such algorithm: PBEWithSHA512AndAES256-CBC-BC for provider BC

my test code:

import java.security.Security;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;

public class App {

static {
    Security.addProvider(new BouncyCastleProvider());
}

public static void main(String[] args) {
    StandardPBEStringEncryptor mySecondEncryptor = new StandardPBEStringEncryptor();
    mySecondEncryptor.setProviderName("BC");
    // mySecondEncryptor.setAlgorithm("PBEWITHSHA256AND128BITAES-CBC-BC");
    mySecondEncryptor.setAlgorithm("PBEWithSHA512AndAES256-CBC-BC");
    mySecondEncryptor.setPassword("pass");

    String myText = "Mindaugas";
    String mySecondEncryptedText = mySecondEncryptor.encrypt(myText);

    System.out.println(mySecondEncryptedText);
    System.out.println(mySecondEncryptor.decrypt(mySecondEncryptedText));
}
}

PBEWITHSHA256AND128BITAES-CBC-BC - this algorithm works fine but I need sha512 and 256 bit AES...

I have installed extensions form: http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html

but still get this error: no such algorithm

Body:
Since the list of algorithms on the bouncycastle website is not updated, looking at the code in the constructor in the Java file BouncyCastleProvider.java, you can find an exhaustive list of algorithms which are supported by bcprov-jdk16. A small list (of the type of algorithms/functions you were looking for) supported is -

PBEWITHSHAAND128BITAES-CBC-BC
PBEWITHSHAAND192BITAES-CBC-BC
PBEWITHSHAAND256BITAES-CBC-BC
PBEWITHSHA256AND128BITAES-CBC-BC
PBEWITHSHA256AND192BITAES-CBC-BC
PBEWITHSHA256AND256BITAES-CBC-BC
PBEWITHSHA1AND128BITAES-CBC-BC
PBEWITHSHA1AND192BITAES-CBC-BC
PBEWITHSHA1AND256BITAES-CBC-BC
PBEWITHSHA-1AND128BITAES-CBC-BC
PBEWITHSHA-1AND192BITAES-CBC-BC
PBEWITHSHA-1AND256BITAES-CBC-BC
PBEWITHSHA-256AND128BITAES-CBC-BC
PBEWITHSHA-256AND192BITAES-CBC-BC
PBEWITHSHA-256AND256BITAES-CBC-BC


问:
Python using regex to extract parts of a string in pandas column
I've got a pandas df column called 'Raw' for which the format is inconsistent. The strings it contains look like that:

```<code>'(1T XXX, Europe)'
'(2T YYYY, Latin America)'
'(3T ZZ/ZZZZ, Europe)'
'(4T XXX XXX, Africa)'
</code>```

The only thing consistent in the strings in 'Raw' is that they start with a digit, includes a comma in the middle followed by a whitespace, and they contain parentheses as well.

Now, I'd like to create two extra columns (Model and Region) in my dataframe:

'Model' would contain the beginning of the string, i.e. everything between the first parenthesis and the comma

'Region' would contain the end of the string, i.e. everything between the whitespace after the comma and the final parenthesis

How do I do that using regex?

答:
```<code>string_list = ['(1T XXX, Europe)',
'(2T YYYY, Latin America)',
'(3T ZZ/ZZZZ, Europe)',
'(4T XXX XXX, Africa)']
df = pd.DataFrame(string_list)
df = df[0].str.extract("\(([^,]*), ([^)]*)\)", expand=False)
</code>```

Body:
I've got a pandas df column called 'Raw' for which the format is inconsistent. The strings it contains look like that:

'(1T XXX, Europe)'
'(2T YYYY, Latin America)'
'(3T ZZ/ZZZZ, Europe)'
'(4T XXX XXX, Africa)'

The only thing consistent in the strings in 'Raw' is that they start with a digit, includes a comma in the middle followed by a whitespace, and they contain parentheses as well.

Now, I'd like to create two extra columns (Model and Region) in my dataframe:

'Model' would contain the beginning of the string, i.e. everything between the first parenthesis and the comma

'Region' would contain the end of the string, i.e. everything between the whitespace after the comma and the final parenthesis

How do I do that using regex?


问:
Laravel hasManyThrough in depth
I have been looking at documentation regarding the hasManyThrough relationship in Laravel, and fro some reason I am struggling with it as the documentation makes it look simple (maybe I am overthinking it)....

I have three Models tables at the moment:

```<code>-User (extends authenticatable)
    id,
    name,
    surname,
    email,
    password.

-Order
    id,
    user_id,
    name,
    unit,
    qty

-Product (i need to add a qty table to show how many is ordered).
    id,
    order_id,
    name,
    unit,
    description,
    family
</code>```

My Products model is used by Admin to CRUD products.

Please can someone explain to me how I will be able to display to admin which user made an order, and what does the order consist of.
I also want to display to the user a 'order history'..

Please will anyone be able to assist..

UPDATE

```<code>-order_product
  id,
  order_id,
  product_id
  quantity
</code>```

product controller:

```<code>  public function orders()
    {
       return $this->belongsToMany('App\Order')->withPivot('quantity');
    }
</code>```

order controller:

```<code>  public function products()
    {
       return $this->belongsToMany('App\Product')->withPivot('quantity');
    }
</code>```

答:
It is many to many to relationship show you'll have to create one another pivot table named
order_product with fields

-id

-order_id

-product_id

-quantity

and in your Order table Model define relationship as

```<code>public function products()
{
  return $this->belongsToMany('App\Product')->withPivot('quantity');
}
</code>```

and in your Product table Model define relationship as

```<code>public function orders()
{
  return $this->belongsToMany('App\Order')->withPivot('quantity');
}
</code>```

to Retrieve data

```<code>$order= App\Order::find(1);

@foreach ($order->products as $product)
    echo $product->pivot->quantity."<br>";
@endforeach
</code>```

Title: Laravel hasManyThrough in depth

Body:
I have been looking at documentation regarding the hasManyThrough relationship in Laravel, and fro some reason I am struggling with it as the documentation makes it look simple (maybe I am overthinking it)....

I have three Models tables at the moment:

-User (extends authenticatable)
    id,
    name,
    surname,
    email,
    password.

-Order
    id,
    user_id,
    name,
    unit,
    qty

-Product (i need to add a qty table to show how many is ordered).
    id,
    order_id,
    name,
    unit,
    description,
    family

My Products model is used by Admin to CRUD products.

Please can someone explain to me how I will be able to display to admin which user made an order, and what does the order consist of.
I also want to display to the user a 'order history'..

Please will anyone be able to assist..

UPDATE

-order_product
  id,
  order_id,
  product_id
  quantity

product controller:

  public function orders()
    {
       return $this->belongsToMany('App\Order')->withPivot('quantity');
    }

order controller:

  public function products()
    {
       return $this->belongsToMany('App\Product')->withPivot('quantity');
    }

Body:
It is many to many to relationship show you'll have to create one another pivot table named
order_product with fields

-id

-order_id

-product_id

-quantity

and in your Order table Model define relationship as

public function products()
{
  return $this->belongsToMany('App\Product')->withPivot('quantity');
}

and in your Product table Model define relationship as

public function orders()
{
  return $this->belongsToMany('App\Order')->withPivot('quantity');
}

to Retrieve data

$order= App\Order::find(1);

@foreach ($order->products as $product)
    echo $product->pivot->quantity."<br>";
@endforeach


问:
ggplotly barchart and line chart with separate labels
I have the following dataset:

```<code>       dput(head(table_age))
structure(list(Age = c("0-19", "20-24", "25-29", "30-34", "35-39",
"40-44"), Freq_nominal = c(1321, 3446, 5354, 7233, 7471, 6623
), Freq_percent = c(1.92, 5.01, 7.79, 10.52, 10.86, 9.63), Percent = c("1.92%",
"5.01%", "7.79%", "10.52%", "10.86%", "9.63%"), Nominal = c(1321,
3446, 5354, 7233, 7471, 6623), female = c(655L, 1473L, 2275L,
2929L, 3081L, 2830L), male = c(665L, 1918L, 3002L, 4258L, 4347L,
3762L), female_percent = c(2.2, 4.94, 7.63, 9.82, 10.33, 9.49
), female_percent_label = c("2.2%", "4.94%", "7.63%", "9.82%",
"10.33%", "9.49%"), male_percent = c(1.73, 4.99, 7.8, 11.07,
11.3, 9.78), male_percent_label = c("1.73%", "4.99%", "7.8%",
"11.07%", "11.3%", "9.78%")), .Names = c("Age", "Freq_nominal",
"Freq_percent", "Percent", "Nominal", "female", "male", "female_percent",
"female_percent_label", "male_percent", "male_percent_label"), row.names = c(NA,
6L), class = "data.frame")
</code>```

I used ggplotly to interactivly plot the Age as a barchart, and display custom labels in the tooltip with the text parametar.

This is the working code:

```<code>t <- ggplot(table_age, aes(as.factor(Age), Freq_percent, text1 = Nominal,
                           text = paste0("Age group: ", Age), text2 = Percent))  +

  geom_bar(position="dodge",stat="identity", fill = "deepskyblue4", width = 0.5) +

  theme(legend.title=element_blank()) +
  xlab("") + ylab("") +
  theme_minimal()

ggplotly(t, tooltip = c("text1", "text2"))
</code>```

I want to overlay a line/point for each gender on top of the age barchart. In that respect, I have two problems:

geom_point gets plotted through plotly, but not geom_line (when static plot it works fine)

i don't know how to label the geom_points seperately from the geom_bar

This is my attempt code:

```<code>t <- ggplot(table_age, aes(as.factor(Age), Freq_percent, text1 = Nominal,
                           text = paste0("Age group: ", Age), text2 = Percent))  +

  geom_bar(position="dodge",stat="identity", fill = "deepskyblue4", width = 0.5) +

  theme(legend.title=element_blank()) +
  xlab("") + ylab("") +
  theme_minimal()

t <- t + geom_point(data=table_age, aes(x=Age, y=female_percent), size = 2, color="magenta")
t <- t + geom_line(data=table_age, aes(x=Age, y=female_percent), colour="magenta")

ggplotly(t, tooltip = c("text1", "text2", "female"))
</code>```

Any ideas?

答:
geom_line() needs (usually) a group aesthetic, which we can set to a constant to have a single group of obs. This will display geom_line.

To display different tooltip we can use a single 'hidden' text aesthetic (as you already did) and override it.

In this case is better to define the aess inside each geom instead of defining inside the initial ggplot() call.

On to the code:

library(ggplot2)
library(plotly)

t <- ggplot(table_age)  +
    geom_bar(aes(as.factor(Age),
                 Freq_percent,
                 #text = paste0("Age group: ", Age),
                 text1 = Nominal,
                 text2 = Percent),
             position = "dodge",
             stat = "identity",
             fill = "deepskyblue4",
             width = 0.5) +
    geom_point(aes(as.factor(Age),
                   female_percent,
                   text1 = female),
               size = 2,
               color="magenta") +
    geom_line(aes(as.factor(Age),
                  female_percent,
                  group = 1),
              color = "magenta") +
    theme(legend.title = element_blank()) +
    xlab("") +
    ylab("") +
    theme_minimal()
#> Warning: Ignoring unknown aesthetics: text1, text2
#> Warning: Ignoring unknown aesthetics: text1

t
```

<p><img src="https://i.imgur.com/2GYut75.png" alt=""></p>

<pre class="lang-r prettyprint-override"><code>ggplotly(t, tooltip = c("text1", "text2"))
</code>```

Body:
I have the following dataset:

       dput(head(table_age))
structure(list(Age = c("0-19", "20-24", "25-29", "30-34", "35-39",
"40-44"), Freq_nominal = c(1321, 3446, 5354, 7233, 7471, 6623
), Freq_percent = c(1.92, 5.01, 7.79, 10.52, 10.86, 9.63), Percent = c("1.92%",
"5.01%", "7.79%", "10.52%", "10.86%", "9.63%"), Nominal = c(1321,
3446, 5354, 7233, 7471, 6623), female = c(655L, 1473L, 2275L,
2929L, 3081L, 2830L), male = c(665L, 1918L, 3002L, 4258L, 4347L,
3762L), female_percent = c(2.2, 4.94, 7.63, 9.82, 10.33, 9.49
), female_percent_label = c("2.2%", "4.94%", "7.63%", "9.82%",
"10.33%", "9.49%"), male_percent = c(1.73, 4.99, 7.8, 11.07,
11.3, 9.78), male_percent_label = c("1.73%", "4.99%", "7.8%",
"11.07%", "11.3%", "9.78%")), .Names = c("Age", "Freq_nominal",
"Freq_percent", "Percent", "Nominal", "female", "male", "female_percent",
"female_percent_label", "male_percent", "male_percent_label"), row.names = c(NA,
6L), class = "data.frame")

I used ggplotly to interactivly plot the Age as a barchart, and display custom labels in the tooltip with the text parametar.

This is the working code:

t <- ggplot(table_age, aes(as.factor(Age), Freq_percent, text1 = Nominal,
                           text = paste0("Age group: ", Age), text2 = Percent))  +

  geom_bar(position="dodge",stat="identity", fill = "deepskyblue4", width = 0.5) +

  theme(legend.title=element_blank()) +
  xlab("") + ylab("") +
  theme_minimal()

ggplotly(t, tooltip = c("text1", "text2"))

I want to overlay a line/point for each gender on top of the age barchart. In that respect, I have two problems:

geom_point gets plotted through plotly, but not geom_line (when static plot it works fine)

i don't know how to label the geom_points seperately from the geom_bar

This is my attempt code:

t <- ggplot(table_age, aes(as.factor(Age), Freq_percent, text1 = Nominal,
                           text = paste0("Age group: ", Age), text2 = Percent))  +

  geom_bar(position="dodge",stat="identity", fill = "deepskyblue4", width = 0.5) +

  theme(legend.title=element_blank()) +
  xlab("") + ylab("") +
  theme_minimal()

t <- t + geom_point(data=table_age, aes(x=Age, y=female_percent), size = 2, color="magenta")
t <- t + geom_line(data=table_age, aes(x=Age, y=female_percent), colour="magenta")

ggplotly(t, tooltip = c("text1", "text2", "female"))

Any ideas?

Body:
geom_line() needs (usually) a group aesthetic, which we can set to a constant to have a single group of obs. This will display geom_line.

To display different tooltip we can use a single 'hidden' text aesthetic (as you already did) and override it.

In this case is better to define the aess inside each geom instead of defining inside the initial ggplot() call.

On to the code:

library(ggplot2)
library(plotly)

t <- ggplot(table_age)  +
    geom_bar(aes(as.factor(Age),
                 Freq_percent,
                 #text = paste0("Age group: ", Age),
                 text1 = Nominal,
                 text2 = Percent),
             position = "dodge",
             stat = "identity",
             fill = "deepskyblue4",
             width = 0.5) +
    geom_point(aes(as.factor(Age),
                   female_percent,
                   text1 = female),
               size = 2,
               color="magenta") +
    geom_line(aes(as.factor(Age),
                  female_percent,
                  group = 1),
              color = "magenta") +
    theme(legend.title = element_blank()) +
    xlab("") +
    ylab("") +
    theme_minimal()
#> Warning: Ignoring unknown aesthetics: text1, text2
#> Warning: Ignoring unknown aesthetics: text1

t

ggplotly(t, tooltip = c("text1", "text2"))


问:
Undefined index errors (PHP)
I'm getting notices of an undefined index "id" on lines 3, 6 and 7 in this code. I can't figure out what I'm doing wrong:

```<code>    if ( isset($_POST['action']) && $_POST['action'] == 'save' ) {
    foreach ($options as $value) {
        if(($value['type'] === "checkbox" or $value['type'] === "multiselect" ) and is_array($_REQUEST[ $value['id'] ]))
            { $_REQUEST[ $value['id'] ]=implode(',',$_REQUEST[ $value['id'] ]); //This will take from the array and make one string
            }
        $key = $value['id'];
        $val = $_REQUEST[$key];
        $settings[$key] = $val;
    }
</code>```

I'm thinking this is a small thing to fix but haven't had any luck with anything I've tried. One thing I did do is run var_dump($key) and sometimes $key is null and sometimes it's not. So I'm assuming it has to do with this.

This is part of an options page for a WordPress theme, by the way. This is the code that runs as part of the "save" function.

The script actually works properly if debug mode is turned off, but when debug mode is on, these notices pop up when hitting the save button on the options page. Thanks in advance for any insights, and let me know if I need to post more code to give more context.

EDIT: I've posted the options page in pastebin. It's long. It contains t13lo's fixes. The problem code is on line 1957. Thanks: http://pastebin.com/NGX6qzgr

答:
You can change line 3 to:

```<code>if ( ($value['type'] === "checkbox" || $value['type'] === "multiselect" ) && isset($_REQUEST['id']) && is_array($_REQUEST[ $value['id'] ]) )
</code>```

However, the rest of your code in your foreach seems dependent upon $value['id']. This value is not always being set so it may make these lines:

```<code>$key = $value['id'];
$val = $_REQUEST[$key];
$settings[$key] = $val;
</code>```

Irrelevant if $value['id'] is not set. If that's the case, placing all of the code that is currently in the foreach within an if (isset($value['id'])) { may be appropriate.

You'll need to further analyze and understand what the code is (and needs to be) doing in order to determine the correct logic.

ContentLicense: CC BY-SA 2.5

Title: Undefined index errors (PHP)

Body:
I'm getting notices of an undefined index "id" on lines 3, 6 and 7 in this code. I can't figure out what I'm doing wrong:

    if ( isset($_POST['action']) && $_POST['action'] == 'save' ) {
    foreach ($options as $value) {
        if(($value['type'] === "checkbox" or $value['type'] === "multiselect" ) and is_array($_REQUEST[ $value['id'] ]))
            { $_REQUEST[ $value['id'] ]=implode(',',$_REQUEST[ $value['id'] ]); //This will take from the array and make one string
            }
        $key = $value['id'];
        $val = $_REQUEST[$key];
        $settings[$key] = $val;
    }

I'm thinking this is a small thing to fix but haven't had any luck with anything I've tried. One thing I did do is run var_dump($key) and sometimes $key is null and sometimes it's not. So I'm assuming it has to do with this.

This is part of an options page for a WordPress theme, by the way. This is the code that runs as part of the "save" function.

The script actually works properly if debug mode is turned off, but when debug mode is on, these notices pop up when hitting the save button on the options page. Thanks in advance for any insights, and let me know if I need to post more code to give more context.

EDIT: I've posted the options page in pastebin. It's long. It contains t13lo's fixes. The problem code is on line 1957. Thanks: http://pastebin.com/NGX6qzgr

Body:
You can change line 3 to:

if ( ($value['type'] === "checkbox" || $value['type'] === "multiselect" ) && isset($_REQUEST['id']) && is_array($_REQUEST[ $value['id'] ]) )

However, the rest of your code in your foreach seems dependent upon $value['id']. This value is not always being set so it may make these lines:

$key = $value['id'];
$val = $_REQUEST[$key];
$settings[$key] = $val;

Irrelevant if $value['id'] is not set. If that's the case, placing all of the code that is currently in the foreach within an if (isset($value['id'])) { may be appropriate.

You'll need to further analyze and understand what the code is (and needs to be) doing in order to determine the correct logic.


问:
Can I change my android application style at runtime?
I want to change the manifest style when the user chooses a setting in the preferences file or settings. I have a setting in my apk which includes a list of preferences with three entries {Style_1, Style_2, Style_3}. I want to change the style color, like primaryColor, when the user clicks a style. How can I do this?

答:
Yes you can set Theme like this:</p>

```<code>    activity.setTheme(R.style.theme_large);
    activity.setTheme(R.style.theme_small);

    <style name="theme_large">
            <item name="main_background">@drawable/background_red</item>
            <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
            <item name="button_light">@color/button_light</item>
    </style>

    <style name="theme_small">
            <item name="main_background">@drawable/background_red</item>
            <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
            <item name="button_light">@color/button_light</item>
    </style>
</code>```

Body:
Yes you can set Theme like this:

    activity.setTheme(R.style.theme_large);
    activity.setTheme(R.style.theme_small);

    <style name="theme_large">
            <item name="main_background">@drawable/background_red</item>
            <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
            <item name="button_light">@color/button_light</item>
    </style>

    <style name="theme_small">
            <item name="main_background">@drawable/background_red</item>
            <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
            <item name="button_light">@color/button_light</item>
    </style>


问:
Overplot trends in matplotlib: every loop gives additional trend
With the code below I get three different plots, and I would like to know how to combine them so that I have three lines on one plot. I thought there is something simple as overplot instead of plot, but somehow I could't find it.

Somehow I also need to adjust the x to the "longest" dataset.

```<code>import matplotlib.pyplot as plt

big_array = [[4,5,4,5],[6,4,1],[1,2,3,4]]
for i in big_array:
    x = range(len(i))
    y = i
    plt.plot(x, y)
    plt.show()
</code>```

答:
When you call plt.show() this displays all the current figures that have been drawn and blocks the rest of the code until the figure window has been closed.

As you are in a loop of 3 iterations you code will display and block the figure at each call to show. Then when you close the window your loop will continue, creating another figure when you call plt.plot() and then displays it again when you call show.

To fix you should only call plt.show() at the end of your script:

```<code>big_array = [[4,5,4,5],[6,4,1],[1,2,3,4]]

for i in big_array:
    x = range(len(i))
    y = i
    plt.plot(x, y)

plt.show()
</code>```

Which will produce the following figure:

Body:
With the code below I get three different plots, and I would like to know how to combine them so that I have three lines on one plot. I thought there is something simple as overplot instead of plot, but somehow I could't find it.

Somehow I also need to adjust the x to the "longest" dataset.

import matplotlib.pyplot as plt

big_array = [[4,5,4,5],[6,4,1],[1,2,3,4]]
for i in big_array:
    x = range(len(i))
    y = i
    plt.plot(x, y)
    plt.show()

Body:
When you call plt.show() this displays all the current figures that have been drawn and blocks the rest of the code until the figure window has been closed.

As you are in a loop of 3 iterations you code will display and block the figure at each call to show. Then when you close the window your loop will continue, creating another figure when you call plt.plot() and then displays it again when you call show.

To fix you should only call plt.show() at the end of your script:

big_array = [[4,5,4,5],[6,4,1],[1,2,3,4]]

for i in big_array:
    x = range(len(i))
    y = i
    plt.plot(x, y)

plt.show()

Which will produce the following figure:


问:
Why do I always get 403 when fetching data with RestTemplate?
I'm trying to fetch data but always getting 403(Forbidden) with RestTemplate.

But when I try org.apache.http.client.HttpClient instead, everything is OK. I'm also able to get data with Postman on my machine.

The code is quite simple but I don't know what's wrong.

```<code>public Object get() {
        try {
            RestTemplate restTemplate = new RestTemplate();
            Object result = restTemplate.getForObject("https://api.hearthstonejson.com/v1/19776/enUS/cards.json", Object.class);
            return result;
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            return null;
        }
    }
</code>```

EDIT: appending stack trace

```<code>org.springframework.web.client.HttpClientErrorException: 403 Forbidden
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:63)
    at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:700)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:653)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:613)
    at org.springframework.web.client.RestTemplate.getForObject(RestTemplate.java:287)
    at com.brawlstone.metaservice.service.SyncService.get(SyncService.java:49)
    at com.brawlstone.metaservice.web.SyncController.getCards(SyncController.java:30)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:105)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.springframework.boot.web.support.ErrorPageFilter.doFilter(ErrorPageFilter.java:115)
    at org.springframework.boot.web.support.ErrorPageFilter.access$000(ErrorPageFilter.java:59)
    at org.springframework.boot.web.support.ErrorPageFilter$1.doFilterInternal(ErrorPageFilter.java:90)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.boot.web.support.ErrorPageFilter.doFilter(ErrorPageFilter.java:108)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:522)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1095)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:672)
    at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2500)
    at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2489)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
</code>```

答:
You are trying to access https without configuring RestTemplate to use any SSL certificate for request

Try to use following configuration of RestTemplate

```<code>CloseableHttpClient httpClient = HttpClients.custom()
                    .setSSLHostnameVerifier(new NoopHostnameVerifier())
                    .build();
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);
RestTemplate restTemplate = new RestTemplate(requestFactory);
Object result = restTemplate.getForObject("https://api.hearthstonejson.com/v1/19776/enUS/cards.json", Object.class);
....
</code>```

Body:
I'm trying to fetch data but always getting 403(Forbidden) with RestTemplate.

But when I try org.apache.http.client.HttpClient instead, everything is OK. I'm also able to get data with Postman on my machine.

The code is quite simple but I don't know what's wrong.

public Object get() {
        try {
            RestTemplate restTemplate = new RestTemplate();
            Object result = restTemplate.getForObject("https://api.hearthstonejson.com/v1/19776/enUS/cards.json", Object.class);
            return result;
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            return null;
        }
    }

EDIT: appending stack trace

org.springframework.web.client.HttpClientErrorException: 403 Forbidden
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:63)
    at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:700)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:653)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:613)
    at org.springframework.web.client.RestTemplate.getForObject(RestTemplate.java:287)
    at com.brawlstone.metaservice.service.SyncService.get(SyncService.java:49)
    at com.brawlstone.metaservice.web.SyncController.getCards(SyncController.java:30)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:105)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.springframework.boot.web.support.ErrorPageFilter.doFilter(ErrorPageFilter.java:115)
    at org.springframework.boot.web.support.ErrorPageFilter.access$000(ErrorPageFilter.java:59)
    at org.springframework.boot.web.support.ErrorPageFilter$1.doFilterInternal(ErrorPageFilter.java:90)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.boot.web.support.ErrorPageFilter.doFilter(ErrorPageFilter.java:108)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:522)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1095)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:672)
    at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2500)
    at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2489)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)

Body:
You are trying to access https without configuring RestTemplate to use any SSL certificate for request

Try to use following configuration of RestTemplate

CloseableHttpClient httpClient = HttpClients.custom()
                    .setSSLHostnameVerifier(new NoopHostnameVerifier())
                    .build();
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);
RestTemplate restTemplate = new RestTemplate(requestFactory);
Object result = restTemplate.getForObject("https://api.hearthstonejson.com/v1/19776/enUS/cards.json", Object.class);
....


问:
Vertical Scrollbar is not Working while trying with Mouse Wheel#FF,Chrome
I have a grid with around 8 rows and 10 columns(Ext 4.2.1-with JS Code) and I got a "vertical scrollbar" as the data size is more than min data size.But while trying to move the scrollbar using "mouse wheel",its lagging in Firefox(version:54.0.1),Google(version:59.0.3071.115).

I created the Grid with one of the columns is locked. I noticed that when grid column(s) is locked the mouseonwheel scrolling is very slow(When I am scrolling with my cursor on locked column. Scrolling happens smoothly when the cursor is on unlocked column.)

Here is my column configuration

```<code>columns: [
        { text: 'Name',  dataIndex: 'name',locked   : true},
        { text: 'Email', dataIndex: 'email', flex: 1,lockable : false },
        { text: 'Phone', dataIndex: 'phone',locked   : true }
    ],
</code>```

Here when my cursor is on Name and phone , Scrolling is happening smoothly. But when I am trying to scroll with cursor on Email Scrolling is not happening as expected. (Means scrolling is hard)

Here is my fiddler. Fiddle You can give a try.

How to overcome this. I am using ExtJS 4.2.1

答:
If you override onLockedViewScroll method in your grid and set it as an empty function, it should do the trick.

```<code>Ext.create('Ext.grid.Panel', {
    ...
    onLockedViewScroll: Ext.emptyFn,
});
</code>```

Body:
I have a grid with around 8 rows and 10 columns(Ext 4.2.1-with JS Code) and I got a "vertical scrollbar" as the data size is more than min data size.But while trying to move the scrollbar using "mouse wheel",its lagging in Firefox(version:54.0.1),Google(version:59.0.3071.115).

I created the Grid with one of the columns is locked. I noticed that when grid column(s) is locked the mouseonwheel scrolling is very slow(When I am scrolling with my cursor on locked column. Scrolling happens smoothly when the cursor is on unlocked column.)

Here is my column configuration

columns: [
        { text: 'Name',  dataIndex: 'name',locked   : true},
        { text: 'Email', dataIndex: 'email', flex: 1,lockable : false },
        { text: 'Phone', dataIndex: 'phone',locked   : true }
    ],

Here when my cursor is on Name and phone , Scrolling is happening smoothly. But when I am trying to scroll with cursor on Email Scrolling is not happening as expected. (Means scrolling is hard)

Here is my fiddler. Fiddle You can give a try.

How to overcome this. I am using ExtJS 4.2.1

Body:
If you override onLockedViewScroll method in your grid and set it as an empty function, it should do the trick.

Ext.create('Ext.grid.Panel', {
    ...
    onLockedViewScroll: Ext.emptyFn,
});


问:
Best 2D Plane out of 3D points
I have the following problem: I have given some 3D Points like
(0,2,2), (0,4,5) etc..

And I want to get the best fit Plane through those points. It's a bit like a linear regression. The problem is, the points don't match exactly. So I have to find the best plane going through them in the 3D area. The Size of the plane doesn't matter, I just need one Vector out of my points.
I read a bit about regression but It didn't help me out.

I just ask for a resource, pseudo code or just a working code. Just something for me to start.

答:
If you have source code for fitting a 2D polynomial such as

Y = a + bX + cX^2

you will see that internally the code regresses Y against X^0 (1.0), X^1 (X)and X^2 to find equation parameters a, b, and c. You might also have regressed Y against other terms such as sin(X) or exp(X), the source code that performs the linear regression does not care and would happily fit those terms also.

You can use that same source code to instead determine parameters for

Z = a + bX + cY

by regressing Z against 1.0,  X^1 (X) and Y^1 (Y) to find equation parameters a, b and c. You might also regress against X^1 * Y^1 (X*Y) or even sin(X) or [log(X) * exp(Y)].

Many software packages have pre-packaged functions for fitting 2D polynomials because that fitting task is very common, but the code inside such functions can be used as I describe above - if you have source code, look through the polynomial fitting method and copy-paste-edit the code's data formatting as I describe above and you should be fine.

Title: Best 2D Plane out of 3D points


问:
jQuery slider - slide: function (event, ui) in for loop
I have a simple code with 2 (or more) jQuery sliders:

HTML:

```<code><label for="ST">ST:</label>
<input type="text" id="ST" value="10">
<div id="slider-ST"></div>

<label for="DX">DX:</label>
<input type="text" id="DX" value="10">
<div id="slider-DX"></div>
</code>```

and JS:

```<code>$function(){
$( "#slider-ST" ).slider({
  orientation: "horizontal",
  range: "min",
  value: 10,

  slide: function (event, ui) {sliderChange(ui,"#ST");}
});

$( "#slider-DX" ).slider({
  orientation: "horizontal",
  range: "min",
  value: 10,

  slide: function (event, ui) {sliderChange(ui,"#DX");}
});

function sliderChange(t, disp)
{
   $(disp).val(t.value);
};
}
</code>```

It works perfectly well.

Now, I want to make it nicer and I would like to call these functions in a for loop:

```<code>$function(){
var ID_Inp = ["#slider-ST", "#slider-DX"];
var ID_Sli = ["#ST", "#DX"];
var i;
for (i=0;i<ID_Inp.length;i++)
{
  $(ID_Inp[i]).slider({
  orientation: "horizontal",
  range: "min",
  min: 1,
  max: 18,
  value: 10,

  slide: function (event, ui) {sliderChange(ui,ID_Sli[i]);}
  });
};
function sliderChange(t, disp)
{
   $(disp).val(t.value);
};
}
</code>```

Simplified code also available at jsfiddle:

working

not working (using for loop)

And what happens is, that i is set to 2 after changing the slider's value and obviously function sliderChange doesn't work properly (ID_Sli[i] is undefined).

Any ideas?

答:
For loop is not good option for this , I think you need to do like following:

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">

  Minimum number of bedrooms:
  <input type="text" id="amountbeds">

    Minimum number of cars:
    <input type="text" id="amountcars">

```

For more information read documention

Body:
I have a simple code with 2 (or more) jQuery sliders:

HTML:

ST:
<input type="text" id="ST" value="10">

DX:
<input type="text" id="DX" value="10">

and JS:

$function(){
$( "#slider-ST" ).slider({
  orientation: "horizontal",
  range: "min",
  value: 10,

  slide: function (event, ui) {sliderChange(ui,"#ST");}
});

$( "#slider-DX" ).slider({
  orientation: "horizontal",
  range: "min",
  value: 10,

  slide: function (event, ui) {sliderChange(ui,"#DX");}
});

function sliderChange(t, disp)
{
   $(disp).val(t.value);
};
}

It works perfectly well.

Now, I want to make it nicer and I would like to call these functions in a for loop:

$function(){
var ID_Inp = ["#slider-ST", "#slider-DX"];
var ID_Sli = ["#ST", "#DX"];
var i;
for (i=0;i<ID_Inp.length;i++)
{
  $(ID_Inp[i]).slider({
  orientation: "horizontal",
  range: "min",
  min: 1,
  max: 18,
  value: 10,

  slide: function (event, ui) {sliderChange(ui,ID_Sli[i]);}
  });
};
function sliderChange(t, disp)
{
   $(disp).val(t.value);
};
}

Simplified code also available at jsfiddle:

working

not working (using for loop)

And what happens is, that i is set to 2 after changing the slider's value and obviously function sliderChange doesn't work properly (ID_Sli[i] is undefined).

Any ideas?

Body:
For loop is not good option for this , I think you need to do like following:

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
  $(function() {
    $("#slider-range-max-cars,#slider-range-max-beds").slider({
      range: "max",
      value: 2,
      slide: function(event, ui) {
        $("#amountcars").val($("#slider-range-max-cars").slider("value"));
        $("#amountbeds").val($("#slider-range-max-beds").slider("value"));
      }
    });
    $("#amountcars").val($("#slider-range-max-cars").slider("value"));
    $("#amountbeds").val($("#slider-range-max-beds").slider("value"));
  });
</script>

<body>
  <label for="beds">Minimum number of bedrooms:</label>
  <input type="text" id="amountbeds">
  <div id="slider-range-max-beds"></div>

  <p>
    <label for="cars">Minimum number of cars:</label>
    <input type="text" id="amountcars">
    <div id="slider-range-max-cars"></div>
    <div id="debug">

    </div>
</body>

</html>

For more information read documention


答:
try this : </p>

```<code>if(($value['type'] === "checkbox" || $value['type'] === "multiselect" ) &&  isset($value['id']) && is_array($_REQUEST[ $value['id'] ])){ ...
</code>```

Title: Undefined index errors (PHP)

Body:
try this :

if(($value['type'] === "checkbox" || $value['type'] === "multiselect" ) &&  isset($value['id']) && is_array($_REQUEST[ $value['id'] ])){ ...


问:
Displaying values in modal from ng-repeat
I have list of stories with images , content and title in ng-repeat.
When I click on particular story , I need a bootstrap model to open and values to be displayed . I am doing it by calling a function showStories(); But I couldnt do it . I am getting empty value since its globally declared as

```<code>            $scope.selectedStoryPreview =  "";
            $scope.selectedStoryContent = "";
            $scope.selectedStoryTitle  = "";
</code>```

Html :

```<code><div class="image" ng-repeat="item in filteredStories track by $index">
    <img ng-src="{{item.images}}" style="cursor: pointer;" ng-click="showStories(item)" data-toggle="modal" data-target="#storyPreview">
    <button><span>{{item.title}}</span>
    </button>
</div>
</code>```

JS:

```<code>$scope.showStories = function(item) {

            $scope.selectedStoryPreview =  item.images;
            $scope.selectedStoryContent = item.content;
            $scope.selectedStoryTitle  = item.title;

        }
</code>```

Modal :

```<code><div class="modal fade" id="storyPreview" role="dialog"  data-keyboard="false" data-backdrop="static" style="padding-top: 8em;">

        <div class="modal-dialog">
  <div class="modal-content" style="text-align: center;">
    <div class="modal-header imagemodalhead">
        <h4>{{selectedStoryTitle}}</h4>
        <a class="edit" ng-click="openmanageprofile()"><img src="css/images/edit.png">
        </a>
    </div>
    <div class="modal-body" style="background: #eee;">

        <div class="row">

            <img class="file-imageStory" ng-src="{{selectedStoryPreview}}" />

        </div>
        <br>
        <div class="row">
            <div class=" col-sm-12 storyPrv">
                <span class="styletheStory">{{selectedStoryContent}}</span>
            </div>
        </div>

        <div class="modal-footer imagefooter">
            <button type="button" class="button share" ng-click="closePreview()" style="background-color: #7B7D7D; color: black;">close</button>
        </div>

    </div>
</code>```

答:
If modal controller is different. Then send the value using resolve method. If the controller is same. Then I think it should display the values.

And provide the id of modal here :

```<code><div class="modal-content" id="storyPreview" style="text-align: center;">
</code>```

Body:
I have list of stories with images , content and title in ng-repeat.
When I click on particular story , I need a bootstrap model to open and values to be displayed . I am doing it by calling a function showStories(); But I couldnt do it . I am getting empty value since its globally declared as

            $scope.selectedStoryPreview =  "";
            $scope.selectedStoryContent = "";
            $scope.selectedStoryTitle  = "";

Html :

    <button>{{item.title}}
    </button>

JS:

$scope.showStories = function(item) {

            $scope.selectedStoryPreview =  item.images;
            $scope.selectedStoryContent = item.content;
            $scope.selectedStoryTitle  = item.title;

        }

Modal :

{{selectedStoryTitle}}

                {{selectedStoryContent}}

            <button type="button" class="button share" ng-click="closePreview()" style="background-color: #7B7D7D; color: black;">close</button>

Body:
If modal controller is different. Then send the value using resolve method. If the controller is same. Then I think it should display the values.

And provide the id of modal here :

<div class="modal-content" id="storyPreview" style="text-align: center;">


问:
Azure DocumentDB .NET SDK does not contains all HTTP Status Codes
When you look at the document of HTTP status codes that CosmosDB REST API returns, there are some status codes that does not exist in .NET SDK.

HTTP Status Codes for Azure Cosmos DB

Suppose, status code 449, does not exist in the HttpStatusCode(System.Net).

"449 Retry With"

The operation encountered a transient error.

This only occurs on write operations.

It is safe to retry the operation.

How do you handle this sort of status code using the Azure DocDb's .NET client SDK?

Or does the SDK handles these by itself?

答:
As you said, if we check the StatusCode property (that is nullable) of DocumentClientException, we will find that status code 449 does not exist in the System.Net.HttpStatusCode.

After check the source of Azure DocumentDB .NET SDK, the SDK seems handle these by itself.


问:
Adding MYSQL to Cloud Foundry and using it as a service
I am new to cloud foundry service, and wondering if the community can help to answer my question.

I have a simple WordPress app pushed to Cloud Foundry cf push Wordpress which has backend MYSQL servers. I have been asked to add MYSQL as a service within Cloud Foundry, but currently this does not exist.

When i perform cf marketplace there is not an option for MYSQL.

Simply put how do i get MYSQL on Cloud Foundry for my app to use it as a service.

Thanks

答: Here are instructions how to deploy a MySQL bosh release to your environment and register a service broker for it so that it appears in cf marketplace: https://github.com/cloudfoundry/cf-mysql-release


问:
[KDB+/Q]: Deparse q parse tree into q expression (string)
Let's define deparse1 as inverse operation to q's native parse, so that the following holds:

```<code>q)aStringQExpression~deparse parse aStringQExpression
1b
</code>```

Question

What's the definition of deparse function so that the above indeed works?

For example, in the  below update expression, we know that "a*0^b+c-d" expression corresponds to (*;`a;(^;0;(+;`b;(-;`c;`d)))) parse tree:

```<code>q)-3!parse "update col:a*0^b+c-d from t"
"(!;`t;();0b;(,`col)!,(*;`a;(^;0;(+;`b;(-;`c;`d)))))"
</code>```

So the envisaged deparse function should return:

```<code>q)deparse "(*;`a;(^;0;(+;`b;(-;`c;`d))))"
"a*0^b+c-d"
q)deparse "(!;`t;();0b;(,`col)!,(*;`a;(^;0;(+;`b;(-;`c;`d)))))"
"update col:a*0^b+c-d from t"
</code>```

Motivation/Background/Use case:
Inline expressions are arguably faster to grok by human eye (left-to-right) than deeply nested parse trees. Although in the background my code is editing the parse tree programatically, it is useful for debugging or presentation to conveniently convert that resulting parse tree into inline expression string.

1 Similar functionality described here: http://adv-r.had.co.nz/Expressions.html#parsing-and-deparsing

答:
I think the only way to do this would be to parse the list recursively and build up a string, e.g. for a dyadic:

```<code>q)deparse:{a:-3!'x;a[1],a[0],a[2]}
q)deparse parse "3*3"
"3*3"
</code>```

So you can count last x to get it valency and build the string accordingly

Body:
Let's define deparse1 as inverse operation to q's native parse, so that the following holds:

q)aStringQExpression~deparse parse aStringQExpression
1b

Question

What's the definition of deparse function so that the above indeed works?

For example, in the  below update expression, we know that "a*0^b+c-d" expression corresponds to (*;`a;(^;0;(+;`b;(-;`c;`d)))) parse tree:

q)-3!parse "update col:a*0^b+c-d from t"
"(!;`t;();0b;(,`col)!,(*;`a;(^;0;(+;`b;(-;`c;`d)))))"

So the envisaged deparse function should return:

q)deparse "(*;`a;(^;0;(+;`b;(-;`c;`d))))"
"a*0^b+c-d"
q)deparse "(!;`t;();0b;(,`col)!,(*;`a;(^;0;(+;`b;(-;`c;`d)))))"
"update col:a*0^b+c-d from t"

Motivation/Background/Use case:
Inline expressions are arguably faster to grok by human eye (left-to-right) than deeply nested parse trees. Although in the background my code is editing the parse tree programatically, it is useful for debugging or presentation to conveniently convert that resulting parse tree into inline expression string.

1 Similar functionality described here: http://adv-r.had.co.nz/Expressions.html#parsing-and-deparsing

Body:
I think the only way to do this would be to parse the list recursively and build up a string, e.g. for a dyadic:

q)deparse:{a:-3!'x;a[1],a[0],a[2]}
q)deparse parse "3*3"
"3*3"

So you can count last x to get it valency and build the string accordingly


问:
javascript element.style is undefined in FF
I want to set up css display property in javascript code:

```<code>    var div = document.createElement('div');
    div.innerHTML = content;
    div.childNodes[0].style.display = '';
</code>```

It works in IE but doesn't in FF. It says "style" is undefined for element div.  How can I do it in FF?

Thanks

答:
What is content? If it starts with white space, then there will be a TextNode as the first child and they don't have style properties (HTMLElementNodes do).

You can either:

loop over the children until you either get to the end or find an HTMLElementNode

strip the whitespace from the start of content

switch to using createElement and friends instead of innerHTML

Body:
I want to set up css display property in javascript code:

    var div = document.createElement('div');
    div.innerHTML = content;
    div.childNodes[0].style.display = '';

It works in IE but doesn't in FF. It says "style" is undefined for element div.  How can I do it in FF?

Thanks


问:
Angular 2 adding button to md-tab-group
Is it possible to add a button or an icon to md-tab-group?
I have the following template for example:

```<code><md-tab-group  [selectedIndex]="selectedIndex">

  <md-tab *ngFor="let tab of getTabs() let i=index">

    <ng-template md-tab-label>
      {{tab.title}} <md-icon class="tabRemove" (click)="removeTab(i)">close</md-icon>
    </ng-template>

    <tab [tabData]="tab"></tab>
  </md-tab>
</md-tab-group>
</code>```

I tried adding a button in the md-tab-group but it is not showing up. Is this even possible or should I find another way?

答:
You can add a button after <md-tab-group></md-tab-group> and change css position to needed position and give a z-index of 10:

```<code>button{
 postion:absolute;
 top:0;
 right:0;
 z-index:10;
}
</code>```

Title: Angular 2 adding button to md-tab-group

Body:
Is it possible to add a button or an icon to md-tab-group?
I have the following template for example:

<md-tab-group  [selectedIndex]="selectedIndex">

  <md-tab *ngFor="let tab of getTabs() let i=index">

    <ng-template md-tab-label>
      {{tab.title}} <md-icon class="tabRemove" (click)="removeTab(i)">close</md-icon>
    </ng-template>

    <tab [tabData]="tab"></tab>
  </md-tab>
</md-tab-group>

I tried adding a button in the md-tab-group but it is not showing up. Is this even possible or should I find another way?

Body:
You can add a button after <md-tab-group></md-tab-group> and change css position to needed position and give a z-index of 10:

button{
 postion:absolute;
 top:0;
 right:0;
 z-index:10;
}


问:
how to reuse JDBC Statements and automatic close back resultsets?
iam working on an project that will have many statements connected to DB
and i want to reuse statements instead of create new one every connect
and the most important thing that i don't want to close every resultset after use

i want to close back resultsets on statement before reuse it

my code look like this

```<code>ArrayList<Statement> BackStatements = new ArrayList();
int lastStatementIndex = 0;

private Statement GetStatement() throws SQLException {
    Statement SM;
    int MaxStatements = 5;
    if (BackStatements.size() < MaxStatements) {
        SM = Connection.createStatement();
        BackStatements.add(SM);
        lastStatementIndex = BackStatements.size() - 1;
    } else {
        lastStatementIndex = lastStatementIndex + 1;
        if (lastStatementIndex == MaxStatements) {
            lastStatementIndex = 0;
        }
        SM = BackStatements.get(lastStatementIndex);
     /// i want to close resultset generated by SM now and i do this before return this SM
        SM.getResultSet().close();

    }

    System.out.println("Last Index:" + lastStatementIndex + "---- Size:" + BackStatements.size());
    return SM;
}
</code>```

but this method return this error by logger

```<code>Caused by: java.sql.SQLException: ResultSet already requested
</code>```

答:
This looks like bad style to me. You can not ensure the oldest Statement (and ResultSet) is not in use anymore when forcefully closing it.

You give no hint where that Exeption happend but i think this could be the the cause.

If you want to use a statement pool, then you should actively give them back after usage.

Body:
iam working on an project that will have many statements connected to DB
and i want to reuse statements instead of create new one every connect
and the most important thing that i don't want to close every resultset after use

i want to close back resultsets on statement before reuse it

my code look like this

ArrayList<Statement> BackStatements = new ArrayList();
int lastStatementIndex = 0;

private Statement GetStatement() throws SQLException {
    Statement SM;
    int MaxStatements = 5;
    if (BackStatements.size() < MaxStatements) {
        SM = Connection.createStatement();
        BackStatements.add(SM);
        lastStatementIndex = BackStatements.size() - 1;
    } else {
        lastStatementIndex = lastStatementIndex + 1;
        if (lastStatementIndex == MaxStatements) {
            lastStatementIndex = 0;
        }
        SM = BackStatements.get(lastStatementIndex);
     /// i want to close resultset generated by SM now and i do this before return this SM
        SM.getResultSet().close();

    }

    System.out.println("Last Index:" + lastStatementIndex + "---- Size:" + BackStatements.size());
    return SM;
}

but this method return this error by logger

Caused by: java.sql.SQLException: ResultSet already requested


问:
Jaspersoft Studio: Is it possible to set default values for some properties, for example for textField?
When dragging Fields form the Outline into my Report a Textfield is created with some default properties. I dont like some of these properties. i.e. I would expect my textfields to always have the "Blank When NULL" Checkbox checked.

By now I have to mark all my Textfields and set that checkbox manually.
What i would like to do is tweak the default properties that are used to generate the textfield.

Is there any way to do this?

答:
Yes, it is possible. Jaspersoft Studio provides the concept of Element Templates, where you can set default settings for each element in the palette. You can have several templates and set a specific active template to set the "active" defaults.

A quick way to achieve what you are asking is to select a textfield in your document (which has been set to "Blank when NULL" property).

Right click the element and select Add to Template Set. If you don't have a template, it will ask to create one. A Template Set is a jrxml where Studio stores your defaults.

go back to your report and try to create a new textfield, you will see that the new element is a copy of the one defined in your template jrxml.

To change the template, or restore defaults, use the Settings menu on the top right of the designer view, by clicking on Settings> Elements Template.


问:
Terminate subprocess in python doesn't work
I want to terminate a subprocess, but it doesn't work. Here's my code:

```<code>import os
import subprocess

p = subprocess.Popen(['gnome-terminal','-e','tshark -i eth0 -w /root/Desktop/test.pcap'])
q = subprocess.Popen(['python','avtp2.py'])

if q.wait() == 0:
  p.terminate()
</code>```

Do you know why?

Greetz

答:
From the documentation:

Popen.wait()

Wait for child process to terminate. Set and return returncode attribute.

So for the body of the if to run, the process has to first terminate, you can use q.poll() instead, since it doesn't blocks.

Body:
I want to terminate a subprocess, but it doesn't work. Here's my code:

import os
import subprocess

p = subprocess.Popen(['gnome-terminal','-e','tshark -i eth0 -w /root/Desktop/test.pcap'])
q = subprocess.Popen(['python','avtp2.py'])

if q.wait() == 0:
  p.terminate()

Do you know why?

Greetz


问:
Compare hashMap arrays values with Javascript
How to compare between two Hashmaps that contains arrays in their values with javascript?

Example : Let suppose this is my 2 hashmaps

1st =>

```<code>1234 : [1.03 , 2.17 , 3]
1235 : [1 , 4 , 5]
1236 : [2 , 3 , 3]
1237 : [0.33 , 1.51 , 5]
</code>```

2nd =>

```<code>1234 : [1.03 , 2.17 , 3]
1235 : [1.17 , 2 , 3.9]
1236 : [2 , 3 , 3]
1237 : [2 , 1 , 5]
</code>```

Result =>

```<code>1235 : [1 , 4 , 5]
1237 : [0.33 , 1.51 , 5]
</code>```

(the goal is to compare the first with the second and display what keys and values of the first hashmap that aren't coherent).

答:
You can use Array.prototype.filter() and Array.prototype.map():

const one = {1234: [1.03, 2.17, 3],1235: [1, 4, 5],1236: [2, 3, 3],1237: [0.33, 1.51, 5]};
const two = {1234: [1.03, 2.17, 3],1235: [1.17, 2, 3.9],1236: [2, 3, 3],1237: [2, 1, 5]};
const result = Object.keys(one)
  .filter(k => one[k].toString() !== two[k].toString())
  .map(k => ({[k]: one[k]}));

console.log(result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
How to compare between two Hashmaps that contains arrays in their values with javascript?

Example : Let suppose this is my 2 hashmaps

1st =>

1234 : [1.03 , 2.17 , 3]
1235 : [1 , 4 , 5]
1236 : [2 , 3 , 3]
1237 : [0.33 , 1.51 , 5]

2nd =>

1234 : [1.03 , 2.17 , 3]
1235 : [1.17 , 2 , 3.9]
1236 : [2 , 3 , 3]
1237 : [2 , 1 , 5]

Result =>

1235 : [1 , 4 , 5]
1237 : [0.33 , 1.51 , 5]

(the goal is to compare the first with the second and display what keys and values of the first hashmap that aren't coherent).

Body:
You can use Array.prototype.filter() and Array.prototype.map():

const one = {1234: [1.03, 2.17, 3],1235: [1, 4, 5],1236: [2, 3, 3],1237: [0.33, 1.51, 5]};
const two = {1234: [1.03, 2.17, 3],1235: [1.17, 2, 3.9],1236: [2, 3, 3],1237: [2, 1, 5]};
const result = Object.keys(one)
  .filter(k => one[k].toString() !== two[k].toString())
  .map(k => ({[k]: one[k]}));

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
How to get the params from a saved XGBoost model
I'm trying to train a XGBoost model using the params below:

```<code>xgb_params = {
    'objective': 'binary:logistic',
    'eval_metric': 'auc',
    'lambda': 0.8,
    'alpha': 0.4,
    'max_depth': 10,
    'max_delta_step': 1,
    'verbose': True
}
</code>```

Since my input data is too big to be fully loaded into the memory, I adapt the incremental training:

```<code>xgb_clf = xgb.train(xgb_params, input_data, num_boost_round=rounds_per_batch,
                    xgb_model=model_path)
</code>```

The code for prediction is

```<code>xgb_clf = xgb.XGBClassifier()
booster = xgb.Booster()
booster.load_model(model_path)
xgb_clf._Booster = booster
raw_probas = xgb_clf.predict_proba(x)
</code>```

The result seemed good. But when I tried to invoke xgb_clf.get_xgb_params(), I got a param dict in which all params were set to default values.

I can guess that the root cause is when I initialized the model, I didn't pass any params in. So the model was initialized using the default values but when it predicted, it used an internal booster that had been fitted using some pre-defined params.

However, I wonder is there any way that, after I assign a pre-trained booster model to a XGBClassifier, I can see the real params that are used to train the booster, but not those which are used to initialize the classifier.

答:
You seem to be mixing the sklearn API with the functional API in your code, if you stick to either one you should get the parameters to persist in the pickle. Here's an example using the sklearn API.

```<code>import pickle
import numpy as np
import xgboost as xgb
from sklearn.datasets import load_digits

digits = load_digits(2)
y = digits['target']
X = digits['data']

xgb_params = {
    'objective': 'binary:logistic',
    'reg_lambda': 0.8,
    'reg_alpha': 0.4,
    'max_depth': 10,
    'max_delta_step': 1,
}
clf = xgb.XGBClassifier(**xgb_params)
clf.fit(X, y, eval_metric='auc', verbose=True)

pickle.dump(clf, open("xgb_temp.pkl", "wb"))
clf2 = pickle.load(open("xgb_temp.pkl", "rb"))

assert np.allclose(clf.predict(X), clf2.predict(X))
print(clf2.get_xgb_params())
</code>```

which produces

```<code>{'base_score': 0.5,
 'colsample_bylevel': 1,
 'colsample_bytree': 1,
 'gamma': 0,
 'learning_rate': 0.1,
 'max_delta_step': 1,
 'max_depth': 10,
 'min_child_weight': 1,
 'missing': nan,
 'n_estimators': 100,
 'objective': 'binary:logistic',
 'reg_alpha': 0.4,
 'reg_lambda': 0.8,
 'scale_pos_weight': 1,
 'seed': 0,
 'silent': 1,
 'subsample': 1}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to train a XGBoost model using the params below:

xgb_params = {
    'objective': 'binary:logistic',
    'eval_metric': 'auc',
    'lambda': 0.8,
    'alpha': 0.4,
    'max_depth': 10,
    'max_delta_step': 1,
    'verbose': True
}

Since my input data is too big to be fully loaded into the memory, I adapt the incremental training:

xgb_clf = xgb.train(xgb_params, input_data, num_boost_round=rounds_per_batch,
                    xgb_model=model_path)

The code for prediction is

xgb_clf = xgb.XGBClassifier()
booster = xgb.Booster()
booster.load_model(model_path)
xgb_clf._Booster = booster
raw_probas = xgb_clf.predict_proba(x)

The result seemed good. But when I tried to invoke xgb_clf.get_xgb_params(), I got a param dict in which all params were set to default values.

I can guess that the root cause is when I initialized the model, I didn't pass any params in. So the model was initialized using the default values but when it predicted, it used an internal booster that had been fitted using some pre-defined params.

However, I wonder is there any way that, after I assign a pre-trained booster model to a XGBClassifier, I can see the real params that are used to train the booster, but not those which are used to initialize the classifier.

Body:
You seem to be mixing the sklearn API with the functional API in your code, if you stick to either one you should get the parameters to persist in the pickle. Here's an example using the sklearn API.

import pickle
import numpy as np
import xgboost as xgb
from sklearn.datasets import load_digits

digits = load_digits(2)
y = digits['target']
X = digits['data']

xgb_params = {
    'objective': 'binary:logistic',
    'reg_lambda': 0.8,
    'reg_alpha': 0.4,
    'max_depth': 10,
    'max_delta_step': 1,
}
clf = xgb.XGBClassifier(**xgb_params)
clf.fit(X, y, eval_metric='auc', verbose=True)

pickle.dump(clf, open("xgb_temp.pkl", "wb"))
clf2 = pickle.load(open("xgb_temp.pkl", "rb"))

assert np.allclose(clf.predict(X), clf2.predict(X))
print(clf2.get_xgb_params())

which produces

{'base_score': 0.5,
 'colsample_bylevel': 1,
 'colsample_bytree': 1,
 'gamma': 0,
 'learning_rate': 0.1,
 'max_delta_step': 1,
 'max_depth': 10,
 'min_child_weight': 1,
 'missing': nan,
 'n_estimators': 100,
 'objective': 'binary:logistic',
 'reg_alpha': 0.4,
 'reg_lambda': 0.8,
 'scale_pos_weight': 1,
 'seed': 0,
 'silent': 1,
 'subsample': 1}


问:
I can not display the data from my json_encode ($.each)
Hello to every one and thank you for your time.
My problem is that i can not display the json_encode from my php database but in my chrome the data is appear.
The $.each is not dispaly all only one
enter image description here

now the code for the php :

comment.php

```<code>$data = $_REQUEST;
$photo_id =38;//$data['photo_id_comment'];
$con = mysqli_connect('localhost','root','','gallery');

$sql  = "SELECT * FROM comments";
$sql .= " WHERE photo_id = " . $database->escape_string($photo_id);
$sql .= " ORDER  BY photo_id ASC";

$result = mysqli_query( $con,$sql);

$arr = array();
$row_count = mysqli_num_rows($result);

while ($row = mysqli_fetch_array($result)) {
    array_push($arr , $row);
}

mysqli_close($con);
echo json_encode($arr);
</code>```

And the ajax to retrieve data is: script.js

```<code>function refreshComment() {

requestData = $("#photo_id_comment").serialize();
$.ajax({
    url: "http://localhost/udemy/app_php/includes/comment.php",
    type: "get",
    data: requestData,
    dataType: "text",
    success : function (data) {
        jQuery.each(data, function(index, item) {
            //now you can access properties using dot notation
            $('#chat_box').val( $('#chat_box').val() + item.body + '\n');
            /* $('#author_comment').html(item.author);
            $('#chat_box').html(item.body);*/
        });
    },
    error: function (http, status, error) {
        alert('Some error occurred :'+error);
    }
});

    return false;
}

setInterval( refreshComment , 5000 );
</code>```

And the html where the data is not display is: photo.php.

```<code> <div class="media">
                <a class="pull-left" href="#">
                    <img class="media-object" src="http://placehold.it/64x64" alt="">

                </a>
                <div class="media-body">
                    <h4 id="author_comment"  class="media-heading"></h4>
                    <p id="chat_box"></p>
                    <p class="text-info">This is post at: </p>
                </div>
            </div>
</code>```

答:
Please try this one,

```<code>$sql  = "SELECT * FROM comments WHERE photo_id = " . $database->escape_string($photo_id) ORDER  BY photo_id ASC";
$result = mysqli_query( $con,$sql);
$arr = array();
while ($row = mysqli_fetch_array($result)){
    $arr[] = $row;
}
echo json_encode($arr);
</code>```

and change ,

```<code>dataType:'json' instead of dataType:'text'
</code>```

in script.

Body:
Hello to every one and thank you for your time.
My problem is that i can not display the json_encode from my php database but in my chrome the data is appear.
The $.each is not dispaly all only one
enter image description here

now the code for the php :

comment.php

$data = $_REQUEST;
$photo_id =38;//$data['photo_id_comment'];
$con = mysqli_connect('localhost','root','','gallery');

$sql  = "SELECT * FROM comments";
$sql .= " WHERE photo_id = " . $database->escape_string($photo_id);
$sql .= " ORDER  BY photo_id ASC";

$result = mysqli_query( $con,$sql);

$arr = array();
$row_count = mysqli_num_rows($result);

while ($row = mysqli_fetch_array($result)) {
    array_push($arr , $row);
}

mysqli_close($con);
echo json_encode($arr);

And the ajax to retrieve data is: script.js

function refreshComment() {

requestData = $("#photo_id_comment").serialize();
$.ajax({
    url: "http://localhost/udemy/app_php/includes/comment.php",
    type: "get",
    data: requestData,
    dataType: "text",
    success : function (data) {
        jQuery.each(data, function(index, item) {
            //now you can access properties using dot notation
            $('#chat_box').val( $('#chat_box').val() + item.body + '\n');
            /* $('#author_comment').html(item.author);
            $('#chat_box').html(item.body);*/
        });
    },
    error: function (http, status, error) {
        alert('Some error occurred :'+error);
    }
});

    return false;
}

setInterval( refreshComment , 5000 );

And the html where the data is not display is: photo.php.

This is post at:

Body:
Please try this one,

$sql  = "SELECT * FROM comments WHERE photo_id = " . $database->escape_string($photo_id) ORDER  BY photo_id ASC";
$result = mysqli_query( $con,$sql);
$arr = array();
while ($row = mysqli_fetch_array($result)){
    $arr[] = $row;
}
echo json_encode($arr);

and change ,

dataType:'json' instead of dataType:'text'

in script.


问:
RequireJS `!` Syntax - What is it?
I am pretty new to JS. Here's define section of our application:

```<code>define([
   'angular',
   'underscore',
   'text!./ItemsList.html',
   'less!./ItemsList',
   ]
</code>```

What's the point of text!. and less!.? Is that some kind of pre-processing?

答:
It seems require.js module definition. This text! and less! are definitions of the module in charge of import the file. There're many modules, like json! to load specific type of files (custom module load .jsfiles usually)

Take a look at the requirejs text documentation

Title: RequireJS `!` Syntax - What is it?

Body:
I am pretty new to JS. Here's define section of our application:

define([
   'angular',
   'underscore',
   'text!./ItemsList.html',
   'less!./ItemsList',
   ]

What's the point of text!. and less!.? Is that some kind of pre-processing?


问:
Rename List item when there is the same string multiple time
I have List of names like:

```<code>var list = new List<string> {"Allan", "Michael", "Jhon", "Smith", "George", "Jhon"};
</code>```

and a combobox which itemssource is my list. As you can see in the list there is Jhon 2 times, what I want is when I put those name into combobox add "2" to second Jhon. I mean when I open the combobox names in it shoud look like:

```<code>Allan
Michael
Jhon
Smith
George
Jhon2
</code>```

I have tired linq to do that but I'm quite new to c#/linq. Could someone show me simple way to do that?

答:
Here is what I would do:

First off, separate the list into two smaller ones, one that contains all the unique names, and one that contains only duplicates:

```<code>var duplicates = myList.GroupBy(s => s)
    .SelectMany(grp => grp.Skip(1));

var unique = new HashSet<string>(myList).ToList();
</code>```

Then process:

```<code>var result = new List<string>();
foreach (string uniqueName in unique)
{
    int index=2;
    foreach (string duplicateName in duplicates.Where(dupe => dupe == uniqueName))
    {
        result.Add(string.Format("{0}{1}", duplicateName, index.ToString()));
        index++;
    }
}
</code>```

What we are doing here is the following:

Iterate through unique names.

Initialize a variable index with value 2. This will be the number we add at the end of each name.

Iterate through matching duplicate names.

Modify the name string by adding the number stored at index to the end.

Add this new value to the results list.

Increment index.

Finally, add the unique names back in:

```<code>result.AddRange(unique);
</code>```

The result list should now contain all the same values as the original myList, only difference being that all names that appear more than once have a number appended to their end. Per your specification, there is no name name1. Instead, counting starts from 2.

Body:
I have List of names like:

var list = new List<string> {"Allan", "Michael", "Jhon", "Smith", "George", "Jhon"};

and a combobox which itemssource is my list. As you can see in the list there is Jhon 2 times, what I want is when I put those name into combobox add "2" to second Jhon. I mean when I open the combobox names in it shoud look like:

Allan
Michael
Jhon
Smith
George
Jhon2

I have tired linq to do that but I'm quite new to c#/linq. Could someone show me simple way to do that?

Body:
Here is what I would do:

First off, separate the list into two smaller ones, one that contains all the unique names, and one that contains only duplicates:

var duplicates = myList.GroupBy(s => s)
    .SelectMany(grp => grp.Skip(1));

var unique = new HashSet<string>(myList).ToList();

Then process:

var result = new List<string>();
foreach (string uniqueName in unique)
{
    int index=2;
    foreach (string duplicateName in duplicates.Where(dupe => dupe == uniqueName))
    {
        result.Add(string.Format("{0}{1}", duplicateName, index.ToString()));
        index++;
    }
}

What we are doing here is the following:

Iterate through unique names.

Initialize a variable index with value 2. This will be the number we add at the end of each name.

Iterate through matching duplicate names.

Modify the name string by adding the number stored at index to the end.

Add this new value to the results list.

Increment index.

Finally, add the unique names back in:

result.AddRange(unique);

The result list should now contain all the same values as the original myList, only difference being that all names that appear more than once have a number appended to their end. Per your specification, there is no name name1. Instead, counting starts from 2.


问:
Securing communication on a portable intranet (changing IP addresses)
I have the following scenario:

A network will be set up on a Windows infrastructure

A website will be put on that network - It is not given a domain name and is not available on the internet. It will be addressed only via an internally recognised IP address.

A piece of software within that network will communicate with the website
(we want to avoid the 'Could not establish trust relationship issue' found with self-signed certificates without reducing security as, I believe, the accepted answer does).

The website will also be viewed on tablets and PCs.

After a few days, the service will be be put on a different network (with different IPs).

It will installed on many PCs/Networks.

I want to secure this via SSL, but it seems tricky following the 2015 update that disallowed IP addresses to have certificates.

This post suggests going via a public IP, but the solution may be completely offline in an area without internet access.

I've spent hours researching, but seem to be missing something.

How should this be done please?

答:
I would setup a DNS server with an app.local domain that gets issued the certificate.

Even if you serve up the intermediate certificates in the TLS handshake (which you should ALWAYS do and not rely on AIA), verifying the chain becomes problematic without Internet access as browsers won't be able to reach the CRL URL (Certificate Revocation List). That is, of course, unless we're talking about your own CA (living in the same network) that issues the site certificate.

If everything you describe runs in a well guarded sandbox then you probably don't need the TLS layer at all, ask yourself WHO is the attacker and WHAT are you protecting.