问:
Compiling `core` from a specific source using Xargo
Based on this comment, it should be possible to use Xargo to manage the installation of a custom core crate for a particular target. I've tried the following to get it working with a crate that has no other dependency except core:

Cargo.toml: no dependencies listed

```<code>[package]
name = "chip8-engine"
version = "0.1.0"
authors = ["Dr. ERDI Gergo <gergo@erdi.hu>"]

[dependencies]
</code>```

Xargo.toml: my specific source listed for core

```<code>[target.avr-atmel-none.dependencies]
core = { git = "https://github.com/gergoerdi/rust-avr-libcore-mini", rev = "adda44aa91ac517aab6915447592ee4cad26564c" }
</code>```

However, building via xargo build fails as if I was just using cargo:

```<code>$ ~/.cargo/bin/xargo build --release -v --target avr-atmel-none
+ "rustc" "--print" "sysroot"
+ "cargo" "build" "--release" "-v" "--target" "avr-atmel-none"
   Compiling chip8-engine v0.1.0 (file:///home/cactus/prog/rust/avr/chip8-engine-avr)
     Running `stage1/bin/rustc --crate-name chip8_engine src/lib.rs --crate-type lib -C opt-level=3 -C metadata=231962fc6e1bee04 -C extra-filename=-231962fc6e1bee04 --out-dir /home/cactus/prog/rust/avr/chip8-engine-avr/target/avr-atmel-none/release/deps --emit=dep-info,link --target avr-atmel-none -L dependency=/home/cactus/prog/rust/avr/chip8-engine-avr/target/avr-atmel-none/release/deps -L dependency=/home/cactus/prog/rust/avr/chip8-engine-avr/target/release/deps`
error[E0463]: can't find crate for `core`
  |
  = note: the `avr-atmel-none` target may not be installed

error: aborting due to previous error

error: Could not compile `chip8-engine`.

Caused by:
  process didn't exit successfully: `stage1/bin/rustc --crate-name chip8_engine src/lib.rs --crate-type lib -C opt-level=3 -C metadata=231962fc6e1bee04 -C extra-filename=-231962fc6e1bee04 --out-dir /home/cactus/prog/rust/avr/chip8-engine-avr/target/avr-atmel-none/release/deps --emit=dep-info,link --target avr-atmel-none -L dependency=/home/cactus/prog/rust/avr/chip8-engine-avr/target/avr-atmel-none/release/deps -L dependency=/home/cactus/prog/rust/avr/chip8-engine-avr/target/release/deps` (exit code: 101)
</code>```

Note that there's nothing indicating even attempted Git traffic.

In contrast, here's the output of vanilla cargo if I put my core = { git = ...} line in Cargo.toml instead of Xargo.toml, which works as expected:

```<code>$ cargo build -v --target=avr-atmel-none --release
   Compiling core v0.1.0 (https://github.com/gergoerdi/rust-avr-libcore-mini?rev=adda44aa91ac517aab6915447592ee4cad26564c#adda44aa)
     Running `stage1/bin/rustc --crate-name core /home/cactus/.cargo/git/checkouts/rust-avr-libcore-mini-37e279d93a70b45a/adda44a/src/lib.rs --crate-type lib -C opt-level=3 -C metadata=47f38a1987c5b284 -C extra-filename=-47f38a1987c5b284 --out-dir /home/cactus/prog/rust/avr/chip8-engine-avr/target/avr-atmel-none/release/deps --emit=dep-info,link --target avr-atmel-none -L dependency=/home/cactus/prog/rust/avr/chip8-engine-avr/target/avr-atmel-none/release/deps -L dependency=/home/cactus/prog/rust/avr/chip8-engine-avr/target/release/deps --cap-lints allow`
   Compiling chip8-engine v0.1.0 (file:///home/cactus/prog/rust/avr/chip8-engine-avr)
     Running `stage1/bin/rustc --crate-name chip8_engine src/lib.rs --crate-type lib -C opt-level=3 -C metadata=231962fc6e1bee04 -C extra-filename=-231962fc6e1bee04 --out-dir /home/cactus/prog/rust/avr/chip8-engine-avr/target/avr-atmel-none/release/deps --emit=dep-info,link --target avr-atmel-none -L dependency=/home/cactus/prog/rust/avr/chip8-engine-avr/target/avr-atmel-none/release/deps -L dependency=/home/cactus/prog/rust/avr/chip8-engine-avr/target/release/deps --extern core=/home/cactus/prog/rust/avr/chip8-engine-avr/target/avr-atmel-none/release/deps/libcore-47f38a1987c5b284.rlib`
    Finished release [optimized] target(s) in 15.21 secs
</code>```

答:
It turns out picking up rustc's path from .cargo/config is not currently supported by Xargo, so whatever rustc I want to use need to be installed as a rustup link. To quote the above ticket:

In the meantine you could use rustup to create a custom toolchain that points to your stage1 rustc. That's known to work.

```<code>$ cd /home/cactus/prog/rust/rust-avr/build/build/x86_64-unknown-linux-gnu/stage1
$ rustup toolchain link avr-toolchain .
$ rustup default avr-toolchain
$ rustc -V
# should say dev channel
</code>```

Body:
Based on this comment, it should be possible to use Xargo to manage the installation of a custom core crate for a particular target. I've tried the following to get it working with a crate that has no other dependency except core:

Cargo.toml: no dependencies listed

[package]
name = "chip8-engine"
version = "0.1.0"
authors = ["Dr. ERDI Gergo <gergo@erdi.hu>"]

[dependencies]

Xargo.toml: my specific source listed for core

[target.avr-atmel-none.dependencies]
core = { git = "https://github.com/gergoerdi/rust-avr-libcore-mini", rev = "adda44aa91ac517aab6915447592ee4cad26564c" }

However, building via xargo build fails as if I was just using cargo:

