问:
AWS Lambda Function in java
I need to create a sample lambda function in AWS that is capable on starting or stopping a EC2 instance on call. The first thing that I tried was to create a jar from the project using the following pom

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>Ec2Ops</groupId>
<artifactId>Ec2Ops</artifactId>
<version>0.0.1</version>
<name>Ec2Ops</name>
<description>Application to perform EC2Operations</description>
<dependencies>
    <dependency>
        <groupId>com.amazonaws</groupId>
        <artifactId>aws-java-sdk</artifactId>
        <version>1.11.136</version>
    </dependency>
    <dependency>
        <groupId>com.amazonaws</groupId>
        <artifactId>aws-lambda-java-core</artifactId>
        <version>1.1.0</version>
    </dependency>
</dependencies>
<build>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.1</version>
            <configuration>
                <source>1.7</source>
                <target>1.7</target>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <version>3.0.1</version>
            <executions>
                <execution>
                    <id>copy-dependencies</id>
                    <phase>package</phase>
                    <goals>
                        <goal>copy-dependencies</goal>
                    </goals>
                    <configuration>
                        <!-- configure the plugin here -->
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>
</code>```

I uploaded the jar file I got using this pom into my lambda function; there I'm getting the following error in return

```<code>{
  "errorMessage": "com/amazonaws/services/ec2/AmazonEC2",
  "errorType": "java.lang.NoClassDefFoundError",
  "stackTrace": [
    "com.ec2ops.handler.Ec2OpsHandler.handleRequest(Ec2OpsHandler.java:14)",
    "com.ec2ops.handler.Ec2OpsHandler.handleRequest(Ec2OpsHandler.java:9)"
  ],
  "cause": {
     "errorMessage": "com.amazonaws.services.ec2.AmazonEC2",
     "errorType": "java.lang.ClassNotFoundException",
       "stackTrace": [
       "java.net.URLClassLoader.findClass(URLClassLoader.java:381)",
       "java.lang.ClassLoader.loadClass(ClassLoader.java:424)",
       "java.lang.ClassLoader.loadClass(ClassLoader.java:357)",
        "com.ec2ops.handler.Ec2OpsHandler.handleRequest(Ec2OpsHandler.java:14)",
       "com.ec2ops.handler.Ec2OpsHandler.handleRequest(Ec2OpsHandler.java:9)"
     ]
  }
}
</code>```

Please note I'm using AWS Java SDK to manipulate the instance. I understood from the error that the library is not available; so I tried to include the library also into the jar by using the shade plugin.

```<code><plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-shade-plugin</artifactId>
    <version>2.3</version>
    <configuration>
        <createDependencyReducedPom>false</createDependencyReducedPom>
    </configuration>
    <executions>
        <execution>
            <phase>package</phase>
            <goals>
                <goal>shade</goal>
            </goals>
        </execution>
    </executions>
</plugin>
</code>```

When I'm doing this that size of the jar file is more than 50MB, hence I cannot upload this into the jar file. The code I'm using for the EC2 operation is given below.

```<code>public boolean startInstance(String instanceId) {
    AmazonEC2 ec2 = new AmazonEC2Client();
    StartInstancesRequest startInstanceRequest = new StartInstancesRequest()
            .withInstanceIds(instanceId);
    StartInstancesResult instancesResult = ec2
            .startInstances(startInstanceRequest);

    List<InstanceStateChange> stateChangeList = instancesResult
            .getStartingInstances();

    return checkStateOfInstance(stateChangeList, 16, instanceId) || checkStateOfInstance(stateChangeList, 80, instanceId);
}
</code>```

Can someone tell what I'm doing wrong here.

答:
I have sucessfully found out how to get this lambda function to work. This is for anyone who is looking for an answer in regards to implementation of AWS services related operations in AWS lambda. There is very little documentation on this.

Since the AWS SDK is too large it is not possible for lambda to accommodate jar when this is included. So what we can do is just include that package that is needed; considering the question, the only SDK library I need reference to is EC2 hence I added the dependency to my pom only for EC2 as given below.

```<code><!-- https://mvnrepository.com/artifact/com.amazonaws/aws-java-sdk-ec2 -->
<dependency>
    <groupId>com.amazonaws</groupId>
    <artifactId>aws-java-sdk-ec2</artifactId>
    <version>1.9.0</version>
</dependency>
</code>```

Title: AWS Lambda Function in java

Body:
I need to create a sample lambda function in AWS that is capable on starting or stopping a EC2 instance on call. The first thing that I tried was to create a jar from the project using the following pom

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>Ec2Ops</groupId>
<artifactId>Ec2Ops</artifactId>
<version>0.0.1</version>
<name>Ec2Ops</name>
<description>Application to perform EC2Operations</description>
<dependencies>
    <dependency>
        <groupId>com.amazonaws</groupId>
        <artifactId>aws-java-sdk</artifactId>
        <version>1.11.136</version>
    </dependency>
    <dependency>
        <groupId>com.amazonaws</groupId>
        <artifactId>aws-lambda-java-core</artifactId>
        <version>1.1.0</version>
    </dependency>
</dependencies>
<build>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.1</version>
            <configuration>
                <source>1.7</source>
                <target>1.7</target>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <version>3.0.1</version>
            <executions>
                <execution>
                    <id>copy-dependencies</id>
                    <phase>package</phase>
                    <goals>
                        <goal>copy-dependencies</goal>
                    </goals>
                    <configuration>

                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

I uploaded the jar file I got using this pom into my lambda function; there I'm getting the following error in return

{
  "errorMessage": "com/amazonaws/services/ec2/AmazonEC2",
  "errorType": "java.lang.NoClassDefFoundError",
  "stackTrace": [
    "com.ec2ops.handler.Ec2OpsHandler.handleRequest(Ec2OpsHandler.java:14)",
    "com.ec2ops.handler.Ec2OpsHandler.handleRequest(Ec2OpsHandler.java:9)"
  ],
  "cause": {
     "errorMessage": "com.amazonaws.services.ec2.AmazonEC2",
     "errorType": "java.lang.ClassNotFoundException",
       "stackTrace": [
       "java.net.URLClassLoader.findClass(URLClassLoader.java:381)",
       "java.lang.ClassLoader.loadClass(ClassLoader.java:424)",
       "java.lang.ClassLoader.loadClass(ClassLoader.java:357)",
        "com.ec2ops.handler.Ec2OpsHandler.handleRequest(Ec2OpsHandler.java:14)",
       "com.ec2ops.handler.Ec2OpsHandler.handleRequest(Ec2OpsHandler.java:9)"
     ]
  }
}

Please note I'm using AWS Java SDK to manipulate the instance. I understood from the error that the library is not available; so I tried to include the library also into the jar by using the shade plugin.

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-shade-plugin</artifactId>
    <version>2.3</version>
    <configuration>
        <createDependencyReducedPom>false</createDependencyReducedPom>
    </configuration>
    <executions>
        <execution>
            <phase>package</phase>
            <goals>
                <goal>shade</goal>
            </goals>
        </execution>
    </executions>
</plugin>

When I'm doing this that size of the jar file is more than 50MB, hence I cannot upload this into the jar file. The code I'm using for the EC2 operation is given below.

public boolean startInstance(String instanceId) {
    AmazonEC2 ec2 = new AmazonEC2Client();
    StartInstancesRequest startInstanceRequest = new StartInstancesRequest()
            .withInstanceIds(instanceId);
    StartInstancesResult instancesResult = ec2
            .startInstances(startInstanceRequest);

    List<InstanceStateChange> stateChangeList = instancesResult
            .getStartingInstances();

    return checkStateOfInstance(stateChangeList, 16, instanceId) || checkStateOfInstance(stateChangeList, 80, instanceId);
}

Can someone tell what I'm doing wrong here.

Body:
I have sucessfully found out how to get this lambda function to work. This is for anyone who is looking for an answer in regards to implementation of AWS services related operations in AWS lambda. There is very little documentation on this.

Since the AWS SDK is too large it is not possible for lambda to accommodate jar when this is included. So what we can do is just include that package that is needed; considering the question, the only SDK library I need reference to is EC2 hence I added the dependency to my pom only for EC2 as given below.

<!-- https://mvnrepository.com/artifact/com.amazonaws/aws-java-sdk-ec2 -->
<dependency>
    <groupId>com.amazonaws</groupId>
    <artifactId>aws-java-sdk-ec2</artifactId>
    <version>1.9.0</version>
</dependency>


来源: stackexchange

问:
Cannot open SCTP Socket
I want to open a basic socket by the below code:

```<code>SOCKET  s;
s=socket(AF_INET, SOCK_STREAM, IPPROTO_SCTP);
if(s==INVALID_SOCKET || s == SOCKET_ERROR) {
        printf("%d", errno);
        closesocket(s);
        return SOCKET_INIT_FAILED;
}
</code>```

The errno it returns: 93.

kernel Version: 2.6.18-238.el5
Cent OS: 5.7

答: I think you should install lksctp, the error 93 is "Protocol not supported"</p>

ContentLicense: CC BY-SA 3.0

Title: Cannot open SCTP Socket

Body:
I want to open a basic socket by the below code:

SOCKET  s;
s=socket(AF_INET, SOCK_STREAM, IPPROTO_SCTP);
if(s==INVALID_SOCKET || s == SOCKET_ERROR) {
        printf("%d", errno);
        closesocket(s);
        return SOCKET_INIT_FAILED;
}

The errno it returns: 93.

kernel Version: 2.6.18-238.el5
Cent OS: 5.7


问:
How to delete duplicate lines in a file without sorting it in Unix
Is there a way to delete duplicate lines in a file in Unix?

I can do it with sort -u and uniq commands, but I want to use sed or awk.

Is that possible?

答:
The first solution is also from http://sed.sourceforge.net/sed1line.txt

```<code>$ echo -e '1\n2\n2\n3\n3\n3\n4\n4\n4\n4\n5' |sed -nr '$!N;/^(.*)\n\1$/!P;D'
1
2
3
4
5
</code>```

The core idea is:

Print only once of each duplicate consecutive lines at its last appearance and use the D command to implement the loop.

Explanation:

$!N;: if the current line is not the last line, use the N command to read the next line into the pattern space.

/^(.*)\n\1$/!P: if the contents of the current pattern space is two duplicate strings separated by \n, which means the next line is the same with current line, we can not print it according to our core idea; otherwise, which means the current line is the last appearance of all of its duplicate consecutive lines. We can now use the P command to print the characters in the current pattern space until \n (\n also printed).

D: we use the D command to delete the characters in the current pattern space until \n (\n also deleted), and then the content of pattern space is the next line.

and the D command will force sed to jump to its first command $!N, but not read the next line from a file or standard input stream.

The second solution is easy to understand (from myself):

```<code>$ echo -e '1\n2\n2\n3\n3\n3\n4\n4\n4\n4\n5' |sed -nr 'p;:loop;$!N;s/^(.*)\n\1$/\1/;tloop;D'
1
2
3
4
5
</code>```

The core idea is:

print only once of each duplicate consecutive lines at its first appearance and use the : command and t command to implement LOOP.

Explanation:

read a new line from the input stream or file and print it once.

use the :loop command to set a label named loop.

use N to read the next line into the pattern space.

use s/^(.*)\n\1$/\1/ to delete the current line if the next line is the same with the current line. We use the s command to do the delete action.

if the s command is executed successfully, then use the tloop command to force sed to jump to the label named loop, which will do the same loop to the next lines until there are no duplicate consecutive lines of the line which is latest printed; otherwise, use the D command to delete the line which is the same with the latest-printed line, and force sed to jump to the first command, which is the p command. The content of the current pattern space is the next new line.

ContentLicense: CC BY-SA 4.0

Body:
The first solution is also from http://sed.sourceforge.net/sed1line.txt

$ echo -e '1\n2\n2\n3\n3\n3\n4\n4\n4\n4\n5' |sed -nr '$!N;/^(.*)\n\1$/!P;D'
1
2
3
4
5

The core idea is:

Print only once of each duplicate consecutive lines at its last appearance and use the D command to implement the loop.

Explanation:

$!N;: if the current line is not the last line, use the N command to read the next line into the pattern space.

/^(.*)\n\1$/!P: if the contents of the current pattern space is two duplicate strings separated by \n, which means the next line is the same with current line, we can not print it according to our core idea; otherwise, which means the current line is the last appearance of all of its duplicate consecutive lines. We can now use the P command to print the characters in the current pattern space until \n (\n also printed).

D: we use the D command to delete the characters in the current pattern space until \n (\n also deleted), and then the content of pattern space is the next line.

and the D command will force sed to jump to its first command $!N, but not read the next line from a file or standard input stream.

The second solution is easy to understand (from myself):

$ echo -e '1\n2\n2\n3\n3\n3\n4\n4\n4\n4\n5' |sed -nr 'p;:loop;$!N;s/^(.*)\n\1$/\1/;tloop;D'
1
2
3
4
5

The core idea is:

print only once of each duplicate consecutive lines at its first appearance and use the : command and t command to implement LOOP.

Explanation:

read a new line from the input stream or file and print it once.

use the :loop command to set a label named loop.

use N to read the next line into the pattern space.

use s/^(.*)\n\1$/\1/ to delete the current line if the next line is the same with the current line. We use the s command to do the delete action.

if the s command is executed successfully, then use the tloop command to force sed to jump to the label named loop, which will do the same loop to the next lines until there are no duplicate consecutive lines of the line which is latest printed; otherwise, use the D command to delete the line which is the same with the latest-printed line, and force sed to jump to the first command, which is the p command. The content of the current pattern space is the next new line.


问:
How to detect text overflow in contenteditable
I am trying to detect text overflow in contenteditable div, so that when text enter after the div width(800px), it will alert about the overflow. I am trying below code.

HTML

var e = document.getElementById('test');
if (e.offsetWidth < e.scrollWidth) {
  alert("Overflow");
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#test{
  max-width: 800px;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow:hidden;
  font-size: 76px;
}</code>```

Click here..

    ```

答:
Try the below one:

$(document).ready(function(){
  $('.content').on('input',function(){
    var e = document.getElementById('test');
     $.fn.textWidth = function() {
      var htmlCalc = $('' + this.html() + '');
       htmlCalc.css('font-size', this.css('font-size'))
      .hide()
      .prependTo('body');
      var width = htmlCalc.width();
      htmlCalc.remove();
      return width;
    };
    if ($('#test').textWidth() > $('#test').width()) {
      alert("Overflow");
    }
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#test{
  max-width: 800px;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow:hidden;
  font-size: 76px;
}</code>```

Click here..

```

.textwidth() function has taken from here

Body:
I am trying to detect text overflow in contenteditable div, so that when text enter after the div width(800px), it will alert about the overflow. I am trying below code.

HTML

var e = document.getElementById('test');
if (e.offsetWidth < e.scrollWidth) {
  alert("Overflow");
}

#test{
  max-width: 800px;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow:hidden;
  font-size: 76px;
}

Click here..

Body:
Try the below one:

$(document).ready(function(){
  $('.content').on('input',function(){
    var e = document.getElementById('test');
     $.fn.textWidth = function() {
      var htmlCalc = $('<span>' + this.html() + '</span>');
       htmlCalc.css('font-size', this.css('font-size'))
      .hide()
      .prependTo('body');
      var width = htmlCalc.width();
      htmlCalc.remove();
      return width;
    };
    if ($('#test').textWidth() > $('#test').width()) {
      alert("Overflow");
    }
  });
});

#test{
  max-width: 800px;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow:hidden;
  font-size: 76px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="content" contenteditable="true">
  <div id="test">Click here..</div>
</div>

.textwidth() function has taken from here


问:
Build tuple from heterogeneous initializer list at function call
Consider the following function

```<code>template <class... T, class... U>
void f(std::tuple<T...> t, std::tuple<U...> u)
{
    std::cout << sizeof...(T) << " " << sizeof...(U) << std::endl;
}

int main(int argc, char* argv[])
{
    f({3, 3.5, "Hello World!"}, {'a', std::string("b")}); // Fails
    return 0;
}
</code>```

Would there be any way in C++17 to modify the function signature so that the line marked "Fails" would work? (keeping that line the same).

答:
My guess is that the short answer is no.

Roughly speaking, { args... } isn't a tuple and you incur in the same deduction and conversion issues you were facing in C++14.

That being said, in C++14/17 you can do this to simulate it (minimal, working example):

```<code>#include<iostream>
#include<string>
#include<tuple>
#include<utility>

template <class... T, class... U>
void f_(std::tuple<T...> t, std::tuple<U...> u) {
    std::cout << sizeof...(T) << " " << sizeof...(U) << std::endl;
}

template<typename... T>
auto f(T... t) {
    return [tup{std::make_tuple(t...)}](auto... u) {
        f_(std::move(tup), std::make_tuple(u...));
    };
}

int main(int argc, char* argv[]) {
    f(3, 3.5, "Hello World!")('a', std::string("b"));
    return 0;
}
</code>```

Generic lambdas do the magic for you and you have something similar to what you want with an extra level of indirection (that usually helps to solve any problem).

In C++17 you can also do this:

```<code>f(std::tuple{3, 3.5, "Hello World!"}, std::tuple{'a', std::string("b")});
</code>```

That is having types of arguments deduced directly from the call to the constructor instead of explicitly specifying them. With an alias you can even go further and reduce the expressions at the call point to something like this:

```<code>f(T{3, 3.5, "Hello World!"}, T{'a', std::string("b")});
</code>```

Anyway you sacrifice readability for that and it doesn't worth it from my point of view.

Body:
Consider the following function

template <class... T, class... U>
void f(std::tuple<T...> t, std::tuple u)
{
    std::cout << sizeof...(T) << " " << sizeof...(U) << std::endl;
}

int main(int argc, char* argv[])
{
    f({3, 3.5, "Hello World!"}, {'a', std::string("b")}); // Fails
    return 0;
}

Would there be any way in C++17 to modify the function signature so that the line marked "Fails" would work? (keeping that line the same).

Body:
My guess is that the short answer is no.

Roughly speaking, { args... } isn't a tuple and you incur in the same deduction and conversion issues you were facing in C++14.

That being said, in C++14/17 you can do this to simulate it (minimal, working example):

#include<iostream>
#include<string>
#include<tuple>
#include<utility>

template <class... T, class... U>
void f_(std::tuple<T...> t, std::tuple<U...> u) {
    std::cout << sizeof...(T) << " " << sizeof...(U) << std::endl;
}

template<typename... T>
auto f(T... t) {
    return [tup{std::make_tuple(t...)}](auto... u) {
        f_(std::move(tup), std::make_tuple(u...));
    };
}

int main(int argc, char* argv[]) {
    f(3, 3.5, "Hello World!")('a', std::string("b"));
    return 0;
}

Generic lambdas do the magic for you and you have something similar to what you want with an extra level of indirection (that usually helps to solve any problem).

In C++17 you can also do this:

f(std::tuple{3, 3.5, "Hello World!"}, std::tuple{'a', std::string("b")});

That is having types of arguments deduced directly from the call to the constructor instead of explicitly specifying them. With an alias you can even go further and reduce the expressions at the call point to something like this:

f(T{3, 3.5, "Hello World!"}, T{'a', std::string("b")});

Anyway you sacrifice readability for that and it doesn't worth it from my point of view.


问:
How do I change NA into Column median
A data frame contains 123 columns,
and each columns have at least 1 NA value.

I want these NA values to be raplaced into column median.
because there are so many columns, i cannot write a code using each column name.

so i tried to use 'apply' to solve this but it didn't work.

```<code>data2[-1]<-lapply(data2[-1],function(x)x - median(x,na.rm=TRUE))
</code>```

it says it doesn't work since it is data frame, not numeric.

答:
We can use map2_df

```<code>library(purrr)
df <- data.frame(a = c(1, 2, 3), b = c(2, NA, 9), c = c(NA, 3, 5), d = c(0, 4, NA))
purrr::map2_df(df, purrr::dmap(df, median, na.rm = TRUE), function(x, y) ifelse(is.na(x), y, x))
</code>```

Title: How do I change NA into Column median

Body:
A data frame contains 123 columns,
and each columns have at least 1 NA value.

I want these NA values to be raplaced into column median.
because there are so many columns, i cannot write a code using each column name.

so i tried to use 'apply' to solve this but it didn't work.

data2[-1]<-lapply(data2[-1],function(x)x - median(x,na.rm=TRUE))

it says it doesn't work since it is data frame, not numeric.

Body:
We can use map2_df

library(purrr)
df <- data.frame(a = c(1, 2, 3), b = c(2, NA, 9), c = c(NA, 3, 5), d = c(0, 4, NA))
purrr::map2_df(df, purrr::dmap(df, median, na.rm = TRUE), function(x, y) ifelse(is.na(x), y, x))


问:
PHP: Manipulating existing array
I have an existing array $cars[]. Here's how I created the array $cars[]

```<code>$cars = array("1" => "Toyota",
              "5" => "BMW",
              "7" => "Volvo",
              "32"=> "Porsche" );