$ ~/.cargo/bin/xargo build --release -v --target avr-atmel-none
+ "rustc" "--print" "sysroot"
+ "cargo" "build" "--release" "-v" "--target" "avr-atmel-none"
   Compiling chip8-engine v0.1.0 (file:///home/cactus/prog/rust/avr/chip8-engine-avr)
     Running `stage1/bin/rustc --crate-name chip8_engine src/lib.rs --crate-type lib -C opt-level=3 -C metadata=231962fc6e1bee04 -C extra-filename=-231962fc6e1bee04 --out-dir /home/cactus/prog/rust/avr/chip8-engine-avr/target/avr-atmel-none/release/deps --emit=dep-info,link --target avr-atmel-none -L dependency=/home/cactus/prog/rust/avr/chip8-engine-avr/target/avr-atmel-none/release/deps -L dependency=/home/cactus/prog/rust/avr/chip8-engine-avr/target/release/deps`
error[E0463]: can't find crate for `core`
  |
  = note: the `avr-atmel-none` target may not be installed

error: aborting due to previous error

error: Could not compile `chip8-engine`.

Caused by:
  process didn't exit successfully: `stage1/bin/rustc --crate-name chip8_engine src/lib.rs --crate-type lib -C opt-level=3 -C metadata=231962fc6e1bee04 -C extra-filename=-231962fc6e1bee04 --out-dir /home/cactus/prog/rust/avr/chip8-engine-avr/target/avr-atmel-none/release/deps --emit=dep-info,link --target avr-atmel-none -L dependency=/home/cactus/prog/rust/avr/chip8-engine-avr/target/avr-atmel-none/release/deps -L dependency=/home/cactus/prog/rust/avr/chip8-engine-avr/target/release/deps` (exit code: 101)

Note that there's nothing indicating even attempted Git traffic.

In contrast, here's the output of vanilla cargo if I put my core = { git = ...} line in Cargo.toml instead of Xargo.toml, which works as expected:

$ cargo build -v --target=avr-atmel-none --release
   Compiling core v0.1.0 (https://github.com/gergoerdi/rust-avr-libcore-mini?rev=adda44aa91ac517aab6915447592ee4cad26564c#adda44aa)
     Running `stage1/bin/rustc --crate-name core /home/cactus/.cargo/git/checkouts/rust-avr-libcore-mini-37e279d93a70b45a/adda44a/src/lib.rs --crate-type lib -C opt-level=3 -C metadata=47f38a1987c5b284 -C extra-filename=-47f38a1987c5b284 --out-dir /home/cactus/prog/rust/avr/chip8-engine-avr/target/avr-atmel-none/release/deps --emit=dep-info,link --target avr-atmel-none -L dependency=/home/cactus/prog/rust/avr/chip8-engine-avr/target/avr-atmel-none/release/deps -L dependency=/home/cactus/prog/rust/avr/chip8-engine-avr/target/release/deps --cap-lints allow`
   Compiling chip8-engine v0.1.0 (file:///home/cactus/prog/rust/avr/chip8-engine-avr)
     Running `stage1/bin/rustc --crate-name chip8_engine src/lib.rs --crate-type lib -C opt-level=3 -C metadata=231962fc6e1bee04 -C extra-filename=-231962fc6e1bee04 --out-dir /home/cactus/prog/rust/avr/chip8-engine-avr/target/avr-atmel-none/release/deps --emit=dep-info,link --target avr-atmel-none -L dependency=/home/cactus/prog/rust/avr/chip8-engine-avr/target/avr-atmel-none/release/deps -L dependency=/home/cactus/prog/rust/avr/chip8-engine-avr/target/release/deps --extern core=/home/cactus/prog/rust/avr/chip8-engine-avr/target/avr-atmel-none/release/deps/libcore-47f38a1987c5b284.rlib`
    Finished release [optimized] target(s) in 15.21 secs

Body:
It turns out picking up rustc's path from .cargo/config is not currently supported by Xargo, so whatever rustc I want to use need to be installed as a rustup link. To quote the above ticket:

In the meantine you could use rustup to create a custom toolchain that points to your stage1 rustc. That's known to work.

$ cd /home/cactus/prog/rust/rust-avr/build/build/x86_64-unknown-linux-gnu/stage1
$ rustup toolchain link avr-toolchain .
$ rustup default avr-toolchain
$ rustc -V
# should say dev channel


来源: stackexchange

问:
spring MVC - mapping error
I found similar questions asked here but I tried those answers and here I am after spending a day. I dont know what is wrong here I am stuck with my first spring mvc application. If anyone can help me then that will be highly appreciated. I am getting error 404- Not found. Console error - "No mapping found for HTTP request with URI [/FirstSpringMVC/welcome] in DispatcherServlet with name 'mvc-dispatcher'"

Here is my entire code.

pom.xml

```<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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.thomsontech</groupId>
  <artifactId>FirstSpringMVC</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>FirstSpringMVC Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>4.3.8.RELEASE</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework/spring-aop -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aop</artifactId>
        <version>4.3.8.RELEASE</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>4.3.8.RELEASE</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>

  </dependencies>
  <build>
    <finalName>FirstSpringMVC</finalName>
  </build>
</project>
</code>```

web.xml

```<code>        <!DOCTYPE web-app PUBLIC
     "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
     "http://java.sun.com/dtd/web-app_2_3.dtd" >

    <web-app>
      <display-name>Archetype Created Web Application</display-name>

      <servlet>
        <servlet-name>mvc-dispatcher</servlet-name>
            <servlet-class>
                 org.springframework.web.servlet.DispatcherServlet
            </servlet-class>
      </servlet>
      <servlet-mapping>
        <servlet-name>mvc-dispatcher</servlet-name>
            <url-pattern>/</url-pattern>
      </servlet-mapping>
    </web-app>
</code>```

mvc-dispatcher-servlet.xml

```<code>    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">

        <bean id="HandlerMapping" class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping" />

        <context:component-scan base-package="com.thomsontech.controller" />

        <bean id="viewResolver"
            class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
            <property name="prefix">
                <value>/WEB-INF/</value>
            </property>
            <property name="suffix">
                <value>.jsp</value>
            </property>
        </bean>

    </beans>
</code>```

HelloWorldController.java

```<code>    package com.thomsontech.controller;

    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.servlet.ModelAndView;

    @Controller
    public class HelloWorldController {

        @RequestMapping("/welcome")
        public ModelAndView helloWorld() {

            ModelAndView model = new ModelAndView("HelloWorldPage");
            model.addObject("msg", "hello world");

            return model;
        }
    }
</code>```

HelloWorldPage.jsp

```<code>        <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
    <html>
    <body>
        <h1>Spring MVC Hello World Example</h1>

        <h2>${msg}</h2>
    </body>
    </html>
</code>```

答:
Well, have done below changes to your code to fix the 404 issue.

```<code>@Controller
public class HelloWorldController {

    @RequestMapping(value = {"/welcome","/"}, method = RequestMethod.GET)
    public ModelAndView helloWorld() {

        ModelAndView model = new ModelAndView("HelloWorldPage");
        model.addObject("msg", "hello world");

        return model;
    }

}
</code>```

It is almost same as yours except it answers to the requests received on root page("/"). I've just added it to directly test the homepage.

I don't know the reason, the combination of @Controller and <context:component-scan base-package="com.thomsontech.controller" /> weren't creating the helloWorldController bean. So, I had to explicitly create bean by adding <bean id="helloWorldController" class="com.thomsontech.controller.HelloWorldController"></bean> in mvc-dispatcher-servlet.xml file. I also removed <bean id="HandlerMapping" class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/> from the same file as I couldn't see that bean being used anywhere.

So, your final mvc-dispatcher-servlet.xml would be :

```<code><beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <context:component-scan base-package="com.thomsontech.controller" />

    <bean id="helloWorldController" class="com.thomsontech.controller.HelloWorldController"></bean>

    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/WEB-INF/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>

</beans>
</code>```

In your web.xml, have added <load-on-startup>1</load-on-startup> to </servlet> tag, so as to load mvc-dispatcher servlet on startup.
Also, you will have to upgrade of web-app version 2.3 as you are using jstl. JSTL doesn't works only with 2.4+ versions. However, this shouldn't stop you from testing 404 issue. ${msg} in HelloWorldPage jsp will not render "hello world" string returned by the HelloWorldController controller.

Your final web.xml would be :

```<code><web-app>
    <display-name>Archetype Created Web Application</display-name>
    <servlet>
        <servlet-name>mvc-dispatcher</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>mvc-dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>
</code>```

After making these changes, do a cleanup of tomcat/jetty work directory followed by  maven clean install and then run this app on the server.

Hope this helps and good luck!!

ContentLicense: CC BY-SA 3.0

Title: spring MVC - mapping error

Body:
I found similar questions asked here but I tried those answers and here I am after spending a day. I dont know what is wrong here I am stuck with my first spring mvc application. If anyone can help me then that will be highly appreciated. I am getting error 404- Not found. Console error - "No mapping found for HTTP request with URI [/FirstSpringMVC/welcome] in DispatcherServlet with name 'mvc-dispatcher'"

Here is my entire code.

pom.xml

    <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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.thomsontech</groupId>
  <artifactId>FirstSpringMVC</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>FirstSpringMVC Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>4.3.8.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aop</artifactId>
        <version>4.3.8.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>4.3.8.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>

  </dependencies>
  <build>
    <finalName>FirstSpringMVC</finalName>
  </build>
</project>

web.xml

        <!DOCTYPE web-app PUBLIC
     "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
     "http://java.sun.com/dtd/web-app_2_3.dtd" >

    <web-app>
      <display-name>Archetype Created Web Application</display-name>

      <servlet>
        <servlet-name>mvc-dispatcher</servlet-name>
            <servlet-class>
                 org.springframework.web.servlet.DispatcherServlet
            </servlet-class>
      </servlet>
      <servlet-mapping>
        <servlet-name>mvc-dispatcher</servlet-name>
            <url-pattern>/</url-pattern>
      </servlet-mapping>
    </web-app>

mvc-dispatcher-servlet.xml

    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">

        <bean id="HandlerMapping" class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping" />

        <context:component-scan base-package="com.thomsontech.controller" />

        <bean id="viewResolver"
            class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
            <property name="prefix">
                <value>/WEB-INF/</value>
            </property>
            <property name="suffix">
                <value>.jsp</value>
            </property>
        </bean>

    </beans>

HelloWorldController.java

    package com.thomsontech.controller;

    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.servlet.ModelAndView;

    @Controller
    public class HelloWorldController {

        @RequestMapping("/welcome")
        public ModelAndView helloWorld() {

            ModelAndView model = new ModelAndView("HelloWorldPage");
            model.addObject("msg", "hello world");

            return model;
        }
    }

HelloWorldPage.jsp

        <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

Spring MVC Hello World Example

${msg}

Body:
Well, have done below changes to your code to fix the 404 issue.

@Controller
public class HelloWorldController {

    @RequestMapping(value = {"/welcome","/"}, method = RequestMethod.GET)
    public ModelAndView helloWorld() {

        ModelAndView model = new ModelAndView("HelloWorldPage");
        model.addObject("msg", "hello world");

        return model;
    }

}

It is almost same as yours except it answers to the requests received on root page("/"). I've just added it to directly test the homepage.

I don't know the reason, the combination of @Controller and <context:component-scan base-package="com.thomsontech.controller" /> weren't creating the helloWorldController bean. So, I had to explicitly create bean by adding <bean id="helloWorldController" class="com.thomsontech.controller.HelloWorldController"></bean> in mvc-dispatcher-servlet.xml file. I also removed <bean id="HandlerMapping" class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/> from the same file as I couldn't see that bean being used anywhere.

So, your final mvc-dispatcher-servlet.xml would be :

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <context:component-scan base-package="com.thomsontech.controller" />

    <bean id="helloWorldController" class="com.thomsontech.controller.HelloWorldController"></bean>

    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/WEB-INF/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>

</beans>

In your web.xml, have added <load-on-startup>1</load-on-startup> to </servlet> tag, so as to load mvc-dispatcher servlet on startup.
Also, you will have to upgrade of web-app version 2.3 as you are using jstl. JSTL doesn't works only with 2.4+ versions. However, this shouldn't stop you from testing 404 issue. ${msg} in HelloWorldPage jsp will not render "hello world" string returned by the HelloWorldController controller.

Your final web.xml would be :

<web-app>
    <display-name>Archetype Created Web Application</display-name>
    <servlet>
        <servlet-name>mvc-dispatcher</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>mvc-dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

After making these changes, do a cleanup of tomcat/jetty work directory followed by  maven clean install and then run this app on the server.

Hope this helps and good luck!!


问:
What does TensorFlow's `conv2d_transpose()` operation do?
The documentation for the conv2d_transpose() operation does not clearly explain what it does:

The transpose of conv2d.

This operation is sometimes called "deconvolution" after
  Deconvolutional Networks, but is actually the transpose (gradient) of
  conv2d rather than an actual deconvolution.

I went through the paper that the doc points to, but it did not help.

What does this operation do and what are examples of why you would want to use it?

答:
Here's another viewpoint from the "gradients" perspective, i.e. why TensorFlow documentation says conv2d_transpose() is "actually the transpose (gradient) of conv2d rather than an actual deconvolution". For more details on the actual computation done in conv2d_transpose, I would highly recommend this article, starting from page 19.

Four Related Functions

In tf.nn, there are 4 closely related and rather confusing functions for 2d convolution:

tf.nn.conv2d

tf.nn.conv2d_backprop_filter

tf.nn.conv2d_backprop_input

tf.nn.conv2d_transpose

One sentence summary: they are all just 2d convolutions. Their differences are in their input arguments ordering, input rotation or transpose, strides (including fractional stride size), paddings and etc. With tf.nn.conv2d in hand, one can implement all of the 3 other ops by transforming inputs and changing the conv2d arguments.

Problem Settings

Forward and backward computations:

# forward
out = conv2d(x, w)

# backward, given d_out
=> find d_x?
=> find d_w?
```

<p>In the forward computation, we compute the convolution of input image <code>x</code> with the filter <code>w</code>, and the result is <code>out</code>.
In the backward computation, assume we're given <code>d_out</code>, which is the gradient w.r.t. <code>out</code>. Our goal is to find <code>d_x</code> and <code>d_w</code>, which are the gradient w.r.t. <code>x</code> and <code>w</code> respectively.</p>

<p>For the ease of discussion, we assume:</p>

<ul>
<li>All stride size to be <code>1</code></li>
<li>All <code>in_channels</code> and <code>out_channels</code> are <code>1</code></li>
<li>Use <code>VALID</code> padding</li>
<li>Odd number filter size, this avoids some asymmetric shape problem</li>
</ul>

<h3>Short Answer</h3>

<p>Conceptually, with the assumptions above, we have the following relations:</p>

<pre class="lang-py prettyprint-override"><code>out = conv2d(x, w, padding='VALID')
d_x = conv2d(d_out, rot180(w), padding='FULL')
d_w = conv2d(x, d_out, padding='VALID')
</code>```

Where rot180 is a 2d matrix rotated 180 degrees (a left-right flip and a top-down flip), FULL means "apply filter wherever it partly overlaps with the input" (see theano docs). Notes that this is only valid with the above assumptions, however, one can change the conv2d arguments to generalize it.

The key takeaways:

The input gradient d_x is the convolution of the output gradient d_out and the weight w, with some modifications.

The weight gradient d_w is the convolution of the input x and the output gradient d_out, with some modifications.

Long Answer

Now, let's give an actual working code example of how to use the 4 functions above to compute d_x and d_w given d_out. This shows how
conv2d,
conv2d_backprop_filter,
conv2d_backprop_input, and
conv2d_transpose are related to each other.
Please find the full scripts here.

Computing d_x in 4 different ways:

# Method 1: TF's autodiff
d_x = tf.gradients(f, x)[0]

# Method 2: manually using conv2d
d_x_manual = tf.nn.conv2d(input=tf_pad_to_full_conv2d(d_out, w_size),
                          filter=tf_rot180(w),
                          strides=strides,
                          padding='VALID')

# Method 3: conv2d_backprop_input
d_x_backprop_input = tf.nn.conv2d_backprop_input(input_sizes=x_shape,
                                                 filter=w,
                                                 out_backprop=d_out,
                                                 strides=strides,
                                                 padding='VALID')

# Method 4: conv2d_transpose
d_x_transpose = tf.nn.conv2d_transpose(value=d_out,
                                       filter=w,
                                       output_shape=x_shape,
                                       strides=strides,
                                       padding='VALID')
```

<p><strong>Computing <code>d_w</code> in 3 different ways:</strong></p>

<pre class="lang-py prettyprint-override"><code># Method 1: TF's autodiff
d_w = tf.gradients(f, w)[0]

# Method 2: manually using conv2d
d_w_manual = tf_NHWC_to_HWIO(tf.nn.conv2d(input=x,
                                          filter=tf_NHWC_to_HWIO(d_out),
                                          strides=strides,
                                          padding='VALID'))

# Method 3: conv2d_backprop_filter
d_w_backprop_filter = tf.nn.conv2d_backprop_filter(input=x,
                                                   filter_sizes=w_shape,
                                                   out_backprop=d_out,
                                                   strides=strides,
                                                   padding='VALID')
</code>```

Please see the full scripts for the implementation of tf_rot180, tf_pad_to_full_conv2d, tf_NHWC_to_HWIO. In the scripts, we check that the final output values of different methods are the same; a numpy implementation is also available.

Body:
Here's another viewpoint from the "gradients" perspective, i.e. why TensorFlow documentation says conv2d_transpose() is "actually the transpose (gradient) of conv2d rather than an actual deconvolution". For more details on the actual computation done in conv2d_transpose, I would highly recommend this article, starting from page 19.

Four Related Functions

In tf.nn, there are 4 closely related and rather confusing functions for 2d convolution:

tf.nn.conv2d

tf.nn.conv2d_backprop_filter

tf.nn.conv2d_backprop_input

tf.nn.conv2d_transpose

One sentence summary: they are all just 2d convolutions. Their differences are in their input arguments ordering, input rotation or transpose, strides (including fractional stride size), paddings and etc. With tf.nn.conv2d in hand, one can implement all of the 3 other ops by transforming inputs and changing the conv2d arguments.

Problem Settings

Forward and backward computations:

# forward
out = conv2d(x, w)

# backward, given d_out
=> find d_x?
=> find d_w?

In the forward computation, we compute the convolution of input image x with the filter w, and the result is out.
In the backward computation, assume we're given d_out, which is the gradient w.r.t. out. Our goal is to find d_x and d_w, which are the gradient w.r.t. x and w respectively.

For the ease of discussion, we assume:

All stride size to be 1

All in_channels and out_channels are 1

Use VALID padding

Odd number filter size, this avoids some asymmetric shape problem

Short Answer

Conceptually, with the assumptions above, we have the following relations:

out = conv2d(x, w, padding='VALID')
d_x = conv2d(d_out, rot180(w), padding='FULL')
d_w = conv2d(x, d_out, padding='VALID')

Where rot180 is a 2d matrix rotated 180 degrees (a left-right flip and a top-down flip), FULL means "apply filter wherever it partly overlaps with the input" (see theano docs). Notes that this is only valid with the above assumptions, however, one can change the conv2d arguments to generalize it.

The key takeaways:

The input gradient d_x is the convolution of the output gradient d_out and the weight w, with some modifications.

The weight gradient d_w is the convolution of the input x and the output gradient d_out, with some modifications.

Long Answer

Now, let's give an actual working code example of how to use the 4 functions above to compute d_x and d_w given d_out. This shows how
conv2d,
conv2d_backprop_filter,
conv2d_backprop_input, and
conv2d_transpose are related to each other.
Please find the full scripts here.

Computing d_x in 4 different ways:

# Method 1: TF's autodiff
d_x = tf.gradients(f, x)[0]

# Method 2: manually using conv2d
d_x_manual = tf.nn.conv2d(input=tf_pad_to_full_conv2d(d_out, w_size),
                          filter=tf_rot180(w),
                          strides=strides,
                          padding='VALID')

# Method 3: conv2d_backprop_input
d_x_backprop_input = tf.nn.conv2d_backprop_input(input_sizes=x_shape,
                                                 filter=w,
                                                 out_backprop=d_out,
                                                 strides=strides,
                                                 padding='VALID')

# Method 4: conv2d_transpose
d_x_transpose = tf.nn.conv2d_transpose(value=d_out,
                                       filter=w,
                                       output_shape=x_shape,
                                       strides=strides,
                                       padding='VALID')

Computing d_w in 3 different ways:

# Method 1: TF's autodiff
d_w = tf.gradients(f, w)[0]

# Method 2: manually using conv2d
d_w_manual = tf_NHWC_to_HWIO(tf.nn.conv2d(input=x,
                                          filter=tf_NHWC_to_HWIO(d_out),
                                          strides=strides,
                                          padding='VALID'))

# Method 3: conv2d_backprop_filter
d_w_backprop_filter = tf.nn.conv2d_backprop_filter(input=x,
                                                   filter_sizes=w_shape,
                                                   out_backprop=d_out,
                                                   strides=strides,
                                                   padding='VALID')

Please see the full scripts for the implementation of tf_rot180, tf_pad_to_full_conv2d, tf_NHWC_to_HWIO. In the scripts, we check that the final output values of different methods are the same; a numpy implementation is also available.

ContentLicense: CC BY-SA 4.0


问:
How to read the empty cell in a PDF file in ASP.net
I am able to read a pdf file using PDFBOX in my ASP.net application but it is not adding space for an empty cell in a table, So how to read empty fields from a pdf file using PDFBOX in C#. Is there any other method to read the pdf file .

Thanks .

答:
You might be able to pull off this sort of thing if you know exactly where the text should be in advance and can get the locations of the text as you extract it.

If you don't know in advance where the rows and cells are, you'll have to guess based on the text locations.  This will not be easy.

In general, extracting data from PDF is ill advised.  PDFs don't have a concept of "tables" (unless the PDF creator goes well out of there way to use "Marked Content", which is still rare).  PDFs have lines, glyphs, and images (a pile of pixels).  It is Very Hard to extract formatting from that information... and sometimes it is all but impossible.

I don't know if PDFBox will give you the locations of extracted text, but iTextSharp will.

ContentLicense: CC BY-SA 2.5


问:
How do you find the average of three numbers with input and output dialog boxes with JAVA?
I've been playing around with this code for a little bit now and can't seem to find the correct way to sort it out. I used a program without JOptionPane and it worked and tried to use the same sequence but it didn't work. Do I need to add something else? The assignment is to have the user enter 3 integers and print the average with input and output dialog boxes. I've done the average and input/output dialog boxes before but putting it all together is harder than I thought.</p>

```<code>import java.util.Scanner;
import javax.swing.JOptionPane;
import java.text.*;
import java.text.DecimalFormat;
public class Number3
{

  public static void main(String[] args)
  {
    System.out.println("Enter 3 numbers: ");
    Scanner input = new Scanner (System.in);
    DecimalFormat decimalFormat = new DecimalFormat("0.00##");

    int num1;
    int num2;
    int num3;
    double avg;

    num1=input.nextInt();
    num2=input.nextInt();
    num3=input.nextInt();

    avg=(double)(num1+num2+num3)/3.0;
    System.out.println("The average is: " + decimalFormat.format(avg));

  }
}
</code>```

答:
```<code>public static void main(String[] args) {
    int num, count=0;
    double total =0, avg;

    for(int i = 1; i <= 3; i++){
        num = Integer.valueOf(JOptionPane.showInputDialog("Enter number "+ count++));
        total += num;
    }

    avg = total / count;

    JOptionPane.showMessageDialog(null,  "The average is: " + (double)Math.round(avg * 100) / 100);
}
</code>```

Body:
I've been playing around with this code for a little bit now and can't seem to find the correct way to sort it out. I used a program without JOptionPane and it worked and tried to use the same sequence but it didn't work. Do I need to add something else? The assignment is to have the user enter 3 integers and print the average with input and output dialog boxes. I've done the average and input/output dialog boxes before but putting it all together is harder than I thought.

import java.util.Scanner;
import javax.swing.JOptionPane;
import java.text.*;
import java.text.DecimalFormat;
public class Number3
{

  public static void main(String[] args)
  {
    System.out.println("Enter 3 numbers: ");
    Scanner input = new Scanner (System.in);
    DecimalFormat decimalFormat = new DecimalFormat("0.00##");

    int num1;
    int num2;
    int num3;
    double avg;

    num1=input.nextInt();
    num2=input.nextInt();
    num3=input.nextInt();

    avg=(double)(num1+num2+num3)/3.0;
    System.out.println("The average is: " + decimalFormat.format(avg));

  }
}


问:
tidyr::spread() function throws an error
I try to use gather and spread functions in tidyverse package, but it throws an error in spread function

library(caret)

```<code>dataset<-iris

# gather function is to convert wide data to long data

dataset_gather<-dataset %>% tidyr::gather(key=Type,value = Values,1:4)

head(dataset_gather)

# spead is the opposite of gather
</code>```

This code below throws an error like this Error: Duplicate identifiers for rows

```<code>dataset_spead<- dataset_gather%>%tidyr::spread(key = Type,value = Values)
</code>```

答:
We can do this with data.table

```<code>library(data.table)
dcast(melt(setDT(dataset, keep.rownames = TRUE), id.var = c("rn", "Species")), rn + Species ~ variable)
</code>```

Body:
I try to use gather and spread functions in tidyverse package, but it throws an error in spread function

library(caret)

dataset<-iris

# gather function is to convert wide data to long data

dataset_gather<-dataset %>% tidyr::gather(key=Type,value = Values,1:4)

head(dataset_gather)

# spead is the opposite of gather

This code below throws an error like this Error: Duplicate identifiers for rows

dataset_spead<- dataset_gather%>%tidyr::spread(key = Type,value = Values)

Body:
We can do this with data.table

library(data.table)
dcast(melt(setDT(dataset, keep.rownames = TRUE), id.var = c("rn", "Species")), rn + Species ~ variable)


问:
Angular 4 component get selected checkbox
I am new to Angular, and I want to get the current selected checkbox id. I have checked other threads in SO, but most of them are using with Controller, I am using in component.

Here is detailed information.
I have such a component

```<code><table class='table table-striped table-hover admin-form' *ngIf="deviceCategories">
<a (click)="test()">test</a>
<thead>
    <tr>
        <td class="text-center">序列</td>
        <th class="text-center">组名</th>
        <th class="text-center">LOGO</th>
        <th class="text-center">操作</th>
    </tr>
</thead>
<tbody>
    <tr *ngFor="let deviceCategory of deviceCategories | paginate: config">
        <td class="center">
            <input type="checkbox" ng-model="selected[deviceCategory.id]" id="checkbox_{{deviceCategory.id}}">
        </td>
        <td class="text-center">{{deviceCategory.id}}</td>
        <td class="text-center">{{deviceCategory.name}}</td>
        <td class="text-center"><img src="{{deviceCategory.logoUrl}}" width="30" alt=""></td>
        <td class="text-center project-actions">
            <a [routerLink]="['/management/deviceCategory/edit/',deviceCategory.id]" class="btn btn-white btn-xs text-muted"> <i class="fa fa-eye text-system"></i> 修改 </a>
            <a (click)="OnDelete(deviceCategory.id)" class="btn btn-white btn-xs text-muted"> <i class="fa fa-eye text-system"></i> 删除 </a>
        </td>
    </tr>
</tbody>
</code>```

And here is my ts

```<code>import { Component, OnInit, Input } from '@angular/core';
import { PaginationInstance } from 'ng2-pagination';
import { DeviceCategoryService}from '../../../services/deviceCategory.service';
import { DeviceCategoryViewModel } from "../../../model/deviceCategory";

@Component({
  selector: 'app-device-category-admin-table',
  templateUrl: './device-category-admin-table.component.html',
  styleUrls: ['./device-category-admin-table.component.css'],
  providers:[DeviceCategoryService]
})
export class DeviceCategoryAdminTableComponent implements OnInit {

  @Input() deviceCategories :any;
  @Input() config:any;

  public selected:{}

  constructor(
    private deviceCategorySvc:DeviceCategoryService
  ) { }

  ngOnInit() {
  }

  OnDelete(id:number){
      this.deviceCategorySvc.deleteDeviceCategory(id).subscribe(result=>{
          if(result.ok)
          {
            this.deviceCategorySvc.currentCategorys().subscribe(result=>{
              this.deviceCategories=result.data as DeviceCategoryViewModel[];
            });

          }

      });
  }
  test(){
    var result=this.selected;
      console.log(result);
  }
</code>```

Any help would be appreciated.

答:
You can use the [checked] property and bind a variable to it and it should be a boolean value

```<code> <input type="checkbox"  [checked]="deviceCategory.checked"  id="checkbox_{{deviceCategory.id}}"
 />
</code>```

To get the id , you can add a function on (change)="getDeviceID()"

```<code> <input type="checkbox"  (change)="getDeviceID(deviceCategory)" [checked]="deviceCategory.checked"  id="checkbox_{{deviceCategory.id}}"
  />
</code>```

and inside TS

```<code> getDeviceID(device:any) {
      console.log(device.id);
 }
</code>```

Body:
I am new to Angular, and I want to get the current selected checkbox id. I have checked other threads in SO, but most of them are using with Controller, I am using in component.

Here is detailed information.
I have such a component

test

        序列
        组名
        LOGO
        操作

            <input type="checkbox" ng-model="selected[deviceCategory.id]" id="checkbox_{{deviceCategory.id}}">

        {{deviceCategory.id}}
        {{deviceCategory.name}}

              修改
              删除

And here is my ts

import { Component, OnInit, Input } from '@angular/core';
import { PaginationInstance } from 'ng2-pagination';
import { DeviceCategoryService}from '../../../services/deviceCategory.service';
import { DeviceCategoryViewModel } from "../../../model/deviceCategory";

@Component({
  selector: 'app-device-category-admin-table',
  templateUrl: './device-category-admin-table.component.html',
  styleUrls: ['./device-category-admin-table.component.css'],
  providers:[DeviceCategoryService]
})
export class DeviceCategoryAdminTableComponent implements OnInit {

  @Input() deviceCategories :any;
  @Input() config:any;

  public selected:{}

  constructor(
    private deviceCategorySvc:DeviceCategoryService
  ) { }

  ngOnInit() {
  }

  OnDelete(id:number){
      this.deviceCategorySvc.deleteDeviceCategory(id).subscribe(result=>{
          if(result.ok)
          {
            this.deviceCategorySvc.currentCategorys().subscribe(result=>{
              this.deviceCategories=result.data as DeviceCategoryViewModel[];
            });

          }

      });
  }
  test(){
    var result=this.selected;
      console.log(result);
  }

Any help would be appreciated.

Body:
You can use the [checked] property and bind a variable to it and it should be a boolean value

 <input type="checkbox"  [checked]="deviceCategory.checked"  id="checkbox_{{deviceCategory.id}}"
 />

To get the id , you can add a function on (change)="getDeviceID()"

 <input type="checkbox"  (change)="getDeviceID(deviceCategory)" [checked]="deviceCategory.checked"  id="checkbox_{{deviceCategory.id}}"
  />

and inside TS

 getDeviceID(device:any) {
      console.log(device.id);
 }


问:
Including Delphi Type Libraries in repository (SVN)?
What is the best way to save a Delphi Type Library in SVN.

The file changes every time you compile the Application

The file is not saved in a readable form of  AscII

It is very difficult to work out what changes have been made from one version to the next

This is a  major problem when more than one person is changing the file

QUESTIONS:

1) Should one save an exported ‘IDL’ file in the version control ?

2) Can one covert an ‘IDL ’ into a Delphi type library If so how ?

3) What are the best practices when working with a Delphi type library ?

4) How easy is it get rid of the type library in Delphi2009 datasnap project?