</code>```

As you can see, the indices of the array $cars[] is not in order. What I need to do is insert an array element in the array $cars[] when needed, to make it in order. I need to make the array $cars[] like this:

```<code>$cars = array("1" => "Toyota",
              "2"=> "NULL",
              "3"=> "NULL",
              "4"=> "NULL",
              "5" => "BMW",
              "6"=> "NULL",
              "7" => "Volvo",
              "8"=> "NULL",
               .
               .
               .
              "31"=> "NULL",
              "32"=> "Porsche"
               .
               .
               .
              "48"=> "NULL"  );
</code>```

A total of 48 cars. Thank you guys!

答:
You can sort array by keys try this</p>

```<code>ksort($cars);
</code>```

Title: PHP: Manipulating existing array

Body:
I have an existing array $cars[]. Here's how I created the array $cars[]

$cars = array("1" => "Toyota",
              "5" => "BMW",
              "7" => "Volvo",
              "32"=> "Porsche" );

As you can see, the indices of the array $cars[] is not in order. What I need to do is insert an array element in the array $cars[] when needed, to make it in order. I need to make the array $cars[] like this:

$cars = array("1" => "Toyota",
              "2"=> "NULL",
              "3"=> "NULL",
              "4"=> "NULL",
              "5" => "BMW",
              "6"=> "NULL",
              "7" => "Volvo",
              "8"=> "NULL",
               .
               .
               .
              "31"=> "NULL",
              "32"=> "Porsche"
               .
               .
               .
              "48"=> "NULL"  );

A total of 48 cars. Thank you guys!

Body:
You can sort array by keys try this

ksort($cars);


问:
What language apart from JavaScript can you execute in a browser
Are there other languages apart from javascript that browsers can interpret and execute. I'm happy for browser specific ones as well.

Any answers welcomed

答:
VBScript in Internet Explorer, but nobody uses that. At least in the past (and maybe still), any Windows Script Host language would be executed by Internet Explorer.

As far as other web browsers... nothin' but Javascript, as far as I know.

ContentLicense: CC BY-SA 2.5


问:
Initializing element's value on loading new fxml file
I'm trying to set a TextField's value when the respective FXML file is loaded, but when I tried to set a default value on the TextField in the method where the FXML is loaded, in this case in the writeBtnClick() method, it throws a NullPointerException.

To my understanding, an element is not initialized until the FXML is loaded, so for whatever reason after loading the FXML file, the element is still not recognized.

Controller.java

```<code>public class Controller implements Initializable {
    @FXML private TextField textField;

    public void initialize(URL arg0, ResourceBundle arg1) {

    }

    public void writeBtnClick(ActionEvent event) throws IOException {
        Stage stage = (Stage) ((Node)event.getSource()).getScene().getWindow();
        stage.setScene(new Scene((Parent) FXMLLoader.load(getClass().getResource("WriteScene.fxml"))));

        // the textfield I'm trying to set default value on
        // this throws a NullPointerException
        textField.setText("name");
    }
</code>```

To circumvent this problem I put the setText() in initialize() but of course that would also result in NullPointerException if the controller class gets called before loading the correct fxml file.

This is the best way I could come up with but obviously it's very dirty and I feel like there should be a way to set the value on the writeBtnClick() method where the scene actually gets loaded.

```<code>public void initialize(URL arg0, ResourceBundle arg1) {
    // very hacky solution
    if (textField != null) {
        textField.setText("name");
    }
}
</code>```

答:
I know it can sound crazy, but remove implements Initializable from your controller definition, but leave initialize method. Ther will be no NPE anymore.

In case you will still get some NPE on GUI element, double check @fx:id tags, as there is most probably a typo (case sensitive), and inflator will not complain about it.

Body:
I'm trying to set a TextField's value when the respective FXML file is loaded, but when I tried to set a default value on the TextField in the method where the FXML is loaded, in this case in the writeBtnClick() method, it throws a NullPointerException.

To my understanding, an element is not initialized until the FXML is loaded, so for whatever reason after loading the FXML file, the element is still not recognized.

Controller.java

public class Controller implements Initializable {
    @FXML private TextField textField;

    public void initialize(URL arg0, ResourceBundle arg1) {

    }

    public void writeBtnClick(ActionEvent event) throws IOException {
        Stage stage = (Stage) ((Node)event.getSource()).getScene().getWindow();
        stage.setScene(new Scene((Parent) FXMLLoader.load(getClass().getResource("WriteScene.fxml"))));

        // the textfield I'm trying to set default value on
        // this throws a NullPointerException
        textField.setText("name");
    }

To circumvent this problem I put the setText() in initialize() but of course that would also result in NullPointerException if the controller class gets called before loading the correct fxml file.

This is the best way I could come up with but obviously it's very dirty and I feel like there should be a way to set the value on the writeBtnClick() method where the scene actually gets loaded.

public void initialize(URL arg0, ResourceBundle arg1) {
    // very hacky solution
    if (textField != null) {
        textField.setText("name");
    }
}


问:
On Back press traversing through last two tabs not working properly in BottomNavigationView?
On click of back button, navigate to the previous tab that was opened. You will exit the app only by traversing through last two tabs you have opened.how to achieve it

I just want to traverse all the tabs that I have opened and then app should exit

Here is the layout:

```<code> <?xml version="1.0" encoding="utf-8"?>
            <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:tools="http://schemas.android.com/tools"
                xmlns:design="http://schemas.android.com/apk/res-auto"
                android:id="@+id/activity_main"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                tools:context="com.segunfamisa.sample.bottomnav.MainActivity">

                <FrameLayout
                    android:id="@+id/container"
                    android:layout_width="match_parent"
                    android:layout_height="0dp"
                    android:layout_weight="1"
                    android:background="#f1f1f1">

                </FrameLayout>

                <android.support.design.widget.BottomNavigationView
                    android:id="@+id/navigation"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity="start"
                    design:menu="@menu/bottom_nav_items" />
            </LinearLayout>
</code>```

Here is the activity:

```<code>public class MainActivity extends AppCompatActivity {
    private static final String SELECTED_ITEM = "arg_selected_item";

    private BottomNavigationView mBottomNav;
    private int mSelectedItem;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mBottomNav = (BottomNavigationView) findViewById(R.id.navigation);
        mBottomNav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                selectFragment(item);
                return true;
            }
        });

        MenuItem selectedItem;
        if (savedInstanceState != null) {
            mSelectedItem = savedInstanceState.getInt(SELECTED_ITEM, 0);
            selectedItem = mBottomNav.getMenu().findItem(mSelectedItem);
        } else
        {
            selectedItem = mBottomNav.getMenu().getItem(0);
        }

        selectFragment(selectedItem);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putInt(SELECTED_ITEM, mSelectedItem);
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onBackPressed() {

        MenuItem homeItem = mBottomNav.getMenu().getItem(0);

        if (mSelectedItem != homeItem.getItemId()) {

            selectFragment(homeItem);
            // Select home item
            mBottomNav.setSelectedItemId(homeItem.getItemId());

        } else {
            super.onBackPressed();
        }
    }

    private void selectFragment(MenuItem item) {
        Fragment frag = null;
        item.setCheckable(true);
        // init corresponding fragment
        switch (item.getItemId()) {
            case R.id.menu_home:

                TabFragmentOne fragmentone = new TabFragmentOne();
                FragmentTransaction ft =  getSupportFragmentManager().beginTransaction();
                ft.replace(R.id.container, fragmentone);
                ft.commit();

                break;
            case R.id.menu_notifications:

                TabFragmentThree fragmentone_Three = new TabFragmentThree();
                FragmentTransaction ft_three =  getSupportFragmentManager().beginTransaction();
                ft_three.replace(R.id.container, fragmentone_Three);
                ft_three.commit();

                break;
            case R.id.menu_search:

                TabFragmentTwo tabFragmentTwo = new TabFragmentTwo();
                FragmentTransaction ft_two =  getSupportFragmentManager().beginTransaction();
                ft_two.replace(R.id.container,tabFragmentTwo);
                ft_two.commit();

                break;
        }

        // update selected item
        mSelectedItem = item.getItemId();

        updateToolbarText(item.getTitle());

        if (frag != null) {
            TabFragmentOne fragmentone = new TabFragmentOne();
            FragmentTransaction ft =  getSupportFragmentManager().beginTransaction();
            ft.replace(R.id.container, fragmentone);
            ft.commit();
        }
    }

    private void updateToolbarText(CharSequence text) {
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setTitle(text);
        }
    }