p.s. I am using BDS2006

答: In Delphi 2009, this has changed completely. Type libraries are now saved in the project as plain text, RIDL files. These will play nice with source control. DataSnap is also completely changed; you can read about it here, and see a screencast here.</p>

OwnerDisplayName: Charles Faiga

LastEditorDisplayName: Charles Faiga

OwnerDisplayName: Craig Stuntz


问:
Laravel 5.4 session is not being set if dd method is used
I am using laravel 5.4. In a method of a controller I have setting a value in session. If I call the dd() right after setting the session the dd() is showing all the session with the session I have just set. But if I fetch the session from another method the session is not available. If I remove the dd() from session setter method, I am getting the session properly.

My Code is as below:

```<code>public class TestController{
  public function setSession(){
    session(['test_key' => 'test_value']);//setting up the session
    dd(session()->all());//getting the session properly here
  }

  public function showSession(){
    dd(session()->all());//Here we are not getting the session
  }
}
</code>```

If we remove the dd() from setSession() session it works properly.  Is it a bug of Laravel or it's intentional. I am interested to know the root cause of this fact. Thanks

答: dd() means "dump & die" and uses die() in its implementation, which immediately terminates the framework and does not allow Laravel to correctly complete the request and save the session. You can use dump() to display information like dd() does and do not shut down the kernel after.

Body:
I am using laravel 5.4. In a method of a controller I have setting a value in session. If I call the dd() right after setting the session the dd() is showing all the session with the session I have just set. But if I fetch the session from another method the session is not available. If I remove the dd() from session setter method, I am getting the session properly.

My Code is as below:

public class TestController{
  public function setSession(){
    session(['test_key' => 'test_value']);//setting up the session
    dd(session()->all());//getting the session properly here
  }

  public function showSession(){
    dd(session()->all());//Here we are not getting the session
  }
}

If we remove the dd() from setSession() session it works properly.  Is it a bug of Laravel or it's intentional. I am interested to know the root cause of this fact. Thanks


问:
JavaScript - Search object property by key and add its value to array
Let's say I have an object like this:

```<code>var object =  {
  "Defender": {
    "player-1868": {
      "birthdate": "1 July 1996",
      "club_country": "IQ",
      "club_id": 171,
      "club_name": "Erbil",
      "forename": "Burhan Jumaah",
      "id": 1868,
      "league_id": 12,
      "league_name": "Iraqi Premier League",
      "name": "Burhan Jumaah",
      "nationality": "iq",
      "nationality_full": "Iraq",
      "position": "Defender",
      "surname": "Razzaq",
      "votes": [
        "y884F42mLCVdld5V5cMeRpl11gJ2"
      ]
    }
  },
  "Goalkeeper": {
    "player-3076": {
      "birthdate": "15 December 1985",
      "club_country": "QA",
      "club_id": 1,
      "club_name": "Lekhwiya",
      "comments": [
        {
          "comment": "xxx",
          "name": "guy tester",
          "photoURL": "http://pbs.twimg.com/profile_images/855450315704979460/RGiq07D7_normal.jpg",
          "time": 1496529030321,
          "user": "y884F42mLCVdld5V5cMeRpl11gJ2"
        }
      ],
      "forename": "Qasem Abdulhamed",
      "id": 3076,
      "league_id": 1,
      "league_name": "Qatar Stars League",
      "name": "Qasem Burhan",
      "nationality": "qa",
      "nationality_full": "Qatar",
      "position": "Goalkeeper",
      "surname": "Burhan",
      "votes": [
        "y884F42mLCVdld5V5cMeRpl11gJ2"
      ]
    },
    "player-3532": {
      "birthdate": "2 April 1992",
      "club_country": "SA",
      "club_id": 18,
      "club_name": "Al Ittihad",
      "forename": "Fawaz",
      "id": 3532,
      "league_id": 2,
      "league_name": "Saudi Professional League",
      "name": "Fawaz Al Qarni",
      "nationality": "sa",
      "nationality_full": "Saudi Arabia",
      "position": "Goalkeeper",
      "surname": "Al Qarni",
      "votes": [
        "y884F42mLCVdld5V5cMeRpl11gJ2"
      ]
    }
  }
};
</code>```

How would I, using lodash, traverse through this object and add every time the property id appears inside an object key of player-xxxxxx, add that value to an array. Essentially, getting all of the player IDs in a single array?

答:
With Javascript, to traverse the keys and get each id, you may use "for" like below sample code:</p>