</code>```

Please help me any one...

答:
Update onBackPressed() as below:

```<code>@Override
public void onBackPressed() {

    if (mSelectedItem == R.id.menu_notifications) {

        MenuItem searchItem = mBottomNav.getMenu().getItem(1);
        selectFragment(searchItem);
        mBottomNav.setSelectedItemId(searchItem.getItemId());

    } else if (mSelectedItem == R.id.menu_search) {

        MenuItem homeItem = mBottomNav.getMenu().getItem(0);
        selectFragment(homeItem);
        mBottomNav.setSelectedItemId(homeItem.getItemId());

    } else {
        super.onBackPressed();
    }
}
</code>```

UPDATE:

Try to add all fragment transaction to the back stack and pop when back pressed:

Try this:

```<code>public class MainActivity extends AppCompatActivity {
    private static final String SELECTED_ITEM = "arg_selected_item";

    private BottomNavigationView mBottomNav;
    private int mSelectedItem;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mBottomNav = (BottomNavigationView) findViewById(R.id.navigation);
        mBottomNav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                selectFragment(item);
                return true;
            }
        });

        MenuItem selectedItem;
        if (savedInstanceState != null) {
            mSelectedItem = savedInstanceState.getInt(SELECTED_ITEM, 0);
            selectedItem = mBottomNav.getMenu().findItem(mSelectedItem);
        } else {
            selectedItem = mBottomNav.getMenu().getItem(0);
        }

        selectFragment(selectedItem);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putInt(SELECTED_ITEM, mSelectedItem);
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onBackPressed() {

        FragmentManager fragmentManager = getSupportFragmentManager();

        if (fragmentManager.getBackStackEntryCount() > 1) {
            fragmentManager.popBackStackImmediate();
        } else  {
            super.onBackPressed();
        }
    }

    private void selectFragment(MenuItem item) {

        Fragment frag = null;
        item.setCheckable(true);
        switch (item.getItemId()) {
            case R.id.menu_home:

                TabFragmentOne fragmentone = new TabFragmentOne();
                FragmentTransaction ft =  getSupportFragmentManager().beginTransaction();
                ft.replace(R.id.container, fragmentone);
                ft.addToBackStack(null);
                ft.commit();

                break;
            case R.id.menu_notifications:

                TabFragmentThree fragmentone_Three = new TabFragmentThree();
                FragmentTransaction ft_three =  getSupportFragmentManager().beginTransaction();
                ft_three.replace(R.id.container, fragmentone_Three);
                ft_three.addToBackStack(null);
                ft_three.commit();

                break;
            case R.id.menu_search:

                TabFragmentTwo tabFragmentTwo = new TabFragmentTwo();
                FragmentTransaction ft_two =  getSupportFragmentManager().beginTransaction();
                ft_two.replace(R.id.container,tabFragmentTwo);
                ft_two.addToBackStack(null);
                ft_two.commit();

                break;
        }

        // update selected item
        mSelectedItem = item.getItemId();

        updateToolbarText(item.getTitle());

        if (frag != null) {
            TabFragmentOne fragmentone = new TabFragmentOne();
            FragmentTransaction ft =  getSupportFragmentManager().beginTransaction();
            ft.replace(R.id.container, fragmentone);
            ft.commit();
        }
    }

    private void updateToolbarText(CharSequence text) {
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setTitle(text);
        }
    }
}
</code>```

Body:
On click of back button, navigate to the previous tab that was opened. You will exit the app only by traversing through last two tabs you have opened.how to achieve it

I just want to traverse all the tabs that I have opened and then app should exit

Here is the layout:

 <?xml version="1.0" encoding="utf-8"?>
            <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:tools="http://schemas.android.com/tools"
                xmlns:design="http://schemas.android.com/apk/res-auto"
                android:id="@+id/activity_main"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                tools:context="com.segunfamisa.sample.bottomnav.MainActivity">

                <FrameLayout
                    android:id="@+id/container"
                    android:layout_width="match_parent"
                    android:layout_height="0dp"
                    android:layout_weight="1"
                    android:background="#f1f1f1">

                </FrameLayout>

                <android.support.design.widget.BottomNavigationView
                    android:id="@+id/navigation"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity="start"
                    design:menu="@menu/bottom_nav_items" />
            </LinearLayout>

Here is the activity:

public class MainActivity extends AppCompatActivity {
    private static final String SELECTED_ITEM = "arg_selected_item";

    private BottomNavigationView mBottomNav;
    private int mSelectedItem;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mBottomNav = (BottomNavigationView) findViewById(R.id.navigation);
        mBottomNav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                selectFragment(item);
                return true;
            }
        });

        MenuItem selectedItem;
        if (savedInstanceState != null) {
            mSelectedItem = savedInstanceState.getInt(SELECTED_ITEM, 0);
            selectedItem = mBottomNav.getMenu().findItem(mSelectedItem);
        } else
        {
            selectedItem = mBottomNav.getMenu().getItem(0);
        }

        selectFragment(selectedItem);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putInt(SELECTED_ITEM, mSelectedItem);
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onBackPressed() {

        MenuItem homeItem = mBottomNav.getMenu().getItem(0);

        if (mSelectedItem != homeItem.getItemId()) {

            selectFragment(homeItem);
            // Select home item
            mBottomNav.setSelectedItemId(homeItem.getItemId());

        } else {
            super.onBackPressed();
        }
    }

    private void selectFragment(MenuItem item) {
        Fragment frag = null;
        item.setCheckable(true);
        // init corresponding fragment
        switch (item.getItemId()) {
            case R.id.menu_home:

                TabFragmentOne fragmentone = new TabFragmentOne();
                FragmentTransaction ft =  getSupportFragmentManager().beginTransaction();
                ft.replace(R.id.container, fragmentone);
                ft.commit();

                break;
            case R.id.menu_notifications:

                TabFragmentThree fragmentone_Three = new TabFragmentThree();
                FragmentTransaction ft_three =  getSupportFragmentManager().beginTransaction();
                ft_three.replace(R.id.container, fragmentone_Three);
                ft_three.commit();

                break;
            case R.id.menu_search:

                TabFragmentTwo tabFragmentTwo = new TabFragmentTwo();
                FragmentTransaction ft_two =  getSupportFragmentManager().beginTransaction();
                ft_two.replace(R.id.container,tabFragmentTwo);
                ft_two.commit();

                break;
        }

        // update selected item
        mSelectedItem = item.getItemId();

        updateToolbarText(item.getTitle());

        if (frag != null) {
            TabFragmentOne fragmentone = new TabFragmentOne();
            FragmentTransaction ft =  getSupportFragmentManager().beginTransaction();
            ft.replace(R.id.container, fragmentone);
            ft.commit();
        }
    }

    private void updateToolbarText(CharSequence text) {
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setTitle(text);
        }
    }

Please help me any one...

Body:
Update onBackPressed() as below:

@Override
public void onBackPressed() {

    if (mSelectedItem == R.id.menu_notifications) {

        MenuItem searchItem = mBottomNav.getMenu().getItem(1);
        selectFragment(searchItem);
        mBottomNav.setSelectedItemId(searchItem.getItemId());

    } else if (mSelectedItem == R.id.menu_search) {

        MenuItem homeItem = mBottomNav.getMenu().getItem(0);
        selectFragment(homeItem);
        mBottomNav.setSelectedItemId(homeItem.getItemId());

    } else {
        super.onBackPressed();
    }
}

UPDATE:

Try to add all fragment transaction to the back stack and pop when back pressed:

Try this:

public class MainActivity extends AppCompatActivity {
    private static final String SELECTED_ITEM = "arg_selected_item";

    private BottomNavigationView mBottomNav;
    private int mSelectedItem;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mBottomNav = (BottomNavigationView) findViewById(R.id.navigation);
        mBottomNav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                selectFragment(item);
                return true;
            }
        });

        MenuItem selectedItem;
        if (savedInstanceState != null) {
            mSelectedItem = savedInstanceState.getInt(SELECTED_ITEM, 0);
            selectedItem = mBottomNav.getMenu().findItem(mSelectedItem);
        } else {
            selectedItem = mBottomNav.getMenu().getItem(0);
        }

        selectFragment(selectedItem);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putInt(SELECTED_ITEM, mSelectedItem);
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onBackPressed() {

        FragmentManager fragmentManager = getSupportFragmentManager();

        if (fragmentManager.getBackStackEntryCount() > 1) {
            fragmentManager.popBackStackImmediate();
        } else  {
            super.onBackPressed();
        }
    }

    private void selectFragment(MenuItem item) {

        Fragment frag = null;
        item.setCheckable(true);
        switch (item.getItemId()) {
            case R.id.menu_home:

                TabFragmentOne fragmentone = new TabFragmentOne();
                FragmentTransaction ft =  getSupportFragmentManager().beginTransaction();
                ft.replace(R.id.container, fragmentone);
                ft.addToBackStack(null);
                ft.commit();

                break;
            case R.id.menu_notifications:

                TabFragmentThree fragmentone_Three = new TabFragmentThree();
                FragmentTransaction ft_three =  getSupportFragmentManager().beginTransaction();
                ft_three.replace(R.id.container, fragmentone_Three);
                ft_three.addToBackStack(null);
                ft_three.commit();

                break;
            case R.id.menu_search:

                TabFragmentTwo tabFragmentTwo = new TabFragmentTwo();
                FragmentTransaction ft_two =  getSupportFragmentManager().beginTransaction();
                ft_two.replace(R.id.container,tabFragmentTwo);
                ft_two.addToBackStack(null);
                ft_two.commit();

                break;
        }

        // update selected item
        mSelectedItem = item.getItemId();

        updateToolbarText(item.getTitle());

        if (frag != null) {
            TabFragmentOne fragmentone = new TabFragmentOne();
            FragmentTransaction ft =  getSupportFragmentManager().beginTransaction();
            ft.replace(R.id.container, fragmentone);
            ft.commit();
        }
    }

    private void updateToolbarText(CharSequence text) {
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setTitle(text);
        }
    }
}


问:
how to convert an object into a String?
I am getting an output as object, but I want the record to be displayed in text.

答:
You mean in the content of "#bs" and "#cost"??
Use "JSON.stringify()" you know the function, you're using it in the code

Did you mean that?

Title: how to convert an object into a String?


问:
What is a real-world use-case for JavaScript's void operator?
Why would someone write:

```<code>function () {
    if (err) {
        return void console.log(err)
    }
}
</code>```

instead of:

```<code>function () {
    if (err) {
        console.log(err)
        return
    }
}
</code>```

Has anyone used the void operator at all? I have seen it being used as in the example case above, but very very rarely.

Update

console.log might be a poor example as it returns void itself. Let me show another use I have seen in an express app:

```<code>function (req, res) {
    ...
    // Some error occurred
    if (err) {
        return void res.send(foo)
        // `send` returns a `Response` instance
    }
}
</code>```

In eslint's source code for example, it is being used quite a lot:

config-initializer.js

jshint.js - BIG FILE WARNING!

consistent-return.js

答:
The above 2 functions are doing the same thing except that the former is written in one line. void is most used in the content of hyperlinks, where the browser may interpret the results of a return and try to display the results.

In your updated code, the void is important, because the author of the function wants to do the following actions in one line.

Perform res.send(foo)

return void (nothing)

Thus he/she uses void to cast the result to undefined

Body:
Why would someone write:

function () {
    if (err) {
        return void console.log(err)
    }
}

instead of:

function () {
    if (err) {
        console.log(err)
        return
    }
}

Has anyone used the void operator at all? I have seen it being used as in the example case above, but very very rarely.

Update

console.log might be a poor example as it returns void itself. Let me show another use I have seen in an express app:

function (req, res) {
    ...
    // Some error occurred
    if (err) {
        return void res.send(foo)
        // `send` returns a `Response` instance
    }
}

In eslint's source code for example, it is being used quite a lot:

config-initializer.js

jshint.js - BIG FILE WARNING!

consistent-return.js


问:
SqlDateTime overflow exception (yyyy-mm-dd to sqldatetime)
I'm extracting a date-formatted string (yyyy-MM-dd) and then converting it to a DateTime and inserting it in the database using a storedprocedure. But I keep getting

System.Data.SqlTypes.SqlTypeException: SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.

The column in my table is of type date.

I convert my string (e.g 2016-01-15) by invoking DateTime.ParseExact(expirationDate, "yyyy-MM-dd", null) and then I take that value and insert it as a parameter into my StoredProcedure and execute the proc.

But when using the debugger I can see that the return value is actually a yyyy-MM-dd HH:mm:ss-formatted DateTime.

this is an example of how the code looks like

```<code>string expirationDate = GetDate();
DateTime date = DateTime.ParseExact(expirationDate, "yyyy-MM-dd", null);

ExecuteMyStoredProc(date);
</code>```

答:
```<code>DateTime convertedInitDate = DateTime.ParseExact(initDate, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);
      cCCBEntities.initDate = convertedInitDate;