```<code>var obj =  {
  "Defender": {
    "player-1868": {
      "birthdate": "1 July 1996",
      "club_country": "IQ",
      "club_id": 171,
      "club_name": "Erbil",
      "forename": "Burhan Jumaah",
      "id": 1868,
      "league_id": 12,
      "league_name": "Iraqi Premier League",
      "name": "Burhan Jumaah",
      "nationality": "iq",
      "nationality_full": "Iraq",
      "position": "Defender",
      "surname": "Razzaq",
      "votes": [
        "y884F42mLCVdld5V5cMeRpl11gJ2"
      ]
    }
  },
  "Goalkeeper": {
    "player-3076": {
      "birthdate": "15 December 1985",
      "club_country": "QA",
      "club_id": 1,
      "club_name": "Lekhwiya",
      "comments": [
        {
          "comment": "xxx",
          "name": "guy tester",
          "photoURL": "http://pbs.twimg.com/profile_images/855450315704979460/RGiq07D7_normal.jpg",
          "time": 1496529030321,
          "user": "y884F42mLCVdld5V5cMeRpl11gJ2"
        }
      ],
      "forename": "Qasem Abdulhamed",
      "id": 3076,
      "league_id": 1,
      "league_name": "Qatar Stars League",
      "name": "Qasem Burhan",
      "nationality": "qa",
      "nationality_full": "Qatar",
      "position": "Goalkeeper",
      "surname": "Burhan",
      "votes": [
        "y884F42mLCVdld5V5cMeRpl11gJ2"
      ]
    },
    "player-3532": {
      "birthdate": "2 April 1992",
      "club_country": "SA",
      "club_id": 18,
      "club_name": "Al Ittihad",
      "forename": "Fawaz",
      "id": 3532,
      "league_id": 2,
      "league_name": "Saudi Professional League",
      "name": "Fawaz Al Qarni",
      "nationality": "sa",
      "nationality_full": "Saudi Arabia",
      "position": "Goalkeeper",
      "surname": "Al Qarni",
      "votes": [
        "y884F42mLCVdld5V5cMeRpl11gJ2"
      ]
    }
  }
};

var arr = [];
tgtObj = obj["Defender"];
for(var key in tgtObj){
    if (tgtObj.hasOwnProperty(key)){
    console.log(key);
    arr.push(tgtObj[key]["id"]);
  }
}
tgtObj = obj["Goalkeeper"];
for(var key in tgtObj){
    if (tgtObj.hasOwnProperty(key)){
    console.log(key);
    arr.push(tgtObj[key]["id"]);
  }
}
console.log(arr);
</code>```

Body:
Let's say I have an object like this:

var object =  {
  "Defender": {
    "player-1868": {
      "birthdate": "1 July 1996",
      "club_country": "IQ",
      "club_id": 171,
      "club_name": "Erbil",
      "forename": "Burhan Jumaah",
      "id": 1868,
      "league_id": 12,
      "league_name": "Iraqi Premier League",
      "name": "Burhan Jumaah",
      "nationality": "iq",
      "nationality_full": "Iraq",
      "position": "Defender",
      "surname": "Razzaq",
      "votes": [
        "y884F42mLCVdld5V5cMeRpl11gJ2"
      ]
    }
  },
  "Goalkeeper": {
    "player-3076": {
      "birthdate": "15 December 1985",
      "club_country": "QA",
      "club_id": 1,
      "club_name": "Lekhwiya",
      "comments": [
        {
          "comment": "xxx",
          "name": "guy tester",
          "photoURL": "http://pbs.twimg.com/profile_images/855450315704979460/RGiq07D7_normal.jpg",
          "time": 1496529030321,
          "user": "y884F42mLCVdld5V5cMeRpl11gJ2"
        }
      ],
      "forename": "Qasem Abdulhamed",
      "id": 3076,
      "league_id": 1,
      "league_name": "Qatar Stars League",
      "name": "Qasem Burhan",
      "nationality": "qa",
      "nationality_full": "Qatar",
      "position": "Goalkeeper",
      "surname": "Burhan",
      "votes": [
        "y884F42mLCVdld5V5cMeRpl11gJ2"
      ]
    },
    "player-3532": {
      "birthdate": "2 April 1992",
      "club_country": "SA",
      "club_id": 18,
      "club_name": "Al Ittihad",
      "forename": "Fawaz",
      "id": 3532,
      "league_id": 2,
      "league_name": "Saudi Professional League",
      "name": "Fawaz Al Qarni",
      "nationality": "sa",
      "nationality_full": "Saudi Arabia",
      "position": "Goalkeeper",
      "surname": "Al Qarni",
      "votes": [
        "y884F42mLCVdld5V5cMeRpl11gJ2"
      ]
    }
  }
};

How would I, using lodash, traverse through this object and add every time the property id appears inside an object key of player-xxxxxx, add that value to an array. Essentially, getting all of the player IDs in a single array?

Body:
With Javascript, to traverse the keys and get each id, you may use "for" like below sample code:

var obj =  {
  "Defender": {
    "player-1868": {
      "birthdate": "1 July 1996",
      "club_country": "IQ",
      "club_id": 171,
      "club_name": "Erbil",
      "forename": "Burhan Jumaah",
      "id": 1868,
      "league_id": 12,
      "league_name": "Iraqi Premier League",
      "name": "Burhan Jumaah",
      "nationality": "iq",
      "nationality_full": "Iraq",
      "position": "Defender",
      "surname": "Razzaq",
      "votes": [
        "y884F42mLCVdld5V5cMeRpl11gJ2"
      ]
    }
  },
  "Goalkeeper": {
    "player-3076": {
      "birthdate": "15 December 1985",
      "club_country": "QA",
      "club_id": 1,
      "club_name": "Lekhwiya",
      "comments": [
        {
          "comment": "xxx",
          "name": "guy tester",
          "photoURL": "http://pbs.twimg.com/profile_images/855450315704979460/RGiq07D7_normal.jpg",
          "time": 1496529030321,
          "user": "y884F42mLCVdld5V5cMeRpl11gJ2"
        }
      ],
      "forename": "Qasem Abdulhamed",
      "id": 3076,
      "league_id": 1,
      "league_name": "Qatar Stars League",
      "name": "Qasem Burhan",
      "nationality": "qa",
      "nationality_full": "Qatar",
      "position": "Goalkeeper",
      "surname": "Burhan",
      "votes": [
        "y884F42mLCVdld5V5cMeRpl11gJ2"
      ]
    },
    "player-3532": {
      "birthdate": "2 April 1992",
      "club_country": "SA",
      "club_id": 18,
      "club_name": "Al Ittihad",
      "forename": "Fawaz",
      "id": 3532,
      "league_id": 2,
      "league_name": "Saudi Professional League",
      "name": "Fawaz Al Qarni",
      "nationality": "sa",
      "nationality_full": "Saudi Arabia",
      "position": "Goalkeeper",
      "surname": "Al Qarni",
      "votes": [
        "y884F42mLCVdld5V5cMeRpl11gJ2"
      ]
    }
  }
};

var arr = [];
tgtObj = obj["Defender"];
for(var key in tgtObj){
    if (tgtObj.hasOwnProperty(key)){
    console.log(key);
    arr.push(tgtObj[key]["id"]);
  }
}
tgtObj = obj["Goalkeeper"];
for(var key in tgtObj){
    if (tgtObj.hasOwnProperty(key)){
    console.log(key);
    arr.push(tgtObj[key]["id"]);
  }
}
console.log(arr);


问:
Is performing .ToList() more than once is a bad idea?
I've written the below function to query the SQLite DB in my Xamarin forms app. But, since I have to call .ToList() twice, I'm not very confident about it. Is this bad code? Any feedback will be highly appreciated.

```<code>public static List<string> GetAllLocationIds()
    {
        try
        {
            lock (CollisionLock)
            {
               //TableQuery<TResult> First .ToList() result
               //List<string> Second .ToList() result
                return Database.Table<Location>().ToList().Select(loc=>loc.LocationId).ToList();
            }
        }
        catch (Exception ex)
        {
            Insights.Report(ex);
            return null;
        }
    }
</code>```

Performing .Select directly on  Database.Table<Location>() results in the following exception.`

```<code>System.MissingMethodException: Default constructor not found for type
System.String at System.RuntimeType.CreateInstanceMono`
</code>```

答:
You just can not do Linq projections to string types like that with sqlite-net(-pcl) as it needs a default parameterless constructor.

What follows is the "best way" simulate a "Linq projection" that I have found when Mobile memory and performance is considered.

Use a custom Class with only the columns that need projected

Use a SQL query with only the columns needed to map to that custom class (where filter in the select statement if needed)

Convert to custom type

Actual Table Class:

```<code>class Location
{
    [PrimaryKey]
    public int Column1 { get; set; }
    public int Column2 { get; set; }
    ~~~
    public string LocationId { get; set; }
}
</code>```

Now make a new class that describes your "projection" needs, in this case I only want the LocationId column.

Projection Class

```<code>class SimpleList
{
    public string LocationId { get; set; }
}
</code>```

SQL Select (selecting only the columns that map to the projection class)

```<code>SQLiteConnection.Query<SimpleList>("select LocationId from [Location]")
</code>```

Now you have a List<SimpleList>, you can convert it to a List<string> if you really need to:

```<code>SQLiteConnection.Query<SimpleList>("select LocationId from [Location]").ConvertAll(x => x.LocationId);
</code>```

Is it worth it? If you have a large number of rows and/or columns in your table and cannot use a deferred query and/or avoid a Linq projection... IMHO yes... Use the profiler to confirm ;-)

If you have a couple dozen rows? Maybe not, but even then the number of temp. objects that get instanced is reduced, and for me that is a win on mobile.

Body:
I've written the below function to query the SQLite DB in my Xamarin forms app. But, since I have to call .ToList() twice, I'm not very confident about it. Is this bad code? Any feedback will be highly appreciated.

public static List<string> GetAllLocationIds()
    {
        try
        {
            lock (CollisionLock)
            {
               //TableQuery<TResult> First .ToList() result
               //List<string> Second .ToList() result
                return Database.Table<Location>().ToList().Select(loc=>loc.LocationId).ToList();
            }
        }
        catch (Exception ex)
        {
            Insights.Report(ex);
            return null;
        }
    }

Performing .Select directly on  Database.Table<Location>() results in the following exception.`

System.MissingMethodException: Default constructor not found for type
System.String at System.RuntimeType.CreateInstanceMono`

Body:
You just can not do Linq projections to string types like that with sqlite-net(-pcl) as it needs a default parameterless constructor.

What follows is the "best way" simulate a "Linq projection" that I have found when Mobile memory and performance is considered.

Use a custom Class with only the columns that need projected

Use a SQL query with only the columns needed to map to that custom class (where filter in the select statement if needed)

Convert to custom type

Actual Table Class:

class Location
{
    [PrimaryKey]
    public int Column1 { get; set; }
    public int Column2 { get; set; }
    ~~~
    public string LocationId { get; set; }
}

Now make a new class that describes your "projection" needs, in this case I only want the LocationId column.

Projection Class

class SimpleList
{
    public string LocationId { get; set; }
}

SQL Select (selecting only the columns that map to the projection class)

SQLiteConnection.Query<SimpleList>("select LocationId from [Location]")

Now you have a List<SimpleList>, you can convert it to a List<string> if you really need to:

SQLiteConnection.Query<SimpleList>("select LocationId from [Location]").ConvertAll(x => x.LocationId);

Is it worth it? If you have a large number of rows and/or columns in your table and cannot use a deferred query and/or avoid a Linq projection... IMHO yes... Use the profiler to confirm ;-)

If you have a couple dozen rows? Maybe not, but even then the number of temp. objects that get instanced is reduced, and for me that is a win on mobile.


问:
AVPlayer currentTime is negative value
I'm using AVPlayer to playing audio files.

But AVPlayer current Time is negative value at start time.

When I use seek(to: time) method to move specific time, AVPlayer play about 0.1 seconds before the specific time. (exactly 0.04~0.08)

Does anyone know this issue?

答:
You're using the wrong seek method. Use a seek method where you define a tolerance of 0, so it seeks accurately.

Documentation for: seek(to:toleranceBefore:toleranceAfter:)

Here's some swift example code to seek to 100 second:

```<code>avPlayer.seek(to: someCMTime, toleranceBefore: kCMTimeZero, toleranceAfter: kCMTimeZero)
</code>```

Title: AVPlayer currentTime is negative value

Body:
You're using the wrong seek method. Use a seek method where you define a tolerance of 0, so it seeks accurately.

Documentation for: seek(to:toleranceBefore:toleranceAfter:)

Here's some swift example code to seek to 100 second:

avPlayer.seek(to: someCMTime, toleranceBefore: kCMTimeZero, toleranceAfter: kCMTimeZero)


问:
How to find files with same size?
I have a file structure like so

```<code>a/file1
a/file2
a/file3
a/...
b/file1
b/file2
b/file3
b/...
...
</code>```

where within each dir, some files have the same file size, and I would like to delete those.

I guess if the problem could be solved for one dir e.g. dir a, then I could wrap a for-loop around it?

```<code>for f in *; do
???
done
</code>```

But how do I find files with same size?

答:
Based on the accepted answer, the following provides a list of all the files of the same size in the current directory (so you can choose which one to keep), sorted by size:

```<code>for FILE in *; do stat -c"%s/%n" "$FILE"; done | awk -F/ '{if ($1 in a)print a[$1]"\n"$2; else a[$1]=$2}' | sort -u | tr '\n' '\0' | xargs -0 ls -lS
</code>```

To determine if the files are actually the same, not just the contain the same number of bytes, do an shasum or md5sum on each file:

```<code>for FILE in *; do stat -c"%s/%n" "$FILE"; done | awk -F/ '{if ($1 in a)print a[$1]"\n"$2; else a[$1]=$2}' | sort -u | tr '\n' '\0' | xargs -0 -n1 shasum
</code>```

Title: How to find files with same size?

Body:
I have a file structure like so

a/file1
a/file2
a/file3
a/...
b/file1
b/file2
b/file3
b/...
...

where within each dir, some files have the same file size, and I would like to delete those.

I guess if the problem could be solved for one dir e.g. dir a, then I could wrap a for-loop around it?

for f in *; do
???
done

But how do I find files with same size?

Body:
Based on the accepted answer, the following provides a list of all the files of the same size in the current directory (so you can choose which one to keep), sorted by size:

for FILE in *; do stat -c"%s/%n" "$FILE"; done | awk -F/ '{if ($1 in a)print a[$1]"\n"$2; else a[$1]=$2}' | sort -u | tr '\n' '\0' | xargs -0 ls -lS

To determine if the files are actually the same, not just the contain the same number of bytes, do an shasum or md5sum on each file:

for FILE in *; do stat -c"%s/%n" "$FILE"; done | awk -F/ '{if ($1 in a)print a[$1]"\n"$2; else a[$1]=$2}' | sort -u | tr '\n' '\0' | xargs -0 -n1 shasum


问:
TCGAbiolinks: GDCprepare Function Issue
I am planning to use TCGAbiolinks to Prepare expression matrix.And I am trying to run the PAADRnaseqSE <- GDCprepare(query_RNA_Seq) function after I have downloaded the Gene expression quantification data, but every time I run the function, it produces the error message as follow:

```<code>> PAADRnaseqSE <- GDCprepare(query_RNA_Seq)
  |=================================================================================================================================| 100%
Downloading genome information (try:0) Using: Homo sapiens genes (GRCh37.p13)
Starting to add information to samples
 => Add clinical information to samples
Error: lexical error: invalid char in json text.
                                       <?xml version="1.0" ?> <respons
                     (right here) ------^
</code>```

Anything I can do to solve the problem?

答:
Try updating the package:

```<code>devtools::install_github(repo = "BioinformaticsFMRP/TCGAbiolinks")
</code>```