</code>```

The code above is the code I used when I encountered this same problem that I kept on looking for like 5 hrs already. Thankfully mine got solved alright with the above code.

Notes:

I was using MVC in Visual Studio to develop a web application using sql server

cCCCBEntities is the name of my Entity I was using

This answer was the answer I got above from user326608, I just cant vote on it yet so i decided to put it on a comment here to emphasize that its what it solved my problem

Also, even though I was using SPs when saving to DB too, I didnt have to follow his recommendation about altering the SP, if you still encounter a problem, then follow user326608 instructions about modifying your SP code

Body:
I'm extracting a date-formatted string (yyyy-MM-dd) and then converting it to a DateTime and inserting it in the database using a storedprocedure. But I keep getting

System.Data.SqlTypes.SqlTypeException: SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.

The column in my table is of type date.

I convert my string (e.g 2016-01-15) by invoking DateTime.ParseExact(expirationDate, "yyyy-MM-dd", null) and then I take that value and insert it as a parameter into my StoredProcedure and execute the proc.

But when using the debugger I can see that the return value is actually a yyyy-MM-dd HH:mm:ss-formatted DateTime.

this is an example of how the code looks like

string expirationDate = GetDate();
DateTime date = DateTime.ParseExact(expirationDate, "yyyy-MM-dd", null);

ExecuteMyStoredProc(date);

Body:
DateTime convertedInitDate = DateTime.ParseExact(initDate, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);
      cCCBEntities.initDate = convertedInitDate;

The code above is the code I used when I encountered this same problem that I kept on looking for like 5 hrs already. Thankfully mine got solved alright with the above code.

Notes:

I was using MVC in Visual Studio to develop a web application using sql server

cCCCBEntities is the name of my Entity I was using

This answer was the answer I got above from user326608, I just cant vote on it yet so i decided to put it on a comment here to emphasize that its what it solved my problem

Also, even though I was using SPs when saving to DB too, I didnt have to follow his recommendation about altering the SP, if you still encounter a problem, then follow user326608 instructions about modifying your SP code


问:
Recurrent Self Organizing Maps in Encog for Unsupervised Clustering with Context
Machine Learning - what a hoot!

I have a little project with which I would like to identify anomalies in unlabeled data. Thus, unsupervised clustering.

However, the sequence of the data is also important, as a single record may not be of interest, but the sequence of records that precede it may make it anomalous.

So I am thinking of building a Recurrent SOM to add the temporal context.

I have trained a few simple Machine Learning Models using Python Graphlab Create, Azure Machine Learning and Encog ML Framework, but Azure does not seem to provide unsupervised clustering and I am leaning towards using Encog.

I have looked at Recurrent Neural Networks in Encog, as well as SOM, but I have no idea how to combine the two. Most of the articles online regarding Feedback/Recurrent SOM Machine Learning are mostly academic.

Are there any good references for doing this with Encog?

答: A google search found only one good answer for RSOM in Encog: https://github.com/leadtune/encog-java/blob/master/encog-core/src/org/encog/neural/pattern/RSOMPattern.java</p>


问:
Why does PYTHONPATH with trailing colon add current directory to sys.path?
Consider a Python project like this:

```<code>foo/
    __init__.py
scripts/
    run.py
demo.sh
</code>```

Under normal circumstances, attempting to import from the foo package will
fail if you run the script from the root of the project, because default Python
behavior is to add the directory of script invoking the Python interpreter
(and not necessarily the current directory) to sys.path.
(docs):

```<code>python scripts/run.py
</code>```

However, I recently noticed that such imports were working on my box, and I
tracked it down to some surprising behavior related to PYTHONPATH. In my Bash
profile I had added a directory to PYTHONPATH:

```<code>export PYTHONPATH="/some/path:$PYTHONPATH"
</code>```

If PYTHONPATH is initially empty, that (somewhat sloppy, but commonly seen)
form of the command will leave a trailing colon:

```<code>echo $PYTHONPATH
/some/path:
</code>```

I had always assumed that this trailing punctuation had no impact, but it
appears that the trailing colon was the cause of the mysteriously successful
import. Leading or trailing colons (or even a defined but empty PYTHONPATH)
will result in sys.path containing an empty string before the site
module loads, which in turn leads to the current working directory being added
to sys.path.

Here are a Python script and a Bash script to demonstrate. I got the same
behavior using both Python 2.7 and Python 3.3.

Python script: run.py:

```<code>import sys, os

pp = os.environ.get('PYTHONPATH')

try:
    import foo
    print 'OK'
    assert os.getcwd() in sys.path
    assert pp == '' or pp.startswith(':') or pp.endswith(':')

except Exception:
    print 'FAIL'
    assert os.getcwd() not in sys.path
    assert pp is None
</code>```

Bash script: demo.sh:

```<code># Import fails.
unset PYTHONPATH;  python scripts/run.py

# Import succeeds -- to my surprise.
PYTHONPATH=''      python scripts/run.py
PYTHONPATH='/tmp:' python scripts/run.py
PYTHONPATH=':/tmp' python scripts/run.py
</code>```

My questions:

Am I understanding the situation correctly, or have I somehow gone astray?

Is this documented anywhere? I did not find anything. At a minimum, I am
posting this information here in case it will help others.

Am I alone in finding this behavior unexpected?

答:
When modifying colon-delimited environment variables such as PYTHONPATH, PATH, CPATH, MANPATH, LD_LIBRARY_PATH, PKG_CONFIG_PATH, etc...  Some of these variables place special meaning to trailing colons, while others do not.

For PYTHONPATH and PATH, I would recommend prepending (or appending) new directories in a manner that does not accidentally introduce trailing (or leading) colons if the variable was previously unset:

```<code>export PYTHONPATH="/some/path${PYTHONPATH+":"}${PYTHONPATH-}"
</code>```

(In the case of MANPATH and INFOPATH, you do want to introduce a trailing colon so that man and info will include their default search directories.)

Explanation:

${PYTHONPATH+":"} expands to a : if PYTHONPATH is set, regardless of if PYTHONPATH is empty.

${PYTHONPATH-} will expand to the contents of PYTHONPATH if it is set, but if PYTHONPATH is unset, then ${PYTHONPATH-} expands to nothing --- just like the usual ${PYTHONPATH}.

${PYTHONPATH-} is the same as ${PYTHONPATH-""} meaning to substitute "" (nothing) when PYTHONPATH is unset.

The reason I recommend ${PYTHONPATH-} over ${PYTHONPATH} here is that ${PYTHONPATH-} will not create an error when PYTHONPATH is unset and your script has executed set -u to raise errors on unset variables.

For details on the ${parameter+[word]} and ${parameter-[word]} mechanisms, see "Parameter Expansion" at http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_02

For details on set -u, see the description of "set" at http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set

Body:
Consider a Python project like this:

foo/
    __init__.py
scripts/
    run.py
demo.sh

Under normal circumstances, attempting to import from the foo package will
fail if you run the script from the root of the project, because default Python
behavior is to add the directory of script invoking the Python interpreter
(and not necessarily the current directory) to sys.path.
(docs):

python scripts/run.py

However, I recently noticed that such imports were working on my box, and I
tracked it down to some surprising behavior related to PYTHONPATH. In my Bash
profile I had added a directory to PYTHONPATH:

export PYTHONPATH="/some/path:$PYTHONPATH"

If PYTHONPATH is initially empty, that (somewhat sloppy, but commonly seen)
form of the command will leave a trailing colon:

echo $PYTHONPATH
/some/path:

I had always assumed that this trailing punctuation had no impact, but it
appears that the trailing colon was the cause of the mysteriously successful
import. Leading or trailing colons (or even a defined but empty PYTHONPATH)
will result in sys.path containing an empty string before the site
module loads, which in turn leads to the current working directory being added
to sys.path.

Here are a Python script and a Bash script to demonstrate. I got the same
behavior using both Python 2.7 and Python 3.3.

Python script: run.py:

import sys, os

pp = os.environ.get('PYTHONPATH')

try:
    import foo
    print 'OK'
    assert os.getcwd() in sys.path
    assert pp == '' or pp.startswith(':') or pp.endswith(':')

except Exception:
    print 'FAIL'
    assert os.getcwd() not in sys.path
    assert pp is None

Bash script: demo.sh:

# Import fails.
unset PYTHONPATH;  python scripts/run.py

# Import succeeds -- to my surprise.
PYTHONPATH=''      python scripts/run.py
PYTHONPATH='/tmp:' python scripts/run.py
PYTHONPATH=':/tmp' python scripts/run.py

My questions:

Am I understanding the situation correctly, or have I somehow gone astray?

Is this documented anywhere? I did not find anything. At a minimum, I am
posting this information here in case it will help others.

Am I alone in finding this behavior unexpected?

Body:
When modifying colon-delimited environment variables such as PYTHONPATH, PATH, CPATH, MANPATH, LD_LIBRARY_PATH, PKG_CONFIG_PATH, etc...  Some of these variables place special meaning to trailing colons, while others do not.

For PYTHONPATH and PATH, I would recommend prepending (or appending) new directories in a manner that does not accidentally introduce trailing (or leading) colons if the variable was previously unset:

export PYTHONPATH="/some/path${PYTHONPATH+":"}${PYTHONPATH-}"

(In the case of MANPATH and INFOPATH, you do want to introduce a trailing colon so that man and info will include their default search directories.)

Explanation:

${PYTHONPATH+":"} expands to a : if PYTHONPATH is set, regardless of if PYTHONPATH is empty.

${PYTHONPATH-} will expand to the contents of PYTHONPATH if it is set, but if PYTHONPATH is unset, then ${PYTHONPATH-} expands to nothing --- just like the usual ${PYTHONPATH}.

${PYTHONPATH-} is the same as ${PYTHONPATH-""} meaning to substitute "" (nothing) when PYTHONPATH is unset.

The reason I recommend ${PYTHONPATH-} over ${PYTHONPATH} here is that ${PYTHONPATH-} will not create an error when PYTHONPATH is unset and your script has executed set -u to raise errors on unset variables.

For details on the ${parameter+[word]} and ${parameter-[word]} mechanisms, see "Parameter Expansion" at http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_02

For details on set -u, see the description of "set" at http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set


问:
Multiple file upload validation in laravel
I have multiple input fields with multiple file upload for each field.

```<code><?php for ($i = 0; $i < $total; $i++)
   {
?>
<div class="col-md-3 addedClass">
     <label>Vehicle Images</label>
     <input type="file" name="vehicle_image[{{$i}}][]" multiple="multiple">
     @if($errors->has('vehicle_image'))
          <span class="help-block">
              <strong>{{$errors->first('vehicle_image')}}</strong>
          </span>
     @endif
</div>
<?php } ?>
</code>```

I have got files in the request like this:

```<code>"vehicle_image" => array:2 [▼
    0 => array:2 [▼
      0 => "citizenship.jpg"
      1 => "logo_vehicle.png"
    ]
    1 => array:2 [▼
      0 => "ae backend.jpg"
      1 => "logo_vehicle.png"
    ]
  ]