If that does not work, there is also another branch with a different code (using this package https://github.com/Bioconductor/GenomicDataCommons). Could you try installing it and see if the bug persists?

```<code>devtools::install_github(repo = "BioinformaticsFMRP/TCGAbiolinks",ref = "GenomicDataCommons" )
</code>```

Title: TCGAbiolinks: GDCprepare Function Issue

Body:
I am planning to use TCGAbiolinks to Prepare expression matrix.And I am trying to run the PAADRnaseqSE <- GDCprepare(query_RNA_Seq) function after I have downloaded the Gene expression quantification data, but every time I run the function, it produces the error message as follow:

> PAADRnaseqSE <- GDCprepare(query_RNA_Seq)
  |=================================================================================================================================| 100%
Downloading genome information (try:0) Using: Homo sapiens genes (GRCh37.p13)
Starting to add information to samples
 => Add clinical information to samples
Error: lexical error: invalid char in json text.
                                       <?xml version="1.0" ?> <respons
                     (right here) ------^

Anything I can do to solve the problem?

Body:
Try updating the package:

devtools::install_github(repo = "BioinformaticsFMRP/TCGAbiolinks")

If that does not work, there is also another branch with a different code (using this package https://github.com/Bioconductor/GenomicDataCommons). Could you try installing it and see if the bug persists?

devtools::install_github(repo = "BioinformaticsFMRP/TCGAbiolinks",ref = "GenomicDataCommons" )


问:
which is better? using cd and execute or using absolute path?
Suppose I would like to do some operation like touch/rmetc  on a specific directory in shell script.
Firstly, I can do cd to that directory and do it.
Secondly, I can use absolute path to do that.

My question is which one will be better in performance perspective? Which one is faster?

答: Depends on what directory you want to access,ie. if the path is too long,the fastest would be absolute path method,whereas it would make no sense to use the path for something in the immediate next directory.</p>


问:
How to detect build server runs?
As described in the blog post THE 7 SCREENSHOTS OF IOS with an IOS build a Codename One app is run on the build server to create screen shots for the possible resolutions of devices.

I would like to detect whether the app runs on the build server. Is that possible and what way of detecting that would You recommend?

答: I would suggest enclosing screenshots in the native iOS directory as explained in this developer guide section. It would probably be the simplest solution.</p>

Title: How to detect build server runs?


问:
Is AsyncTask really conceptually flawed or am I just missing something?
I have investigated this problem for months now, came up with different solutions to it, which I am not happy with since they are all massive hacks. I still cannot believe that a class that flawed in design made it into the framework and no-one is talking about it, so I guess I just must be missing something.

The problem is with AsyncTask. According to the documentation it

"allows to perform background
  operations and publish results on the
  UI thread without having to manipulate
  threads and/or handlers."

The example then continues to show how some exemplary showDialog() method is called in onPostExecute(). This, however, seems entirely contrived to me, because showing a dialog always needs a reference to a valid Context, and an AsyncTask must never hold a strong reference to a context object.

The reason is obvious: what if the activity gets destroyed which triggered the task? This can happen all the time, e.g. because you flipped the screen. If the task would hold a reference to the context that created it, you're not only holding on to a useless context object (the window will have been destroyed and any UI interaction will fail with an exception!), you even risk creating a memory leak.

Unless my logic is flawed here, this translates to: onPostExecute() is entirely useless, because what good is it for this method to run on the UI thread if you don't have access to any context? You can't do anything meaningful here.

One workaround would be to not pass context instances to an AsyncTask, but a Handler instance. That works: since a Handler loosely binds the context and the task, you can exchange messages between them without risking a leak (right?). But that would mean that the premise of AsyncTask, namely that you don't need to bother with handlers, is wrong. It also seems like abusing Handler, since you are sending and receiving messages on the same thread (you create it on the UI thread and send through it in onPostExecute() which is also executed on the UI thread).

To top it all off, even with that workaround, you still have the problem that when the context gets destroyed, you have no record of the tasks it fired. That means that you have to re-start any tasks when re-creating the context, e.g. after a screen orientation change. This is slow and wasteful.

My solution to this (as implemented in the Droid-Fu library) is to maintain a mapping of WeakReferences from component names to their current instances on the unique application object. Whenever an AsyncTask is started, it records the calling context in that map, and on every callback, it will fetch the current context instance from that mapping. This ensures that you will never reference a stale context instance and you always have access to a valid context in the callbacks so you can do meaningful UI work there. It also doesn't leak, because the references are weak and are cleared when no instance of a given component exists anymore.

Still, it is a complex workaround and requires to sub-class some of the Droid-Fu library classes, making this a pretty intrusive approach.

Now I simply want to know: Am I just massively missing something or is AsyncTask really entirely flawed? How are your experiences working with it? How did you solve these problem?

Thanks for your input.

答:
I thought cancel works but it doesn't.

here they RTFMing about it:

""If the task has already started, then the mayInterruptIfRunning
parameter determines whether the thread executing this task should be
interrupted in an attempt to stop the task."

That does not imply, however, that the thread is interruptible. That's a
Java thing, not an AsyncTask thing."

http://groups.google.com/group/android-developers/browse_thread/thread/dcadb1bc7705f1bb/add136eb4949359d?show_docid=add136eb4949359d


问:
pandas: filter rows of DataFrame with operator chaining
Most operations in pandas can be accomplished with operator chaining (groupby, aggregate, apply, etc), but the only way I've found to filter rows is via normal bracket indexing

```<code>df_filtered = df[df['column'] == value]
</code>```

This is unappealing as it requires I assign df to a variable before being able to filter on its values.  Is there something more like the following?

```<code>df_filtered = df.mask(lambda x: x['column'] == value)
</code>```

答:
I offer this for additional examples.  This is the same answer as https://stackoverflow.com/a/28159296/

I'll add other edits to make this post more useful.

pandas.DataFrame.query

query was made for exactly this purpose.  Consider the dataframe df

```<code>import pandas as pd
import numpy as np

np.random.seed([3,1415])
df = pd.DataFrame(
    np.random.randint(10, size=(10, 5)),
    columns=list('ABCDE')
)

df

   A  B  C  D  E
0  0  2  7  3  8
1  7  0  6  8  6
2  0  2  0  4  9
3  7  3  2  4  3
4  3  6  7  7  4
5  5  3  7  5  9
6  8  7  6  4  7
7  6  2  6  6  5
8  2  8  7  5  8
9  4  7  6  1  5
</code>```

Let's use query to filter all rows where D > B

```<code>df.query('D > B')

   A  B  C  D  E
0  0  2  7  3  8
1  7  0  6  8  6
2  0  2  0  4  9
3  7  3  2  4  3
4  3  6  7  7  4
5  5  3  7  5  9
7  6  2  6  6  5
</code>```

Which we chain

```<code>df.query('D > B').query('C > B')
# equivalent to
# df.query('D > B and C > B')
# but defeats the purpose of demonstrating chaining

   A  B  C  D  E
0  0  2  7  3  8
1  7  0  6  8  6
4  3  6  7  7  4
5  5  3  7  5  9
7  6  2  6  6  5
</code>```

Body:
Most operations in pandas can be accomplished with operator chaining (groupby, aggregate, apply, etc), but the only way I've found to filter rows is via normal bracket indexing

df_filtered = df[df['column'] == value]

This is unappealing as it requires I assign df to a variable before being able to filter on its values.  Is there something more like the following?

df_filtered = df.mask(lambda x: x['column'] == value)

Body:
I offer this for additional examples.  This is the same answer as https://stackoverflow.com/a/28159296/

I'll add other edits to make this post more useful.

pandas.DataFrame.query

query was made for exactly this purpose.  Consider the dataframe df

import pandas as pd
import numpy as np

np.random.seed([3,1415])
df = pd.DataFrame(
    np.random.randint(10, size=(10, 5)),
    columns=list('ABCDE')
)

df

   A  B  C  D  E
0  0  2  7  3  8
1  7  0  6  8  6
2  0  2  0  4  9
3  7  3  2  4  3
4  3  6  7  7  4
5  5  3  7  5  9
6  8  7  6  4  7
7  6  2  6  6  5
8  2  8  7  5  8
9  4  7  6  1  5

Let's use query to filter all rows where D > B

df.query('D > B')

   A  B  C  D  E
0  0  2  7  3  8
1  7  0  6  8  6
2  0  2  0  4  9
3  7  3  2  4  3
4  3  6  7  7  4
5  5  3  7  5  9
7  6  2  6  6  5

Which we chain

df.query('D > B').query('C > B')
# equivalent to
# df.query('D > B and C > B')
# but defeats the purpose of demonstrating chaining

   A  B  C  D  E
0  0  2  7  3  8
1  7  0  6  8  6
4  3  6  7  7  4
5  5  3  7  5  9
7  6  2  6  6  5


问:
How to skip certain database tables with mysqldump?
Is there a way to restrict certain tables from the mysqldump command?

For example, I'd use the following syntax to dump only table1 and table2:

```<code>mysqldump -u username -p database table1 table2 > database.sql
</code>```

But is there a similar way to dump all the tables except table1 and table2? I haven't found anything in the mysqldump documentation, so is brute-force (specifying all the table names) the only way to go?

答:
Another example for ignoring multiple tables

```<code>/usr/bin/mysqldump -uUSER -pPASS --ignore-table={db_test.test1,db_test.test3} db_test> db_test.sql
</code>```

using --ignore-table and create an array of tables, with syntaxs like

```<code>--ignore-table={db_test.table1,db_test.table3,db_test.table4}
</code>```

Extra:

Import database

```<code> # if file is .sql
 mysql -uUSER  -pPASS db_test < backup_database.sql
 # if file is .sql.gz
 gzip -dc < backup_database.sql.gz | mysql -uUSER -pPASSWORD db_test
</code>```

Simple script to ignore tables and export in .sql.gz to save space

```<code>#!/bin/bash

#tables to ignore
_TIGNORE=(
my_database.table1
my_database.table2
my_database.tablex
)

#create text for ignore tables
_TDELIMITED="$(IFS=" "; echo "${_TIGNORE[*]/#/--ignore-table=}")"

#don't forget to include user and password
/usr/bin/mysqldump -uUSER -pPASSWORD --events ${_TDELIMITED} --databases my_database | gzip -v > backup_database.sql.gz
</code>```

Links with information that will help you

mysqldump & gzip

mysqldump to a tar.gz

How do I load a sql.gz file to my database?

Note: tested in ubuntu server with mysql Ver 14.14 Distrib 5.5.55

OwnerDisplayName: Zac

Body:
Is there a way to restrict certain tables from the mysqldump command?

For example, I'd use the following syntax to dump only table1 and table2:

mysqldump -u username -p database table1 table2 > database.sql

But is there a similar way to dump all the tables except table1 and table2? I haven't found anything in the mysqldump documentation, so is brute-force (specifying all the table names) the only way to go?

Body:
Another example for ignoring multiple tables

/usr/bin/mysqldump -uUSER -pPASS --ignore-table={db_test.test1,db_test.test3} db_test> db_test.sql

using --ignore-table and create an array of tables, with syntaxs like

--ignore-table={db_test.table1,db_test.table3,db_test.table4}

Extra:

Import database

 # if file is .sql
 mysql -uUSER  -pPASS db_test < backup_database.sql
 # if file is .sql.gz
 gzip -dc < backup_database.sql.gz | mysql -uUSER -pPASSWORD db_test

Simple script to ignore tables and export in .sql.gz to save space

#!/bin/bash

#tables to ignore
_TIGNORE=(
my_database.table1
my_database.table2
my_database.tablex
)

#create text for ignore tables
_TDELIMITED="$(IFS=" "; echo "${_TIGNORE[*]/#/--ignore-table=}")"

#don't forget to include user and password
/usr/bin/mysqldump -uUSER -pPASSWORD --events ${_TDELIMITED} --databases my_database | gzip -v > backup_database.sql.gz

Links with information that will help you

mysqldump & gzip

mysqldump to a tar.gz

How do I load a sql.gz file to my database?

Note: tested in ubuntu server with mysql Ver 14.14 Distrib 5.5.55


问:
Conditional statement for routing in resolve angular 2 - fetch before navigating
I have an app as follows.

User fills in a form (route is ' ')

Submits the form

Data is sent off to a REST api

Data is receive - On a good response (200) the page is routed to an overview  page containing the response. (route is 'overview') On a (400) it currently fails silently.

I've used a resolve for this as I want to wait until data is received before routing. The above works ok but..

What I want is to add the following functionality in part 4.

When a 400 or non 200 error is received I want to display an error and ensure the route is ' '.

My reason for wanting to add some conditional logic in was that I saw it as a demo in the angular docs. fetch before navigating

I have the following code so far.

App component

```<code>const routes: Routes = [
  {
    path: '',
    component:  RegistrationComponent,
  },
  {
    path: 'overview',
    component: ConfirmationComponent,
    resolve: {
        data: RegistrationResolve
    }
  }
]
</code>```

Form component

```<code>export class RegistrationComponent implements OnInit {

  constructor(
    private router: Router,
    private regService: RegistrationService,
    private route: ActivatedRoute
  ){}

  onSubmit(event: RegDetails){
    this.handleView();
  }

  handleView(){
    this.router.navigate(['/overview']);
  }
}
</code>```

Overview component

```<code>export class ConfirmationComponent implements OnInit {

  constructor(
    private router: Router,
    private route: ActivatedRoute
  ) {}

  ngOnInit(){
    this.route.data
    .subscribe(val => {
      this.resolvedData = val["data"];
    });
  }
}
</code>```

Resolve

```<code>export class RegistrationResolve implements Resolve<any> {

  constructor(
    private regService: RegistrationService,
    private router: Router
  ) {}

  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {

    return this.regService.postDummy('apple');

  }
}
</code>```

Service

```<code>export class RegistrationService {

  constructor(private http: Http) {}

  postDummy(data: string): Observable<any> {
    return this.http
      .post('https://demo4795542.mockable.io/test', data)
      .map((response: Response) => response.json())
      .catch ((error: any) => Observable.throw(error.json()));
  }
}
</code>```

NOTE: https://demo4795542.mockable.io/test is only a 24hr test REST api.

So looking at the code I think I need something within the resolve to handle the response. Perhaps subscribing to the response in the resolve rather than in the overview.

I'm thinking of something along the lines of / and have tried the below but doesn't work

Resolve replacement - tried but failed

```<code>export class RegistrationResolve implements Resolve<any> {

  tempData: any;

  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {

    this.tempData = this.regService.postDummy('test')
      .subscribe((data:any) =>
        this.tempData = data["data"]
    );

    if (this.tempData !== undefined) {
      console.log('Successful - routing to page');
      return this.tempData;
    } else {
      console.log('Failed - not router anywhere');
      this.router.navigate(['']);
      return null;
    }
  }
}
</code>```

Any help much appreciated. Thanks

答:
In RegisterComponent's handleView method instead of direct changing route you can fire http request to server and get response .If response code is 200 then chnage route ,otherwise show error

```<code>  //**Below is the pseudo code**

    handleView(){
        RegisterationService.postDummy().subscribe(function(response){
          if(response code is 200){
                this.router.navigate(['/overview']);
        } else{
           show error on Ui
         }
       })
      }
</code>```

And Instead of using resolve in 'Overview route' use canActive guard see
https://angular.io/docs/ts/latest/guide/router.html#!#guards

Body:
I have an app as follows.

User fills in a form (route is ' ')

Submits the form

Data is sent off to a REST api

Data is receive - On a good response (200) the page is routed to an overview  page containing the response. (route is 'overview') On a (400) it currently fails silently.

I've used a resolve for this as I want to wait until data is received before routing. The above works ok but..

What I want is to add the following functionality in part 4.

When a 400 or non 200 error is received I want to display an error and ensure the route is ' '.

My reason for wanting to add some conditional logic in was that I saw it as a demo in the angular docs. fetch before navigating

I have the following code so far.

App component

const routes: Routes = [
  {
    path: '',
    component:  RegistrationComponent,
  },
  {
    path: 'overview',
    component: ConfirmationComponent,
    resolve: {
        data: RegistrationResolve
    }
  }
]

Form component

export class RegistrationComponent implements OnInit {

  constructor(
    private router: Router,
    private regService: RegistrationService,
    private route: ActivatedRoute
  ){}

  onSubmit(event: RegDetails){
    this.handleView();
  }

  handleView(){
    this.router.navigate(['/overview']);
  }
}

Overview component

export class ConfirmationComponent implements OnInit {

  constructor(
    private router: Router,
    private route: ActivatedRoute
  ) {}

  ngOnInit(){
    this.route.data
    .subscribe(val => {
      this.resolvedData = val["data"];
    });
  }
}

Resolve

export class RegistrationResolve implements Resolve<any> {

  constructor(
    private regService: RegistrationService,
    private router: Router
  ) {}

  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {

    return this.regService.postDummy('apple');

  }
}

Service

export class RegistrationService {

  constructor(private http: Http) {}

  postDummy(data: string): Observable<any> {
    return this.http
      .post('https://demo4795542.mockable.io/test', data)
      .map((response: Response) => response.json())
      .catch ((error: any) => Observable.throw(error.json()));
  }
}

NOTE: https://demo4795542.mockable.io/test is only a 24hr test REST api.

So looking at the code I think I need something within the resolve to handle the response. Perhaps subscribing to the response in the resolve rather than in the overview.

I'm thinking of something along the lines of / and have tried the below but doesn't work

Resolve replacement - tried but failed

export class RegistrationResolve implements Resolve<any> {

  tempData: any;

  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {

    this.tempData = this.regService.postDummy('test')
      .subscribe((data:any) =>
        this.tempData = data["data"]
    );

    if (this.tempData !== undefined) {
      console.log('Successful - routing to page');
      return this.tempData;
    } else {
      console.log('Failed - not router anywhere');
      this.router.navigate(['']);
      return null;
    }
  }
}

Any help much appreciated. Thanks

Body:
In RegisterComponent's handleView method instead of direct changing route you can fire http request to server and get response .If response code is 200 then chnage route ,otherwise show error

  //**Below is the pseudo code**

    handleView(){
        RegisterationService.postDummy().subscribe(function(response){
          if(response code is 200){
                this.router.navigate(['/overview']);
        } else{
           show error on Ui
         }
       })
      }

And Instead of using resolve in 'Overview route' use canActive guard see
https://angular.io/docs/ts/latest/guide/router.html#!#guards


问:
Java Swing - Why is my first window not disposing/closing?
So I'm creating an application. I want main to initialize a login window, which I've done. And for now I want the login window to close whenever I click on the button, and when it closes, a new window (called MainWindow) opens with different buttons/info/text.

All these classes are separate, but in the same package.

The problem is: The main window opens when I click login, however the login window doesn't terminate/close.

My main method, from which I call the login window:

```<code>import javax.swing.*;

public class Main {

    // Display Login Window
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            new LoginWindow();
            LoginWindow.createAndShowLoginGUI();
        });
    }
}
</code>```

My login window class:

```<code>import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class LoginWindow extends JFrame implements ActionListener {

    public void prepareLoginGUI() {

        // Frame with GridBagLayout
        JFrame loginFrame = new JFrame("Login Window");
        loginFrame.setSize(1200, 800);
        loginFrame.setLayout(new GridBagLayout());

        // Button for logging in, with respective GridBagConstraint
        // setFocusable is set to false to take out the border around the text
        JButton loginButton = new JButton("Login");
        loginButton.addActionListener(this::actionPerformed);
        loginButton.setActionCommand("Open");
        GridBagConstraints lButtonC = new GridBagConstraints();
        loginButton.setFocusable(false);

        // Username text-field and JLabel with respective GridBagConstraints
        JTextField tfUsername = new JTextField(15);
        GridBagConstraints tfUserC = new GridBagConstraints();
        JLabel txtUser = new JLabel("Username: ");
        GridBagConstraints txtUserC = new GridBagConstraints();

        // Password text-field and JLabel with respective GridBagConstraints
        JPasswordField tfPassword = new JPasswordField(15);
        GridBagConstraints tfPassC = new GridBagConstraints();
        JLabel txtPassword = new JLabel("Password: ");
        GridBagConstraints txtPassC = new GridBagConstraints();

        // Add all components to the JFrame
        // Making sure to add the text before the text-fields
        loginFrame.add(txtUser, txtUserC);
        loginFrame.add(tfUsername, tfUserC);
        loginFrame.add(txtPassword, txtPassC);
        loginFrame.add(tfPassword, tfPassC);
        loginFrame.add(loginButton, lButtonC);

        // Show and set close parameters
        loginFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        loginFrame.setVisible(true);
    }

    // Instructions for when the login button is clicked
    // Close this window, if button == open, which it does
    @Override
    public void actionPerformed(ActionEvent e) {
        String cmd = e.getActionCommand();
        if (cmd.equals("Open")) {
            this.dispose();
            this.setVisible(false);
            new MainWindow();
            MainWindow.createAndShowMainWGUI();
        }
    }

    // Callable from Main class
    public static void createAndShowLoginGUI() {
        LoginWindow loginW = new LoginWindow();
        loginW.prepareLoginGUI();

    }

}
</code>```

My Main Window Class:

```<code>import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class MainWindow extends JFrame implements ActionListener {

    public void prepareMainWGUI(){
        // Frame with GridBagLayout
        JFrame loginFrame = new JFrame("Main Window");
        loginFrame.setSize(1200, 800);
        loginFrame.setLayout(new GridBagLayout());

        // Username text-field and JLabel with respective GridBagConstraints
        JLabel txtUser = new JLabel("It worked!");
        GridBagConstraints txtUserC = new GridBagConstraints();

        loginFrame.add(txtUser, txtUserC);

        loginFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        loginFrame.setVisible(true);
    }

    // Callable from Main class
    public static void createAndShowMainWGUI() {
        MainWindow mainWind = new MainWindow();
        mainWind.prepareMainWGUI();
    }

}
</code>```

If you use this code, when the main window opens, the login window will be right behind it.

答:
You can use when pressing button

```<code>System.exit(0);
</code>```

This will terminate your application. To close one window use(if you have open multiple windows) without affecting to others,

```<code>setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)
</code>```

Then, to open new one,

```<code>new frameName().setvisible(true);
</code>```

Example:

```<code>JButton closeButton = new JButton("Close");

closeButton .addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e)
    {
        this.dispose();//current(close only this) frame
        new frameName().setvisible(true);
    }
});
</code>```

Take a look at this question.

UPDATE:

In below line you have extends JFrame but you didnot use it.

```<code>public class LoginWindow extends JFrame implements ActionListener {
</code>```

Rather than that you have create new object from JFrame

```<code>JFrame loginFrame = new JFrame("Login Window");
</code>```

All the component you are adding to the loginFrame. But when actionPerformed trying to this.dispose(), since you are not using extended JFrame nothing will happen.

Solution:

Declare your JFrame as a instance variable:

```<code>public class LoginWindow implements ActionListener {
    JFrame loginFrame;
    public void prepareLoginGUI() {
</code>```

Then change,

```<code>this.dispose();
</code>```

To:

```<code>loginFrame.dispose();
</code>```

In this this.dispose(); call to the extended JFrame, no effect for your JFrame object(loginForm).

And one last thing, make sure to remove extends JFrame. Because you are not doing anything with extended JFrame. Read this post about extended JFrame.

Body:
So I'm creating an application. I want main to initialize a login window, which I've done. And for now I want the login window to close whenever I click on the button, and when it closes, a new window (called MainWindow) opens with different buttons/info/text.

All these classes are separate, but in the same package.

The problem is: The main window opens when I click login, however the login window doesn't terminate/close.

My main method, from which I call the login window:

import javax.swing.*;

public class Main {

    // Display Login Window
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            new LoginWindow();
            LoginWindow.createAndShowLoginGUI();
        });
    }
}