</code>```

In this case, I have two input fields with 2/2 files. When I have tried to validate mime type for only images like this:

```<code>$this->validate($request,[
           'vehicle_image' => 'mimes:jpeg,png,bmp,tiff |max:4096'
       ],$messages[
            // error messages
      ]);
</code>```

I have got following error:

FatalThrowableError in ReservationController.php line 67: Cannot use [] for reading

Can someone tell me what is wrong with the above code ?
Suggestions are appreciated.

答:
just remove extra empty array index from the input field.

```<code><input type="file" name="vehicle_image[{{$i}}]" multiple="multiple">

$this->validate($request, [
            'vehicle_image' => 'image|mimes:jpeg,png,jpg,gif,svg|max:4096'
        ]);
</code>```

and  dd($errors) see result

Body:
I have multiple input fields with multiple file upload for each field.

<?php for ($i = 0; $i < $total; $i++)
   {
?>

     Vehicle Images
     <input type="file" name="vehicle_image[{{$i}}][]" multiple="multiple">
     @if($errors->has('vehicle_image'))

              {{$errors->first('vehicle_image')}}

     @endif

<?php } ?>

I have got files in the request like this:

"vehicle_image" => array:2 [▼
    0 => array:2 [▼
      0 => "citizenship.jpg"
      1 => "logo_vehicle.png"
    ]
    1 => array:2 [▼
      0 => "ae backend.jpg"
      1 => "logo_vehicle.png"
    ]
  ]

In this case, I have two input fields with 2/2 files. When I have tried to validate mime type for only images like this:

$this->validate($request,[
           'vehicle_image' => 'mimes:jpeg,png,bmp,tiff |max:4096'
       ],$messages[
            // error messages
      ]);

I have got following error:

FatalThrowableError in ReservationController.php line 67: Cannot use [] for reading

Can someone tell me what is wrong with the above code ?
Suggestions are appreciated.

Body:
just remove extra empty array index from the input field.

<input type="file" name="vehicle_image[{{$i}}]" multiple="multiple">

$this->validate($request, [
            'vehicle_image' => 'image|mimes:jpeg,png,jpg,gif,svg|max:4096'
        ]);

and  dd($errors) see result


问:
Failed to resolve: com.google.firebase:firebase-core:9.0.0
I get the following  error while upgrading a firebase project from old domain to new google firebase domain.

Failed to resolve: com.google.firebase:firebase-core:9.0.0

I followed the steps mentioned on the Firebase documentation, in the section Add Firebase to your Android Project, topic Available libraries.

What are my options to resolve this error?

答:
Need to Update

Android SDK : SDK Tools -> Support Repository -> Google Repository

After updating the Android SDK need to sync gradle build in Android studio.


问:
Customize post-publish flash message in Wagtail CMS
I'm using Wagtail's after_create_page and after_edit_page hooks to push data to an external service, and I'd like to display an error or success message depending on the response. Is there a way to hook into the flash messages that appear after publishing a page?

答:
You could use the Wagtail internal messages API as part of your wagtail_hook. This is not documented but I have tested it with the Wagtaildemo application locally.

Wagtail messages API takes a request object and can be used to render success/error/warning messages alongside that request's response.

All messages appear to be append only, so your error message would appear under the success message from the page being created.

Example code below.

```<code># my_aap/wagtail_hooks.py
from wagtail.wagtailcore import hooks
from wagtail.wagtailadmin import messages

@hooks.register('after_edit_page')
def do_after_page_edit(request, page):
    messages.success(request, "Looking good")

@hooks.register('after_create_page')
def do_after_page_create(request, page):
    messages.error(request, "Failed to send items to external server")
</code>```

These messages will not affect the overall HTTP response of the edit or create page response views.

You can also see how the internal messages API is used when creating and editing pages at wagtailadmin/views/pages.py. You can even create buttons on messages pretty easily.

Body:
You could use the Wagtail internal messages API as part of your wagtail_hook. This is not documented but I have tested it with the Wagtaildemo application locally.

Wagtail messages API takes a request object and can be used to render success/error/warning messages alongside that request's response.

All messages appear to be append only, so your error message would appear under the success message from the page being created.

Example code below.

# my_aap/wagtail_hooks.py
from wagtail.wagtailcore import hooks
from wagtail.wagtailadmin import messages

@hooks.register('after_edit_page')
def do_after_page_edit(request, page):
    messages.success(request, "Looking good")

@hooks.register('after_create_page')
def do_after_page_create(request, page):
    messages.error(request, "Failed to send items to external server")

These messages will not affect the overall HTTP response of the edit or create page response views.

You can also see how the internal messages API is used when creating and editing pages at wagtailadmin/views/pages.py. You can even create buttons on messages pretty easily.


问:
Ean 13 Font does not read from scanner
I just downloaded ean 13 font. I'm writing a barcode in word example: 5200095632132 but when I print it, my scanner can't read it. Am I doing something wrong? In other barcode fonts I read that you need to place '*' as character start and end. Like * 5200095632132 * But in this font when i put * doesn't generate it to barcode line.

This is how my barcode looks like:

And this is how a barcode generator software creates the same barcode:

答:
This French guy made an excellent tutorial on how to use the bar code font: http://grandzebu.net/informatique/codbar-en/ean13.htm

(spoiler: it is more complicated than you think)

With help of this page I made a simple translation spreadsheet to make ean8 bar codes: https://www.dropbox.com/s/z7o1w0clfhtxb5i/barcodemaker%20leeg.xls?dl=0

This will give you an idea.

The general idea is that you cannot use the number itself, but a letter instead. Fo example: 0=A, 1=B, 2=C etc

Which letter also depends on the place of the number. In ean8 for example, the first 4 digits: 0=A, 1=B, 2=C etc. But the last 4 digits: 0=a, 1=b, 2=c etc.

In the case of ean13 it depends on the first digit, which translation you use for each of the first 6 digits. Grandzebu has an nice translation table for that.

If you are into VBA you can make a nice macro. But with vanilla excel formulas it is also possible. It just takes up some space.

Title: Ean 13 Font does not read from scanner


问:
R How to plot a graph with multiple geom
The problem comes when I tried to add one more variable, the number of flights, in the last line of my code.
Can I add more than one geom, which unit of x-axis and y-axis are not necessarily the same?   Thank you

```<code>library(nycflights13)
library(tidyverse)
flights %>%
mutate(
    cancelled_flights = is.na(dep_delay),
    sched_dep_time.HMM = sched_dep_time %/%100 + (sched_dep_time%%100)/60,
    sched_dep_time.byH = sched_dep_time.HMM %/%1) %>%
group_by(sched_dep_time.byH) %>%
summarise(
    delay_prob = sum(is.na(dep_delay)) / n(),
    count = n()) %>%
filter(sched_dep_time.byH >=2) %>%
ggplot() +
geom_path(mapping = aes(x = sched_dep_time.byH, y = delay_prob)) +
geom_col(mapping = aes(x = sched_dep_time.byH, y = count ))
</code>```

答:
The only reason why your plot isn't showing is due to the different y-axis values for delay_prob (0.005 to 0.04) and count (1061 to 27242).

Here's a way to play around with a second y-axis to show both plots:

```<code>ggplot(df, aes(x = sched_dep_time.byH)) +
  geom_line(aes(y = delay_prob), colour="red") +
  geom_bar(aes(y=count/1000000), stat="identity") +
  scale_y_continuous(sec.axis = sec_axis(~.*1000000, name = "count"))
</code>```

Alternative approach by plotting different plots on with facet_wrap:

```<code>df <- df %>% gather(type, val, delay_prob, count)

ggplot(df, aes(sched_dep_time.byH, val)) +
  geom_bar(data=df %>% filter(type=="count"), stat="identity") +
  geom_line(data=df %>% filter(type=="delay_prob")) +
  facet_wrap(~type, scales="free", ncol=1)
</code>```

Input data:

```<code>df <- flights %>%
   mutate(
    cancelled_flights = is.na(dep_delay),
    sched_dep_time.HMM = sched_dep_time %/%100 + sched_dep_time%%100)/60,
    sched_dep_time.byH = sched_dep_time.HMM %/%1) %>%
  group_by(sched_dep_time.byH) %>%
  summarise(
    delay_prob = sum(is.na(dep_delay)) / n(),
    count = n()) %>%
  filter(sched_dep_time.byH >=2)
</code>```

Body:
The problem comes when I tried to add one more variable, the number of flights, in the last line of my code.
Can I add more than one geom, which unit of x-axis and y-axis are not necessarily the same?   Thank you

library(nycflights13)
library(tidyverse)
flights %>%
mutate(
    cancelled_flights = is.na(dep_delay),
    sched_dep_time.HMM = sched_dep_time %/%100 + (sched_dep_time%%100)/60,
    sched_dep_time.byH = sched_dep_time.HMM %/%1) %>%
group_by(sched_dep_time.byH) %>%
summarise(
    delay_prob = sum(is.na(dep_delay)) / n(),
    count = n()) %>%
filter(sched_dep_time.byH >=2) %>%
ggplot() +
geom_path(mapping = aes(x = sched_dep_time.byH, y = delay_prob)) +
geom_col(mapping = aes(x = sched_dep_time.byH, y = count ))

Body:
The only reason why your plot isn't showing is due to the different y-axis values for delay_prob (0.005 to 0.04) and count (1061 to 27242).

Here's a way to play around with a second y-axis to show both plots:

ggplot(df, aes(x = sched_dep_time.byH)) +
  geom_line(aes(y = delay_prob), colour="red") +
  geom_bar(aes(y=count/1000000), stat="identity") +
  scale_y_continuous(sec.axis = sec_axis(~.*1000000, name = "count"))

Alternative approach by plotting different plots on with facet_wrap:

df <- df %>% gather(type, val, delay_prob, count)

ggplot(df, aes(sched_dep_time.byH, val)) +
  geom_bar(data=df %>% filter(type=="count"), stat="identity") +
  geom_line(data=df %>% filter(type=="delay_prob")) +
  facet_wrap(~type, scales="free", ncol=1)

Input data:

df <- flights %>%
   mutate(
    cancelled_flights = is.na(dep_delay),
    sched_dep_time.HMM = sched_dep_time %/%100 + sched_dep_time%%100)/60,
    sched_dep_time.byH = sched_dep_time.HMM %/%1) %>%
  group_by(sched_dep_time.byH) %>%
  summarise(
    delay_prob = sum(is.na(dep_delay)) / n(),
    count = n()) %>%
  filter(sched_dep_time.byH >=2)


问:
Combobox inside another combobox
Need help writing a code - I've developed a userform.

I need one combo box to show the main section of a letter:
"based on our determination HE/SHE is entitled to a refund"
"based on our determination HE/SHE is not entitled to a refund"

but I also need a combo box to select gender:
"HE"
"SHE"

so far I have:

```<code>Private Sub Userform_Initialize()
With ComboBoxDecision
.AddItem "based on our determination HE/SHE is entitled to a refund"
.AddItem "based on our determination HE/SHE is not entitled to a refund"
End With
With ComboBoxGender
.AddItem "HE"
.AddItem "SHE"
End With
lbl_exit:
Exit sub
End Sub