My login window class:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class LoginWindow extends JFrame implements ActionListener {

    public void prepareLoginGUI() {

        // Frame with GridBagLayout
        JFrame loginFrame = new JFrame("Login Window");
        loginFrame.setSize(1200, 800);
        loginFrame.setLayout(new GridBagLayout());

        // Button for logging in, with respective GridBagConstraint
        // setFocusable is set to false to take out the border around the text
        JButton loginButton = new JButton("Login");
        loginButton.addActionListener(this::actionPerformed);
        loginButton.setActionCommand("Open");
        GridBagConstraints lButtonC = new GridBagConstraints();
        loginButton.setFocusable(false);

        // Username text-field and JLabel with respective GridBagConstraints
        JTextField tfUsername = new JTextField(15);
        GridBagConstraints tfUserC = new GridBagConstraints();
        JLabel txtUser = new JLabel("Username: ");
        GridBagConstraints txtUserC = new GridBagConstraints();

        // Password text-field and JLabel with respective GridBagConstraints
        JPasswordField tfPassword = new JPasswordField(15);
        GridBagConstraints tfPassC = new GridBagConstraints();
        JLabel txtPassword = new JLabel("Password: ");
        GridBagConstraints txtPassC = new GridBagConstraints();

        // Add all components to the JFrame
        // Making sure to add the text before the text-fields
        loginFrame.add(txtUser, txtUserC);
        loginFrame.add(tfUsername, tfUserC);
        loginFrame.add(txtPassword, txtPassC);
        loginFrame.add(tfPassword, tfPassC);
        loginFrame.add(loginButton, lButtonC);

        // Show and set close parameters
        loginFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        loginFrame.setVisible(true);
    }

    // Instructions for when the login button is clicked
    // Close this window, if button == open, which it does
    @Override
    public void actionPerformed(ActionEvent e) {
        String cmd = e.getActionCommand();
        if (cmd.equals("Open")) {
            this.dispose();
            this.setVisible(false);
            new MainWindow();
            MainWindow.createAndShowMainWGUI();
        }
    }

    // Callable from Main class
    public static void createAndShowLoginGUI() {
        LoginWindow loginW = new LoginWindow();
        loginW.prepareLoginGUI();

    }

}

My Main Window Class:

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class MainWindow extends JFrame implements ActionListener {

    public void prepareMainWGUI(){
        // Frame with GridBagLayout
        JFrame loginFrame = new JFrame("Main Window");
        loginFrame.setSize(1200, 800);
        loginFrame.setLayout(new GridBagLayout());

        // Username text-field and JLabel with respective GridBagConstraints
        JLabel txtUser = new JLabel("It worked!");
        GridBagConstraints txtUserC = new GridBagConstraints();

        loginFrame.add(txtUser, txtUserC);

        loginFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        loginFrame.setVisible(true);
    }

    // Callable from Main class
    public static void createAndShowMainWGUI() {
        MainWindow mainWind = new MainWindow();
        mainWind.prepareMainWGUI();
    }

}

If you use this code, when the main window opens, the login window will be right behind it.

Body:
You can use when pressing button

System.exit(0);

This will terminate your application. To close one window use(if you have open multiple windows) without affecting to others,

setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)

Then, to open new one,

new frameName().setvisible(true);

Example:

JButton closeButton = new JButton("Close");

closeButton .addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e)
    {
        this.dispose();//current(close only this) frame
        new frameName().setvisible(true);
    }
});

Take a look at this question.

UPDATE:

In below line you have extends JFrame but you didnot use it.

public class LoginWindow extends JFrame implements ActionListener {

Rather than that you have create new object from JFrame

JFrame loginFrame = new JFrame("Login Window");

All the component you are adding to the loginFrame. But when actionPerformed trying to this.dispose(), since you are not using extended JFrame nothing will happen.

Solution:

Declare your JFrame as a instance variable:

public class LoginWindow implements ActionListener {
    JFrame loginFrame;
    public void prepareLoginGUI() {

Then change,

this.dispose();

To:

loginFrame.dispose();

In this this.dispose(); call to the extended JFrame, no effect for your JFrame object(loginForm).

And one last thing, make sure to remove extends JFrame. Because you are not doing anything with extended JFrame. Read this post about extended JFrame.