Private Sub CommandButtonOk_Click()
Application.ScreenUpdating = False
With ActiveDocument
    .Bookmarks("Decision").Range.Text = ComboBoxDecision.Value
    End With
Application.ScreenUpdating = True
Unload Me
End Sub
</code>```

Is there a way to do:

```<code>.AddItem "based on our determination "Whatever option was selected in ComboBoxGender" is entitled to a refund"
.AddItem "based on our determination "Whatever option was selected in ComboBoxGender" is not entitled to a refund"
</code>```

Happy to supply any more information.

答:
The simplest way would probably be to populate the 'Decision' combobox with the appropriate text each time the 'Gender' combobox changes. You'd do this by trapping the ComboBoxGender_Change event, like so:

```<code>Private Sub ComboBoxGender_Change()
    Dim gndr As String

    gndr = Me.ComboBoxGender.Text

    With Me.ComboBoxDecision
        .Clear
        .AddItem "based on our determination " & _
                 gndr & " is entitled to a refund"
        .AddItem "based on our determination " & _
                 gndr & " is not entitled to a refund"
    End With

End Sub

Private Sub UserForm_Initialize()
    With Me.ComboBoxGender
        .AddItem "HE"
        .AddItem "SHE"
        .ListIndex = 0
    End With
End Sub
</code>```

Title: Combobox inside another combobox

Body:
Need help writing a code - I've developed a userform.

I need one combo box to show the main section of a letter:
"based on our determination HE/SHE is entitled to a refund"
"based on our determination HE/SHE is not entitled to a refund"

but I also need a combo box to select gender:
"HE"
"SHE"

so far I have:

Private Sub Userform_Initialize()
With ComboBoxDecision
.AddItem "based on our determination HE/SHE is entitled to a refund"
.AddItem "based on our determination HE/SHE is not entitled to a refund"
End With
With ComboBoxGender
.AddItem "HE"
.AddItem "SHE"
End With
lbl_exit:
Exit sub
End Sub

Private Sub CommandButtonOk_Click()
Application.ScreenUpdating = False
With ActiveDocument
    .Bookmarks("Decision").Range.Text = ComboBoxDecision.Value
    End With
Application.ScreenUpdating = True
Unload Me
End Sub

Is there a way to do:

.AddItem "based on our determination "Whatever option was selected in ComboBoxGender" is entitled to a refund"
.AddItem "based on our determination "Whatever option was selected in ComboBoxGender" is not entitled to a refund"

Happy to supply any more information.

Body:
The simplest way would probably be to populate the 'Decision' combobox with the appropriate text each time the 'Gender' combobox changes. You'd do this by trapping the ComboBoxGender_Change event, like so:

Private Sub ComboBoxGender_Change()
    Dim gndr As String

    gndr = Me.ComboBoxGender.Text

    With Me.ComboBoxDecision
        .Clear
        .AddItem "based on our determination " & _
                 gndr & " is entitled to a refund"
        .AddItem "based on our determination " & _
                 gndr & " is not entitled to a refund"
    End With

End Sub

Private Sub UserForm_Initialize()
    With Me.ComboBoxGender
        .AddItem "HE"
        .AddItem "SHE"
        .ListIndex = 0
    End With
End Sub


问:
Adding content to dashboard of liferay user other than admin
I am new to using Liferay, and practicing currently on Liferay DXP. I have created various user, and wanted to add different content to dashboard of any user. Such as asset publisher which will list all the assets published by that user. I am able to add this modified content only for Admin User. I am not able to find any setting where I can change the look and feel of dashboard for every user.
Can anyone please help me where I can find it? It might be pretty simple but I am unable to find it.
Thank you in advance for helping me. </p>

答: You can look at the ADT. Modify the templates as per requirement and on user roles. You won't be able to deliver content as per individual user but to roles. You can also have portlet preferences to show different content on different criteria. This all is possible. You will have to study the subject more. It will be very difficult to detail out the whole stuff here. But yes with ADT in Liferay 7 / DXP you have a lot of flexibility. </p>


问:
Complex If condition in typo3 fluid template inside the css class
I'm facing an issue in the following code

```<code><div class="panel-icon {f:if(condition: '{0:panel.id}=={0:123}', then: 'icon-update', else: 'icon-{icon}')}"></div>
</code>```

Currently the above code check if the panel.id equals to 123 then apply the icon-update to css class else whatever the icon being passed through {icon}

it works fine, but my requirement is I have 3 different panel.id and if any of those panel id's have passed, then the icon-update should be applied.

These are the approches I tried, but they're not working for me

Approach 1

```<code><div class="panel-icon {f:if(condition: '{0:panel.id}=={0:123,0:456,0:789}', then: 'icon-update', else: 'icon-{icon}')}"></div>
</code>```

Approach 2

```<code><div class="panel-icon {f:if(condition: '{0:panel.id, 1:panel.id, 2:panel.id}=={0:123, 1:456, 2:789}', then: 'icon-update', else: 'icon-{icon}')}"></div>
</code>```

I was tyring to find a clean solution for this, but still no luck. Any typo3 expert there to fix this issue?

答:
I found the answer by myself for my question and I'm posting it here if anyone looking for a solution like me

```<code><v:if stack="{0:panel.id, 1:'==', 2:'123', 3:'||', 4:panel.id, 5: '==', 6:'456', 7:'||', 8:panel.id, 9:'==', 10:'789'}">
   <f:then><div class="icon icon-update"></div></f:then>
   <f:else><div class="icon icon-{icon}"></div></f:else>
</v:if>
</code>```

This solved my problem

Body:
I'm facing an issue in the following code

Currently the above code check if the panel.id equals to 123 then apply the icon-update to css class else whatever the icon being passed through {icon}

it works fine, but my requirement is I have 3 different panel.id and if any of those panel id's have passed, then the icon-update should be applied.

These are the approches I tried, but they're not working for me

Approach 1

Approach 2

I was tyring to find a clean solution for this, but still no luck. Any typo3 expert there to fix this issue?

Body:
I found the answer by myself for my question and I'm posting it here if anyone looking for a solution like me

<v:if stack="{0:panel.id, 1:'==', 2:'123', 3:'||', 4:panel.id, 5: '==', 6:'456', 7:'||', 8:panel.id, 9:'==', 10:'789'}">
   <f:then><div class="icon icon-update"></div></f:then>
   <f:else><div class="icon icon-{icon}"></div></f:else>
</v:if>

This solved my problem


问:
Query string in Bokeh Python
I have developed a Bokeh App. hosted on Windows Server. I need query string passed in browser to manipulate my plots.

```<code>192.168.190.126/bokehApp?csv=xyz.csv&tsv=abc.tsv
</code>```

I want to know the values after ?.

答:
This feature was added (as mentioned here).

To query the "??csv=xyz.csv&tsv=abc.tsv" part of the HTML see the attributes of the request, i.e., in the on_session_created function the attributes passed by url are in the session_context variable as session_context.reques.arguments.

In your case if we have:

```<code>def on_session_created(session_context):
    ''' If present, this function is called when a session is created. '''
    print "Arguments after '?': {}".format(session_context.request.arguments)
</code>```

After running bokeh serve bokehApp and pasting 192.168.190.126/bokehApp?csv=xyz.csv&tsv=abc.tsv on the browser the output on terminal would be:

```<code>Arguments after '?': {'csv':'xyz.csv', 'tsv':'abc.tsv'}
</code>```

Note that the on_session_created function is on the server_lifecycle.py.

Title: Query string in Bokeh Python

Body:
I have developed a Bokeh App. hosted on Windows Server. I need query string passed in browser to manipulate my plots.

192.168.190.126/bokehApp?csv=xyz.csv&tsv=abc.tsv

I want to know the values after ?.

Body:
This feature was added (as mentioned here).

To query the "??csv=xyz.csv&tsv=abc.tsv" part of the HTML see the attributes of the request, i.e., in the on_session_created function the attributes passed by url are in the session_context variable as session_context.reques.arguments.

In your case if we have:

def on_session_created(session_context):
    ''' If present, this function is called when a session is created. '''
    print "Arguments after '?': {}".format(session_context.request.arguments)

After running bokeh serve bokehApp and pasting 192.168.190.126/bokehApp?csv=xyz.csv&tsv=abc.tsv on the browser the output on terminal would be:

Arguments after '?': {'csv':'xyz.csv', 'tsv':'abc.tsv'}

Note that the on_session_created function is on the server_lifecycle.py.


问:
How to merge audio and video using MediaMuxer?
I'm developing an Android App with mp3 audio file and mp4 video file with(no sound).

Now I want to mix them and create a new mp4 video file(with sound). From Android 4.3, Google suggests using the MediaMuxer class to mix stream audio and video. I have tried many times without success.

Here is the code:

```<code>    private void muxing() {

    String outputFile = "";

    try {

        File file = new File(Environment.getExternalStorageDirectory() + "/final2.mp4");
        file.createNewFile();
        outputFile = file.getAbsolutePath();
        MediaExtractor videoExtractor = new MediaExtractor();
        videoExtractor.setDataSource(Environment.getExternalStorageDirectory().toString()+"/vd1.h264");
        MediaExtractor audioExtractor = new MediaExtractor();
        audioExtractor.setDataSource(Environment.getExternalStorageDirectory()+"/audioVideoDir/audio.m4a");
        MediaMuxer muxer = new MediaMuxer(outputFile, MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4);

        videoExtractor.selectTrack(0);
        MediaFormat videoFormat = videoExtractor.getTrackFormat(0);
        int videoTrack = muxer.addTrack(videoFormat);

        audioExtractor.selectTrack(0);
        MediaFormat audioFormat = audioExtractor.getTrackFormat(0);
        int audioTrack = muxer.addTrack(audioFormat);
        boolean sawEOS = false;
        int frameCount = 0;
        int offset = 100;
        int sampleSize = 256 * 1024;
        ByteBuffer videoBuf = ByteBuffer.allocate(sampleSize);
        ByteBuffer audioBuf = ByteBuffer.allocate(sampleSize);
        MediaCodec.BufferInfo videoBufferInfo = new MediaCodec.BufferInfo();
        MediaCodec.BufferInfo audioBufferInfo = new MediaCodec.BufferInfo();

        videoExtractor.seekTo(0, MediaExtractor.SEEK_TO_CLOSEST_SYNC);
        audioExtractor.seekTo(0, MediaExtractor.SEEK_TO_CLOSEST_SYNC);

        muxer.start();

        while (!sawEOS)
        {
            videoBufferInfo.offset = offset;
            videoBufferInfo.size = videoExtractor.readSampleData(videoBuf, offset);

            if (videoBufferInfo.size < 0 || audioBufferInfo.size < 0)
            {
               // Log.d(TAG, "saw input EOS.");
                sawEOS = true;
                videoBufferInfo.size = 0;

            }
            else
            {
                videoBufferInfo.presentationTimeUs = videoExtractor.getSampleTime();
                videoBufferInfo.flags = videoExtractor.getSampleFlags();
                muxer.writeSampleData(videoTrack, videoBuf, videoBufferInfo);
                videoExtractor.advance();

                frameCount++;

            }
        }

        Toast.makeText(getApplicationContext() , "frame:" + frameCount , Toast.LENGTH_SHORT).show();

        boolean sawEOS2 = false;
        int frameCount2 =0;
        while (!sawEOS2)
        {
            frameCount2++;

            audioBufferInfo.offset = offset;
            audioBufferInfo.size = audioExtractor.readSampleData(audioBuf, offset);

            if (videoBufferInfo.size < 0 || audioBufferInfo.size < 0)
            {
              //  Log.d(TAG, "saw input EOS.");
                sawEOS2 = true;
                audioBufferInfo.size = 0;
            }
            else
            {
                audioBufferInfo.presentationTimeUs = audioExtractor.getSampleTime();
                audioBufferInfo.flags = audioExtractor.getSampleFlags();
                muxer.writeSampleData(audioTrack, audioBuf, audioBufferInfo);
                audioExtractor.advance();

            }
        }

        Toast.makeText(getApplicationContext() , "frame:" + frameCount2 , Toast.LENGTH_SHORT).show();

        muxer.stop();
        muxer.release();

    } catch (IOException e) {

    } catch (Exception e) {

    }
}
</code>```

I get the below error:

Unknown mime type 'audio/mpeg'. 12-09 11:58:33.569: A/MPEG4Writer(332): frameworks/av/media/libstagefright/MPEG4Writer.cpp:2699 CHECK(!"should not be here, unknown mime type.")

Any solution to resolve my issue with MediaMuxer API from Google? Even i tried with ffmpeg after merging of audio and video together video doesn't plays in default video player of android device but it loads in Vlc player.

FFMPEG followed from here:https://github.com/WritingMinds/ffmpeg-android-java

答:
try to add mp4 video file.
Its working for me. but output file is with audio duration.</p>

Body:
I'm developing an Android App with mp3 audio file and mp4 video file with(no sound).

Now I want to mix them and create a new mp4 video file(with sound). From Android 4.3, Google suggests using the MediaMuxer class to mix stream audio and video. I have tried many times without success.

Here is the code:

    private void muxing() {

    String outputFile = "";

    try {

        File file = new File(Environment.getExternalStorageDirectory() + "/final2.mp4");
        file.createNewFile();
        outputFile = file.getAbsolutePath();
        MediaExtractor videoExtractor = new MediaExtractor();
        videoExtractor.setDataSource(Environment.getExternalStorageDirectory().toString()+"/vd1.h264");
        MediaExtractor audioExtractor = new MediaExtractor();
        audioExtractor.setDataSource(Environment.getExternalStorageDirectory()+"/audioVideoDir/audio.m4a");
        MediaMuxer muxer = new MediaMuxer(outputFile, MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4);

        videoExtractor.selectTrack(0);
        MediaFormat videoFormat = videoExtractor.getTrackFormat(0);
        int videoTrack = muxer.addTrack(videoFormat);

        audioExtractor.selectTrack(0);
        MediaFormat audioFormat = audioExtractor.getTrackFormat(0);
        int audioTrack = muxer.addTrack(audioFormat);
        boolean sawEOS = false;
        int frameCount = 0;
        int offset = 100;
        int sampleSize = 256 * 1024;
        ByteBuffer videoBuf = ByteBuffer.allocate(sampleSize);
        ByteBuffer audioBuf = ByteBuffer.allocate(sampleSize);
        MediaCodec.BufferInfo videoBufferInfo = new MediaCodec.BufferInfo();
        MediaCodec.BufferInfo audioBufferInfo = new MediaCodec.BufferInfo();

        videoExtractor.seekTo(0, MediaExtractor.SEEK_TO_CLOSEST_SYNC);
        audioExtractor.seekTo(0, MediaExtractor.SEEK_TO_CLOSEST_SYNC);

        muxer.start();

        while (!sawEOS)
        {
            videoBufferInfo.offset = offset;
            videoBufferInfo.size = videoExtractor.readSampleData(videoBuf, offset);

            if (videoBufferInfo.size < 0 || audioBufferInfo.size < 0)
            {
               // Log.d(TAG, "saw input EOS.");
                sawEOS = true;
                videoBufferInfo.size = 0;

            }
            else
            {
                videoBufferInfo.presentationTimeUs = videoExtractor.getSampleTime();
                videoBufferInfo.flags = videoExtractor.getSampleFlags();
                muxer.writeSampleData(videoTrack, videoBuf, videoBufferInfo);
                videoExtractor.advance();

                frameCount++;

            }
        }

        Toast.makeText(getApplicationContext() , "frame:" + frameCount , Toast.LENGTH_SHORT).show();

        boolean sawEOS2 = false;
        int frameCount2 =0;
        while (!sawEOS2)
        {
            frameCount2++;

            audioBufferInfo.offset = offset;
            audioBufferInfo.size = audioExtractor.readSampleData(audioBuf, offset);

            if (videoBufferInfo.size < 0 || audioBufferInfo.size < 0)
            {
              //  Log.d(TAG, "saw input EOS.");
                sawEOS2 = true;
                audioBufferInfo.size = 0;
            }
            else
            {
                audioBufferInfo.presentationTimeUs = audioExtractor.getSampleTime();
                audioBufferInfo.flags = audioExtractor.getSampleFlags();
                muxer.writeSampleData(audioTrack, audioBuf, audioBufferInfo);
                audioExtractor.advance();

            }
        }

        Toast.makeText(getApplicationContext() , "frame:" + frameCount2 , Toast.LENGTH_SHORT).show();

        muxer.stop();
        muxer.release();

    } catch (IOException e) {

    } catch (Exception e) {

    }
}

I get the below error:

Unknown mime type 'audio/mpeg'. 12-09 11:58:33.569: A/MPEG4Writer(332): frameworks/av/media/libstagefright/MPEG4Writer.cpp:2699 CHECK(!"should not be here, unknown mime type.")

Any solution to resolve my issue with MediaMuxer API from Google? Even i tried with ffmpeg after merging of audio and video together video doesn't plays in default video player of android device but it loads in Vlc player.

FFMPEG followed from here:https://github.com/WritingMinds/ffmpeg-android-java


问:
Is there a way to change the color of a UINavigationBar based on the color of content displayed
So I'm working on a custom music player app. I need to be able to dynamically change the color of the Navigation bar based on the content displayed in the view. I've searched around and can't seem to find a way to do it if it's even possible. I know how to change the color to basically any color but not have it change based on the colors of a UIImage. This is what my designer has come up with.

I also need to change the colors of the buttons within that same table view cell and on the Navigation bar basically the same way. Here is what I have in storyboard already.

I also need to be able to change the colors of the tab bar and it's items. I don't know if this is even possible. Could someone shed some light on this or maybe point me in the right direction

答: The simplest way to achieve this design will be to make the navigation bar completely transparent and give the full screen image top constraints as 0 with the view. Then the image will be shown from top of the screen. Then give the navigation bar a shadow image as per the design. But for the tab bar I believe you might have to pick the color from imageview and change the tab bar's background.</p>


问:
How to check if a file exists (regardless of its file type)?
Edit: The problem wasn't with my c++. The problem was with how I was calling the shared library in GameMaker Studio, which was why it wasn't working.

I'm trying to detect whether a file exists, and I've tried many methods over the internet and none of them seem to work. Here's an example:

```<code>double file_exists(char *filename)
{
    std::ifstream infile(filename);
    return infile.good();
}
</code>```

I assume it will only work with text files. for example, this won't work:

```<code>file_exists("/usr/bin/gedit");
</code>```

...because that is a Linux executable.

I want a means to check whether a file exists regardless of its file type.

On Windows, this can easily be achieved like so:

```<code>double file_exists(char* filename)
{
    DWORD fileAtt = GetFileAttributesA(filename);
    if(fileAtt == INVALID_FILE_ATTRIBUTES)
        throw GetLastError();

    return (bool)((fileAtt&FILE_ATTRIBUTE_DIRECTORY) == 0);
}
</code>```

But I'm on Linux and I need an equivalent of the above snippet that will work on Linux.

答:
In Linux you have the stat() system call:

```<code>struct stat st;
int res = stat(filename, &st);
bool exists = res == 0;
</code>```

If you want more finesse, you can check the errno if res is non-zero:

```<code>if (res == 0)
    return true;
if (errno == ENOENT)
    return false;
throw errno; //you're throwing an int, aren't you?
</code>```

Also, as a bonus, if you want to know if it is a directory or a normal file or a fifo or a socket or a device... you can check the contents of st.st_mode.

Body:
Edit: The problem wasn't with my c++. The problem was with how I was calling the shared library in GameMaker Studio, which was why it wasn't working.

I'm trying to detect whether a file exists, and I've tried many methods over the internet and none of them seem to work. Here's an example:

double file_exists(char *filename)
{
    std::ifstream infile(filename);
    return infile.good();
}

I assume it will only work with text files. for example, this won't work:

file_exists("/usr/bin/gedit");

...because that is a Linux executable.

I want a means to check whether a file exists regardless of its file type.

On Windows, this can easily be achieved like so:

double file_exists(char* filename)
{
    DWORD fileAtt = GetFileAttributesA(filename);
    if(fileAtt == INVALID_FILE_ATTRIBUTES)
        throw GetLastError();

    return (bool)((fileAtt&FILE_ATTRIBUTE_DIRECTORY) == 0);
}

But I'm on Linux and I need an equivalent of the above snippet that will work on Linux.

Body:
In Linux you have the stat() system call:

struct stat st;
int res = stat(filename, &st);
bool exists = res == 0;

If you want more finesse, you can check the errno if res is non-zero:

if (res == 0)
    return true;
if (errno == ENOENT)
    return false;
throw errno; //you're throwing an int, aren't you?

Also, as a bonus, if you want to know if it is a directory or a normal file or a fifo or a socket or a device... you can check the contents of st.st_mode.