答:
In subprocess you must provide your command as a list, with the first item being the command and each following item being the arguments.

In your case your code should look like:

```<code>CMD_LIST = [['ls', '-l'], ['echo', 'Mama Mia'], ['echo', 'bla bla bla']]
for cmd_arg in CMD_LIST:
    subprocess.call(cmd_arg)
</code>```

See subprocess docs here: https://docs.python.org/2/library/subprocess.html

Title: How to make commands using str array in for loop by Python

Body:
In subprocess you must provide your command as a list, with the first item being the command and each following item being the arguments.

In your case your code should look like:

CMD_LIST = [['ls', '-l'], ['echo', 'Mama Mia'], ['echo', 'bla bla bla']]
for cmd_arg in CMD_LIST:
    subprocess.call(cmd_arg)

See subprocess docs here: https://docs.python.org/2/library/subprocess.html


来源: stackexchange

问:
Proving the primality of strong probable primes
Using the probabilistic version of the Miller-Rabin test, I have generated a list of medium-large (200-300 digit) probable primes. But probable ain't good enough! I need to know these numbers are prime. Is there a library -- preferably wrapped or wrappable in Python -- that implements one of the more efficient primality proving algorithms?

Alternatively, does anyone know where I can find a clear, detailed, and complete description of ECPP (or a similarly fast algorithm) that does not assume a great deal of prior knowledge?

Update: I've found a Java implementation of another test, APRT-CLE, that conclusively proves primality. It verified a 291-digit prime candidate in under 10 minutes on an atom processor. Still hoping for something faster, but this seems like a promising start.

答:
I've found that the Pari/GP library and language use APR-CL to prove primality, which is actually the preferred algorithm for numbers in this size range, as it turns out. GP proves a 291-digit candidate prime in under 20 seconds on an atom processor, which is sufficient for my needs, and it comes with a c library that I can access using ctypes.

```<code>import ctypes

def pari_isprime(self, n):
    try: pari = ctypes.cdll.LoadLibrary("libpari.so")
    except OSError:
        print "pari_isprime: couldn't load libpari!"
        exit()
    int(n)
    pari.pari_init(4000000, 2)
    ret = bool(pari.isprime(pari.gp_read_str(str(n))))
    pari.pari_close()
    return ret
</code>```

I could also use the instant module. Here's a simple c function that runs a string through pari's parser and returns the result as a string:

```<code>from instant import inline

runpari_code = """
PyObject* runpari(PyObject *args) {
    pari_init(40000000, 2);
    char *pari_code;
    char *outstr;

    if (!PyArg_Parse(args, "s", &pari_code)) { return NULL; } // instant uses old-style args; for a module, use PyArg_ParseTuple
    outstr = GENtostr(gp_read_str(pari_code));
    pari_close();
    return Py_BuildValue("s", outstr);
}
"""
runpari = inline(runpari_code, system_headers=['pari/pari.h'], libraries=['pari'])
</code>```

The above can also be used as the basis of a proper CPython extension.

ContentLicense: CC BY-SA 3.0

Body:
I've found that the Pari/GP library and language use APR-CL to prove primality, which is actually the preferred algorithm for numbers in this size range, as it turns out. GP proves a 291-digit candidate prime in under 20 seconds on an atom processor, which is sufficient for my needs, and it comes with a c library that I can access using ctypes.

import ctypes

def pari_isprime(self, n):
    try: pari = ctypes.cdll.LoadLibrary("libpari.so")
    except OSError:
        print "pari_isprime: couldn't load libpari!"
        exit()
    int(n)
    pari.pari_init(4000000, 2)
    ret = bool(pari.isprime(pari.gp_read_str(str(n))))
    pari.pari_close()
    return ret

I could also use the instant module. Here's a simple c function that runs a string through pari's parser and returns the result as a string:

from instant import inline

runpari_code = """
PyObject* runpari(PyObject *args) {
    pari_init(40000000, 2);
    char *pari_code;
    char *outstr;

    if (!PyArg_Parse(args, "s", &pari_code)) { return NULL; } // instant uses old-style args; for a module, use PyArg_ParseTuple
    outstr = GENtostr(gp_read_str(pari_code));
    pari_close();
    return Py_BuildValue("s", outstr);
}
"""
runpari = inline(runpari_code, system_headers=['pari/pari.h'], libraries=['pari'])

The above can also be used as the basis of a proper CPython extension.

ContentLicense: CC BY-SA 2.5


问:
Fatal Error: Cannot create output file "project1.exe"
So for some time now I keep having this problem:

on windows 7 (64bit), with Delphi 7 and Delphi XE2, if from within the IDE, I compile a program, run it, stop it, change it and rerun it I get this error message:

[Fatal Error] Cannot create output file "project1.exe"

I have no clue to what causes this. I googled for more information, but I could not find a solution.

There are two workarounds: either wait a minute or two, or delete project1.exe manually. Needless to say, this is unworkable.

I do not have a virus scanner, and no virus. Have full access to related folders. Run everything as Administrator.

So what causes this? And what can I do to fix it?

答:
In my case Problem solved by excluding project folder from antivirus real time protection.

Can you delete EXE file manually?If no , proccess is in memroy , Open task manager ,select your project, END task . you have some bug in code that prevents application terminate.

If it is not in process list , Then Try :

1-exclude folder from windows Indexing or 3rd party file search applications that index files

2-In windows seven activate application experince service

3-Exclude project folder from Anti virus realtime protection

UPDATE

I noticed that ,Even if you do all what i said above, you may get this error some times in Windows 7 randomly.specially when you compile project many times...first compiles will be OK but after ten or more times this problem will be occurred


问:
Configuring Spring beans
I want to make an AngularJS + Spring MVC + Hibernate + MySQL application. And I can't understand how to configure spring beans, so that I will be able to use @Autowired annotations to my repository and entity classes.

pom.xml dependencies:

```<code><groupId>com.kspt</groupId>
<artifactId>pms</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>
    </plugins>
</build>

<properties>
    <java-version>1.8</java-version>
    <spring-core.version>4.1.6.RELEASE</spring-core.version>
    <javax.servlet-api.version>3.1.0</javax.servlet-api.version>
    <spring-data-jpa.version>1.9.2.RELEASE</spring-data-jpa.version>
    <hibernate.version>5.2.12.Final</hibernate.version>
    <mysql-connector-java.version>5.1.34</mysql-connector-java.version>
    <commons-dbcp2.version>2.1.1</commons-dbcp2.version>
    <jta.version>1.1</jta.version>
    <junit.version>4.11</junit.version>
    <spring-webmvc.version>4.1.6.RELEASE</spring-webmvc.version>
    <spring-test.version>4.1.6.RELEASE</spring-test.version>
    <jstl.version>1.2</jstl.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>${spring-core.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>${spring-core.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-autoconfigure</artifactId>
        <version>1.0.0.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>${spring-webmvc.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${spring-webmvc.version}</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>${javax.servlet-api.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-jpa</artifactId>
        <version>${spring-data-jpa.version}</version>
    </dependency>

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.2.3</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.2.3</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>2.2.3</version>
    </dependency>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>${hibernate.version}</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>${hibernate.version}</version>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>${mysql-connector-java.version}</version>
    </dependency>

    <!--JSF (include "jsf-api" and "jsf-impl")-->
    <dependency>
        <groupId>org.glassfish</groupId>
        <artifactId>javax.faces</artifactId>
        <version>2.2.10</version>
    </dependency>
</dependencies>
</code>```

User entity class:

```<code>@Entity
@Table(name = "USERS")
public class User {

    @Id
    @Column(name = "ID")
    @GeneratedValue
    private Long id;

    @Column(name = "LOGIN", unique = true, nullable = false)
    private String login;

    @Column(name = "NAME")
    private String name;

    @JsonIgnore
    @Column(name = "PASSWORD")
    private String password;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getLogin() {
        return login;
    }

    public void setLogin(String login) {
        this.login = login;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}
</code>```

Repository for User:

```<code>@Repository
public interface UserRepository extends JpaRepository<User, Long> {
    Optional<User> findByLogin(String login);
}
</code>```

Controller for User:

```<code>@RestController
@RequestMapping({"{login}"})
public class UserController {
    @Autowired
    UserRepository userRepository;

    @RequestMapping
    public User getUser(@PathVariable String login) {
        return userRepository.findByLogin(login)
                .orElseThrow(() -> new UserNotFoundException(login));
    }

    @RequestMapping(method = RequestMethod.POST)
    public void addUser(@PathVariable String login, @RequestBody User user) {
        userRepository.save(user);
    }
}
</code>```

Configuration class:

```<code>@EnableWebMvc
@Configuration
@ComponentScan("com.kspt.pms")
public class AppConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**")
                .addResourceLocations("/WEB-INF/resources/");
    }

    @Bean
    public ViewResolver getViewResolver(){
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/view/");
        resolver.setSuffix(".jsp");
        return resolver;
    }

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }
}
</code>```

web.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">

    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextClass</param-name>
            <param-value>
                org.springframework.web.context.support.AnnotationConfigWebApplicationContext
            </param-value>
        </init-param>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>
                com.kspt.pms.AppConfig
            </param-value>
        </init-param>
    </servlet>

    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>*.form</url-pattern>
    </servlet-mapping>

</web-app>
</code>```

When I try to run application, I get following exception:

```<code>org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.kspt.pms.repository.UserRepository com.kspt.pms.controller.UserController.userRepository; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.kspt.pms.repository.UserRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
</code>```

As I understood, this happens because I have not created an applicationContext.xml file for Spring to know how to autowire all bean classes. I decided to try @EnableAutoConfiguration annotation, so that it will automaticly generate all required files. But when I add that annotation to AppConfig class, I get following error:

```<code>org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean]: Factory method 'entityManagerFactory' threw exception; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.sql.DataSource] is defined
</code>```

So I have several questions:

Am I right that I need to create applicationContext.xml file with beans description, or when you use Hibernate (or Spring Data) it can somehow generate this file automatically somehow?

Is there any other way no to write applicationContext manually, but to generate it somehow?

If I'm wrong about applicationContext, then why I have these errors?

And maybe I'm just don't understand the concept of Spring and Hybernate properly. So can anyone help me please?

答:
No qualifying bean of type [javax.sql.DataSource] is defined

That's the key of your problem. To support repositories and hibernate you need to declare DataSource bean with all the configs of your DB - URL, credentials etc.

See here for annotated DataSource config example or for XML based config here

You need something like this

```<code>@Bean
public DataSource dataSource() {
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName(env.getRequiredProperty("jdbc.driverClassName"));
    dataSource.setUrl(env.getRequiredProperty("jdbc.url"));
    dataSource.setUsername(env.getRequiredProperty("jdbc.username"));
    dataSource.setPassword(env.getRequiredProperty("jdbc.password"));
    return dataSource;
}
</code>```

Title: Configuring Spring beans

Body:
I want to make an AngularJS + Spring MVC + Hibernate + MySQL application. And I can't understand how to configure spring beans, so that I will be able to use @Autowired annotations to my repository and entity classes.

pom.xml dependencies:

<groupId>com.kspt</groupId>
<artifactId>pms</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>
    </plugins>
</build>

<properties>
    <java-version>1.8</java-version>
    <spring-core.version>4.1.6.RELEASE</spring-core.version>
    <javax.servlet-api.version>3.1.0</javax.servlet-api.version>
    <spring-data-jpa.version>1.9.2.RELEASE</spring-data-jpa.version>
    <hibernate.version>5.2.12.Final</hibernate.version>
    <mysql-connector-java.version>5.1.34</mysql-connector-java.version>
    <commons-dbcp2.version>2.1.1</commons-dbcp2.version>
    <jta.version>1.1</jta.version>
    <junit.version>4.11</junit.version>
    <spring-webmvc.version>4.1.6.RELEASE</spring-webmvc.version>
    <spring-test.version>4.1.6.RELEASE</spring-test.version>
    <jstl.version>1.2</jstl.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>${spring-core.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>${spring-core.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-autoconfigure</artifactId>
        <version>1.0.0.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>${spring-webmvc.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${spring-webmvc.version}</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>${javax.servlet-api.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-jpa</artifactId>
        <version>${spring-data-jpa.version}</version>
    </dependency>

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.2.3</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.2.3</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>2.2.3</version>
    </dependency>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>${hibernate.version}</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>${hibernate.version}</version>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>${mysql-connector-java.version}</version>
    </dependency>

    <dependency>
        <groupId>org.glassfish</groupId>
        <artifactId>javax.faces</artifactId>
        <version>2.2.10</version>
    </dependency>
</dependencies>

User entity class:

@Entity
@Table(name = "USERS")
public class User {

    @Id
    @Column(name = "ID")
    @GeneratedValue
    private Long id;

    @Column(name = "LOGIN", unique = true, nullable = false)
    private String login;

    @Column(name = "NAME")
    private String name;

    @JsonIgnore
    @Column(name = "PASSWORD")
    private String password;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getLogin() {
        return login;
    }

    public void setLogin(String login) {
        this.login = login;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

Repository for User:

@Repository
public interface UserRepository extends JpaRepository<User, Long> {
    Optional<User> findByLogin(String login);
}

Controller for User:

@RestController
@RequestMapping({"{login}"})
public class UserController {
    @Autowired
    UserRepository userRepository;

    @RequestMapping
    public User getUser(@PathVariable String login) {
        return userRepository.findByLogin(login)
                .orElseThrow(() -> new UserNotFoundException(login));
    }

    @RequestMapping(method = RequestMethod.POST)
    public void addUser(@PathVariable String login, @RequestBody User user) {
        userRepository.save(user);
    }
}

Configuration class:

@EnableWebMvc
@Configuration
@ComponentScan("com.kspt.pms")
public class AppConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**")
                .addResourceLocations("/WEB-INF/resources/");
    }

    @Bean
    public ViewResolver getViewResolver(){
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/view/");
        resolver.setSuffix(".jsp");
        return resolver;
    }

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }
}

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">

    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextClass</param-name>
            <param-value>
                org.springframework.web.context.support.AnnotationConfigWebApplicationContext
            </param-value>
        </init-param>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>
                com.kspt.pms.AppConfig
            </param-value>
        </init-param>
    </servlet>

    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>*.form</url-pattern>
    </servlet-mapping>

</web-app>

When I try to run application, I get following exception:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.kspt.pms.repository.UserRepository com.kspt.pms.controller.UserController.userRepository; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.kspt.pms.repository.UserRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

As I understood, this happens because I have not created an applicationContext.xml file for Spring to know how to autowire all bean classes. I decided to try @EnableAutoConfiguration annotation, so that it will automaticly generate all required files. But when I add that annotation to AppConfig class, I get following error:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean]: Factory method 'entityManagerFactory' threw exception; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.sql.DataSource] is defined

So I have several questions:

Am I right that I need to create applicationContext.xml file with beans description, or when you use Hibernate (or Spring Data) it can somehow generate this file automatically somehow?

Is there any other way no to write applicationContext manually, but to generate it somehow?

If I'm wrong about applicationContext, then why I have these errors?

And maybe I'm just don't understand the concept of Spring and Hybernate properly. So can anyone help me please?

Body:
No qualifying bean of type [javax.sql.DataSource] is defined

That's the key of your problem. To support repositories and hibernate you need to declare DataSource bean with all the configs of your DB - URL, credentials etc.

See here for annotated DataSource config example or for XML based config here

You need something like this

@Bean
public DataSource dataSource() {
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName(env.getRequiredProperty("jdbc.driverClassName"));
    dataSource.setUrl(env.getRequiredProperty("jdbc.url"));
    dataSource.setUsername(env.getRequiredProperty("jdbc.username"));
    dataSource.setPassword(env.getRequiredProperty("jdbc.password"));
    return dataSource;
}


问:
Check multiple columns for value, replace with NA if not found in R
I have a data.frame like this:

```<code>#df1
ID     a1      a2     a3      b1      b2      b3     Date    Name
3xy    NA      NA     NA     Ben      Bob     Alex   12/3    Bob
4lm    John    Bill   Sue    NA       NA      NA     12/5    Mark
</code>```

I want those in the "name" column to be replaced by NA if they don't appear in any of the a1 through b3 columns in their row, like this:

```<code>ID     a1      a2     a3      b1      b2      b3     Date    Name
3xy    NA      NA     NA     Ben      Bob     Alex   12/3    Bob
4lm    John    Bill   Sue    NA       NA      NA     12/5    NA
</code>```

I can't figure out why what's below doesn't work:

```<code>df1$Name <- with(df1, ifelse(Name %in% df1[2:7], Name, NA))
</code>```

or

```<code>df1$Name[!(df1$Name %in% df1[2:7])] <- NA
</code>```

Both statements replace the entire "Name" column with NA, failing to preserve the names that appear in columns a1 through b3.

答:
Solution using apply and ifelse:

```<code>df1$Name <- apply(df1, 1, function(x) ifelse(x[9] %in% x[2:7], x[9], NA))
</code>```

Body:
I have a data.frame like this:

#df1
ID     a1      a2     a3      b1      b2      b3     Date    Name
3xy    NA      NA     NA     Ben      Bob     Alex   12/3    Bob
4lm    John    Bill   Sue    NA       NA      NA     12/5    Mark

I want those in the "name" column to be replaced by NA if they don't appear in any of the a1 through b3 columns in their row, like this:

ID     a1      a2     a3      b1      b2      b3     Date    Name
3xy    NA      NA     NA     Ben      Bob     Alex   12/3    Bob
4lm    John    Bill   Sue    NA       NA      NA     12/5    NA

I can't figure out why what's below doesn't work:

df1$Name <- with(df1, ifelse(Name %in% df1[2:7], Name, NA))

or

df1$Name[!(df1$Name %in% df1[2:7])] <- NA

Both statements replace the entire "Name" column with NA, failing to preserve the names that appear in columns a1 through b3.

Body:
Solution using apply and ifelse:

df1$Name <- apply(df1, 1, function(x) ifelse(x[9] %in% x[2:7], x[9], NA))


问:
Display image json object into ionic list ( v2)
I have a json object that contains id of an image and its url in the server , in order to display it in an ion-list i try the code below but the image doesn't appear.

About.html

```<code><ion-content padding>

  <ion-list>
    <ion-item *ngFor="let post of posts">
      <img [src]="post.pic"/>
    </ion-item>
  </ion-list>

</ion-content>
</code>```

here is my json object :

```<code>{"ListeImages":[{"id":"44","pic":"https:\/\/stationpfe.000webhostapp.com\/projet\/uploads\/1494201248244.jpg"}],"success":1}
</code>```

About.ts

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import {Imageservice} from '../../providers/imageservice';
import { Http } from '@angular/http';
@Component({
  selector: 'page-about',
  templateUrl: 'about.html',
  providers:[Imageservice]
})
export class AboutPage {
posts: any;
  constructor(public navCtrl: NavController,public im:Imageservice,public http: Http) {
this.getImages();

  }

getImages(){
this.im.OneArrive().subscribe(response=>
{
  this.posts=response.ListeImages;
});

}
}```
</div>
</div>
</p>

<p>imageservice.ts ( provider)</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class Imageservice {

  constructor(public http: Http) {
    console.log('Hello Imageservice Provider');
  }
public OneArrive(){
var url='https://stationpfe.000webhostapp.com/projet/SelectListeImages.php';
     return this.http.get(url).map(res=>res.json());
}
}</code>```

答:
```<code><ion-avatar item-left>

      <img [src]="imageUrl+card.image" />
</ion-avatar>
</code>```

i have stored the image url in .ts file the card.image value is the value that i get from server.
In my case i have a server storage=>http://311.11.111.111:8000/storage<=like this
i specify the storage + the value from api to display in the

      specified above.
Hope it helps....

Body:
I have a json object that contains id of an image and its url in the server , in order to display it in an ion-list i try the code below but the image doesn't appear.

About.html

<ion-content padding>

  <ion-list>
    <ion-item *ngFor="let post of posts">

    </ion-item>
  </ion-list>

</ion-content>

here is my json object :

{"ListeImages":[{"id":"44","pic":"https:\/\/stationpfe.000webhostapp.com\/projet\/uploads\/1494201248244.jpg"}],"success":1}

About.ts

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import {Imageservice} from '../../providers/imageservice';
import { Http } from '@angular/http';
@Component({
  selector: 'page-about',
  templateUrl: 'about.html',
  providers:[Imageservice]
})
export class AboutPage {
posts: any;
  constructor(public navCtrl: NavController,public im:Imageservice,public http: Http) {
this.getImages();

  }

getImages(){
this.im.OneArrive().subscribe(response=>
{
  this.posts=response.ListeImages;
});

}
}

imageservice.ts ( provider)

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class Imageservice {

  constructor(public http: Http) {
    console.log('Hello Imageservice Provider');
  }
public OneArrive(){
var url='https://stationpfe.000webhostapp.com/projet/SelectListeImages.php';
     return this.http.get(url).map(res=>res.json());
}
}

Body:
<ion-avatar item-left>

      <img [src]="imageUrl+card.image" />
</ion-avatar>

i have stored the image url in .ts file the card.image value is the value that i get from server.
In my case i have a server storage=>http://311.11.111.111:8000/storage<=like this
i specify the storage + the value from api to display in the

     <img [scr]=""/> specified above.
Hope it helps....


问:
How to get a function to return different types
So, I have a function with multiple definitions (guards), and depending on which one it matches, I'm trying to have it either return an (a,b) or [(a,b)], however the compiler is throwing up errors 'cause they're different types. I was trying to use Either to solve this, but probably not using it right :P. any help?</p>

答:
Functions in Haskell can only return one type so Either will work for you since it would have your function return the type Either (a,b) [(a.b)].

I am not sure what went wrong with how you are using Either but here is a simple example of its usage:

```<code>test a b =
    if a == True
    then Left (a,b)
    else Right [(a,b)]
</code>```

Body:
Functions in Haskell can only return one type so Either will work for you since it would have your function return the type Either (a,b) [(a.b)].

I am not sure what went wrong with how you are using Either but here is a simple example of its usage:

test a b =
    if a == True
    then Left (a,b)
    else Right [(a,b)]


问:
Getting ERROR 1452: Cannot add or update a child row: a foreign key constraint fails when using 1 our 4 insert statements
I am trying to insert data into my DB and I keep getting the "ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails" on 1 insert command. I believe it has to do with the FKs I used when I created the table. But I am not sure how to fix it. Any suggestions would be awesome.

Original Create table commands:
REATE TABLE Donut
  (DonutID int,
  DonutName VARCHAR(25) not null,
  Description VARCHAR(25) not null,
  UnitPrice decimal(4,2) not null,
  PRIMARY KEY (DonutID) ) ;

CREATE TABLE Customer
  ( CustomerID INT not null,
   FirstName VARCHAR(20) not null,
   LastName VARCHAR(20) not null,
   StreetAddress VARCHAR(20) not null,
   Apt VARCHAR(20),
   City VARCHAR(20) not null,
   State VARCHAR(2) not null,
   ZipCode VARCHAR(5) not null,
   HomePhone VARCHAR(10) not null,
   MobilePhone VARCHAR(10) not null,
   OtherPhone VARCHAR(10),
    PRIMARY KEY(CustomerID) ) ;

CREATE TABLE Orders
  ( OrderID int not null,
   CustomerID int,
   OrderDate Date not null,
   Notes VARCHAR(100),
    PRIMARY KEY (OrderID),
    FOREIGN KEY (CustomerID)
        REFERENCES Customer (CustomerID) ) ;

CREATE TABLE OrderItem
  ( OrderID INT,
   DonutID INT,
   Qty SMALLINT not null,
   PRIMARY KEY(OrderID, DonutID),
   FOREIGN KEY (OrderID)
        REFERENCES Orders (CustomerID),
   FOREIGN KEY (DonutID)
        REFERENCES Donut (DonutID) ) ;

Insert command that is failing:
INSERT INTO OrderItem
    (OrderID,DonutID,Qty) VALUES
    (991,1,12),
    (992,2,500),
    (993,3,6);

答:
I had to change The Foreign key reference for OrderID..it was referencing Orders (customerID) and it should be Reference Orders (OrderID)

CREATE TABLE OrderItem
  ( OrderID INT,
   DonutID INT,
   Qty SMALLINT not null,
   PRIMARY KEY(OrderID, DonutID),
   FOREIGN KEY (OrderID)
        REFERENCES Orders (OrderID),
   FOREIGN KEY (DonutID)
        REFERENCES Donut (DonutID) ) ;

Answered my own question!


问:
ImportXML function in Google Sheets #ERROR
Have often frequented these pages but never needed to raise a new question...

I've searched high and low for a solution to, what should be, a fairly simple ImportXML function in Google sheets and I simply cannot grab the data I'm looking for.

Companies House in the UK make their basic company data freely available in various formats. For example, for company number 06732413 (I've picked that entirely at random as a usable example), their data can be accessed at http://data.companieshouse.gov.uk/doc/company/06732413 (or alternatively at http://data.companieshouse.gov.uk/doc/company/06732413.xml, and a range of other types.)

I simply cannot find a way for ImportXML to return a specific element within that data, say the <Accounts>/<NextDueDate> data.

Is there an obvious solution?

答:
There is also a format for csv you can just use this function to pull it in:

=importdata("http://data.companieshouse.gov.uk/doc/company/06732413.csv")

note you just append .csv onto the end of the url for it to work.


问:
Troubleshoot SSL/TLS handshake in Google Chrome browser
I would like to inspect the SSL/TLS handshake in Google Chrome (or Chromium) browser.

I'm looking for output similar to what you'd see using commands like these from other HTTPS clients (just examples):

```<code>➜  ~  curl -k -v https://foo.com:443 --tlsv1
</code>```

or

```<code>➜  ~  openssl s_client -debug -connect foo.com:443 -tls1
</code>```

I've searched a bit, and it doesn't look like native tools (ie via inspect element) nor plugins have this level of visibility.

答:
You may use Wireshark(https://www.wireshark.org/) to capture the network packets, and use the

```<code>Menu->Statistics->Flow Graph
</code>```

to view the network sequence as below. Below diagram illustrates the TCP flow visiting stackoverflow.com. Meanwhile, you can click on the arrows in the diagram to inspect down to ethernet frame level, including TCP/IP/Ethernet packets.

Body:
I would like to inspect the SSL/TLS handshake in Google Chrome (or Chromium) browser.

I'm looking for output similar to what you'd see using commands like these from other HTTPS clients (just examples):

➜  ~  curl -k -v https://foo.com:443 --tlsv1

or

➜  ~  openssl s_client -debug -connect foo.com:443 -tls1

I've searched a bit, and it doesn't look like native tools (ie via inspect element) nor plugins have this level of visibility.

Body:
You may use Wireshark(https://www.wireshark.org/) to capture the network packets, and use the

Menu->Statistics->Flow Graph

to view the network sequence as below. Below diagram illustrates the TCP flow visiting stackoverflow.com. Meanwhile, you can click on the arrows in the diagram to inspect down to ethernet frame level, including TCP/IP/Ethernet packets.


问:
jQuery animation interruption issue
I am working on angular program in which I have an image which I am animating by using jQuery .animate() property.Its working fine but the issue occur when I change the state using ui-router in middle of the animation.

It result in abrupt behaviour like even its url changes but the animation process still persist.I have tried .stop() , .clearQueue() and even .finish() property to end the animation before switching but nothing help me at all.

app.controller('appCtrl',function () {
  setTimeout(function () {
    $('#character').animate({marginTop:"A1px",marginLeft:"B1px"},1000);
  },1000);
  setTimeout(function () {
    $('#character').animate({marginTop:"A2px",marginLeft:"B2px"},1000);
  },3000);
  setTimeout(function () {
    $('#character').animate({marginTop:"A3px",marginLeft:"B3px"},1000);
  },5000);
  setTimeout(function () {
    $('#character').animate({marginTop:"A4px",marginLeft:"B4px"},1000);
  },7000);
  setTimeout(function () {
    $('#character').animate({marginTop:"A5px",marginLeft:"B5px"},1000);
  },9000);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="">
  <div class="">
    <img src="character.png" id="character" alt="" />
  </div>
  <div class="">
    <input type="button" name="name" value="BACK" ui-sref="backpage">
    <input type="button" name="name" value="NEXT" ui-sref="nextpage">
  </div>
</div></code>```

答:
Here is updated plunker.

Use $timeout and on controller destroy remove the timeout .

```<code>$scope.$on('$destroy', function() {
  $timeout.cancel(timer);
});
</code>```

Better practice do never merge jQuery with Angular.

Title: jQuery animation interruption issue

Body:
I am working on angular program in which I have an image which I am animating by using jQuery .animate() property.Its working fine but the issue occur when I change the state using ui-router in middle of the animation.

It result in abrupt behaviour like even its url changes but the animation process still persist.I have tried .stop() , .clearQueue() and even .finish() property to end the animation before switching but nothing help me at all.

app.controller('appCtrl',function () {
  setTimeout(function () {
    $('#character').animate({marginTop:"A1px",marginLeft:"B1px"},1000);
  },1000);
  setTimeout(function () {
    $('#character').animate({marginTop:"A2px",marginLeft:"B2px"},1000);
  },3000);
  setTimeout(function () {
    $('#character').animate({marginTop:"A3px",marginLeft:"B3px"},1000);
  },5000);
  setTimeout(function () {
    $('#character').animate({marginTop:"A4px",marginLeft:"B4px"},1000);
  },7000);
  setTimeout(function () {
    $('#character').animate({marginTop:"A5px",marginLeft:"B5px"},1000);
  },9000);
});

    <input type="button" name="name" value="BACK" ui-sref="backpage">
    <input type="button" name="name" value="NEXT" ui-sref="nextpage">

Body:
Here is updated plunker.

Use $timeout and on controller destroy remove the timeout .

$scope.$on('$destroy', function() {
  $timeout.cancel(timer);
});

Better practice do never merge jQuery with Angular.


问:
ASP.NET MVC: No record added to database after POST
```<code>[HttpPost]
public ActionResult Create(FormCollection collection)
{
    UpdateModel(collection);
    context.SaveChanges();
    return RedirectToAction("Index", new {controller = "Home"});
}
</code>```

The action succeed, but there was no recored inserted into the database. Why?

I do not want to manually create a object by getting each value from each field in form collection.

答:
```<code>UpdateModel(collection);
context.SaveChanges();
</code>```

You didn't made any changes to the context in order to expect something to get saved. Entity Framework (assuming this is what you are using) works with objects. So you need a model and persist this model into the database. So your controller action could look like this:

```<code>[HttpPost]
public ActionResult Create(Product product)
{
    _repository.Create(product);
    return RedirectToAction("Index", new {controller = "Home"});
}
</code>```

where the _repository variable is some interface which defines the operations on your models. Using an interface here allows you to separate your data access logic from your controller logic. In the implementation of this repository you could be using any data access technology you like such as EF or NHibernate, it's just that your controller shouldn't know about it.

Body:
[HttpPost]
public ActionResult Create(FormCollection collection)
{
    UpdateModel(collection);
    context.SaveChanges();
    return RedirectToAction("Index", new {controller = "Home"});
}

The action succeed, but there was no recored inserted into the database. Why?

I do not want to manually create a object by getting each value from each field in form collection.

Body:
UpdateModel(collection);
context.SaveChanges();

You didn't made any changes to the context in order to expect something to get saved. Entity Framework (assuming this is what you are using) works with objects. So you need a model and persist this model into the database. So your controller action could look like this:

[HttpPost]
public ActionResult Create(Product product)
{
    _repository.Create(product);
    return RedirectToAction("Index", new {controller = "Home"});
}

where the _repository variable is some interface which defines the operations on your models. Using an interface here allows you to separate your data access logic from your controller logic. In the implementation of this repository you could be using any data access technology you like such as EF or NHibernate, it's just that your controller shouldn't know about it.


问:
how to load a tensorflow model and continue training
I want to load a pretrained model and continue training with this model.

Standard code snippet to save a model (pretrain.py):

```<code>tf.reset_default_graph()

# tf Graph input
X = tf.placeholder("float", [None, n_input])
Y = tf.placeholder("float", [None, n_classes])

mlp_layer_name = ['h1', 'b1', 'h2', 'b2', 'h3', 'b3', 'w_o', 'b_o']
logits = multilayer_perceptron(X, n_input, n_classes, mlp_layer_name)

loss_op = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=Y), name='loss_op')
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)
train_op = optimizer.minimize(loss_op, name='train_op')

saver = tf.train.Saver()

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())

    # Training cycle
    for epoch in range(training_epochs):
        avg_cost = 0.

        # Loop over all batches
        for i in range(total_batch):
            batch_x, batch_y = next(train_generator)

            # Run optimization op (backprop) and cost op (to get loss value)
            _, c = sess.run([train_op, loss_op], feed_dict={X: batch_x,
                                                            Y: batch_y})
            # Compute average loss
            avg_cost += c / total_batch

        print("Epoch: {:3d}, cost = {:.6f}".format(epoch+1, avg_cost))

    print("Optimization Finished!")
    saver.save(sess, 'model')
    print("Model saved")
</code>```

Now load the pretrained model and continue training with it (continue.py).

```<code># tf Graph input
X = tf.placeholder("float", [None, n_input])
Y = tf.placeholder("float", [None, n_classes])
mlp_layer_name = ['h1', 'b1', 'h2', 'b2', 'h3', 'b3', 'w_o', 'b_o']
logits = multilayer_perceptron(X, n_input, n_classes, mlp_layer_name)
loss_op = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=Y), name='loss_op')
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)
train_op = optimizer.minimize(loss_op, name='train_op')

with tf.Session() as sess:
    saver = tf.train.import_meta_graph('model.meta')
    saver.restore(sess, tf.train.latest_checkpoint('./')) # search for checkpoint file

    graph = tf.get_default_graph()

    for epoch in range(training_epochs):
        avg_cost = 0.

        # Loop over all batches
        for i in range(total_batch):
            batch_x, batch_y = next(train_generator)

            # Run optimization op (backprop) and cost op (to get loss value)
            _, c = sess.run([train_op, loss_op], feed_dict={X: batch_x,
                                                            Y: batch_y})
            # Compute average loss
            avg_cost += c / total_batch

        print("Epoch: {:3d}, cost = {:.6f}".format(epoch+1, avg_cost))
</code>```

But it shows following error:

tensorflow.python.framework.errors_impl.FailedPreconditionError:
  Attempting to use uninitialized value h1
           [[Node: h1/read = IdentityT=DT_FLOAT, _class=["loc:@h1"], _device="/job:localhost/replica:0/task:0/cpu:0"]]

Here are my questions:

1. In many tensorflow's tutorial, it uses get_tensor_by_name() to load weights and biases. Here, I don't want to get weights and biases. I just want to load the model and continue training with it.

2. The error showed that tensor is uninitialized. However, I think saver.restore(sess, tf.train.latest_checkpoint('./')) should have loaded the weights and biases succesfully.

Here is multilayer_perceptron() if it helps to illustrate my questoins.

```<code>def multilayer_perceptron(x, n_input, n_classes, name):
    n_hidden_1 = 512
    n_hidden_2 = 256
    n_hidden_3 = 128
    # Store layers weight & bias
    weights = {
        'h1' : tf.get_variable(name[0], initializer=tf.random_normal([n_input, n_hidden_1])),
        'h2' : tf.get_variable(name[2], initializer=tf.random_normal([n_hidden_1, n_hidden_2])),
        'h3' : tf.get_variable(name[4], initializer=tf.random_normal([n_hidden_2, n_hidden_3])),
        'w_o': tf.get_variable(name[6], initializer=tf.random_normal([n_hidden_3, n_classes]))
    }
    biases = {
        'b1' : tf.get_variable(name[1], initializer=tf.random_normal([n_hidden_1])),
        'b2' : tf.get_variable(name[3], initializer=tf.random_normal([n_hidden_2])),
        'b3' : tf.get_variable(name[5], initializer=tf.random_normal([n_hidden_3])),
        'b_o': tf.get_variable(name[7], initializer=tf.random_normal([n_classes]))
    }

    layer_1 = tf.nn.relu(tf.add(tf.matmul(x      , weights['h1']), biases['b1']))
    layer_1 = tf.layers.dropout(layer_1, rate=0.5, training=True)
    layer_2 = tf.nn.relu(tf.add(tf.matmul(layer_1, weights['h2']), biases['b2']))
    layer_2 = tf.layers.dropout(layer_2, rate=0.3, training=True)
    layer_3 = tf.nn.relu(tf.add(tf.matmul(layer_2, weights['h3']), biases['b3']))
    layer_3 = tf.layers.dropout(layer_3, rate=0.1, training=True)
    out_layer = tf.matmul(layer_3, weights['w_o']) + biases['b_o']
    return out_layer
</code>```

答:
I think I found the answer. The key is that it doesn't need to call tf.train.import_meta_graph() if it has already uses saver.restore(sess, tf.train.latest_checkpoint('./')). Here is my code.

```<code># tf Graph input
X = tf.placeholder("float", [None, n_input])
Y = tf.placeholder("float", [None, n_classes])
mlp_layer_name = ['h1', 'b1', 'h2', 'b2', 'h3', 'b3', 'w_o', 'b_o']
logits = multilayer_perceptron(X, n_input, n_classes, mlp_layer_name)
loss_op = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=Y), name='loss_op')
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)
train_op = optimizer.minimize(loss_op, name='train_op')

with tf.Session() as sess:
    saver = tf.train.Saver()
    saver.restore(sess, tf.train.latest_checkpoint('./')) # search for checkpoint file

    graph = tf.get_default_graph()

    for epoch in range(training_epochs):
        avg_cost = 0.

        # Loop over all batches
        for i in range(total_batch):
            batch_x, batch_y = next(train_generator)

            # Run optimization op (backprop) and cost op (to get loss value)
            _, c = sess.run([train_op, loss_op], feed_dict={X: batch_x,
                                                            Y: batch_y})
            # Compute average loss
            avg_cost += c / total_batch

        print("Epoch: {:3d}, cost = {:.6f}".format(epoch+1, avg_cost))
</code>```

Body:
I want to load a pretrained model and continue training with this model.

Standard code snippet to save a model (pretrain.py):

tf.reset_default_graph()

# tf Graph input
X = tf.placeholder("float", [None, n_input])
Y = tf.placeholder("float", [None, n_classes])

mlp_layer_name = ['h1', 'b1', 'h2', 'b2', 'h3', 'b3', 'w_o', 'b_o']
logits = multilayer_perceptron(X, n_input, n_classes, mlp_layer_name)

loss_op = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=Y), name='loss_op')
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)
train_op = optimizer.minimize(loss_op, name='train_op')

saver = tf.train.Saver()

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())

    # Training cycle
    for epoch in range(training_epochs):
        avg_cost = 0.

        # Loop over all batches
        for i in range(total_batch):
            batch_x, batch_y = next(train_generator)

            # Run optimization op (backprop) and cost op (to get loss value)
            _, c = sess.run([train_op, loss_op], feed_dict={X: batch_x,
                                                            Y: batch_y})
            # Compute average loss
            avg_cost += c / total_batch

        print("Epoch: {:3d}, cost = {:.6f}".format(epoch+1, avg_cost))

    print("Optimization Finished!")
    saver.save(sess, 'model')
    print("Model saved")

Now load the pretrained model and continue training with it (continue.py).

# tf Graph input
X = tf.placeholder("float", [None, n_input])
Y = tf.placeholder("float", [None, n_classes])
mlp_layer_name = ['h1', 'b1', 'h2', 'b2', 'h3', 'b3', 'w_o', 'b_o']
logits = multilayer_perceptron(X, n_input, n_classes, mlp_layer_name)
loss_op = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=Y), name='loss_op')
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)
train_op = optimizer.minimize(loss_op, name='train_op')

with tf.Session() as sess:
    saver = tf.train.import_meta_graph('model.meta')
    saver.restore(sess, tf.train.latest_checkpoint('./')) # search for checkpoint file

    graph = tf.get_default_graph()

    for epoch in range(training_epochs):
        avg_cost = 0.

        # Loop over all batches
        for i in range(total_batch):
            batch_x, batch_y = next(train_generator)

            # Run optimization op (backprop) and cost op (to get loss value)
            _, c = sess.run([train_op, loss_op], feed_dict={X: batch_x,
                                                            Y: batch_y})
            # Compute average loss
            avg_cost += c / total_batch

        print("Epoch: {:3d}, cost = {:.6f}".format(epoch+1, avg_cost))

But it shows following error:

tensorflow.python.framework.errors_impl.FailedPreconditionError:
  Attempting to use uninitialized value h1
           [[Node: h1/read = IdentityT=DT_FLOAT, _class=["loc:@h1"], _device="/job:localhost/replica:0/task:0/cpu:0"]]

Here are my questions:

1. In many tensorflow's tutorial, it uses get_tensor_by_name() to load weights and biases. Here, I don't want to get weights and biases. I just want to load the model and continue training with it.

2. The error showed that tensor is uninitialized. However, I think saver.restore(sess, tf.train.latest_checkpoint('./')) should have loaded the weights and biases succesfully.

Here is multilayer_perceptron() if it helps to illustrate my questoins.

def multilayer_perceptron(x, n_input, n_classes, name):
    n_hidden_1 = 512
    n_hidden_2 = 256
    n_hidden_3 = 128
    # Store layers weight & bias
    weights = {
        'h1' : tf.get_variable(name[0], initializer=tf.random_normal([n_input, n_hidden_1])),
        'h2' : tf.get_variable(name[2], initializer=tf.random_normal([n_hidden_1, n_hidden_2])),
        'h3' : tf.get_variable(name[4], initializer=tf.random_normal([n_hidden_2, n_hidden_3])),
        'w_o': tf.get_variable(name[6], initializer=tf.random_normal([n_hidden_3, n_classes]))
    }
    biases = {
        'b1' : tf.get_variable(name[1], initializer=tf.random_normal([n_hidden_1])),
        'b2' : tf.get_variable(name[3], initializer=tf.random_normal([n_hidden_2])),
        'b3' : tf.get_variable(name[5], initializer=tf.random_normal([n_hidden_3])),
        'b_o': tf.get_variable(name[7], initializer=tf.random_normal([n_classes]))
    }

    layer_1 = tf.nn.relu(tf.add(tf.matmul(x      , weights['h1']), biases['b1']))
    layer_1 = tf.layers.dropout(layer_1, rate=0.5, training=True)
    layer_2 = tf.nn.relu(tf.add(tf.matmul(layer_1, weights['h2']), biases['b2']))
    layer_2 = tf.layers.dropout(layer_2, rate=0.3, training=True)
    layer_3 = tf.nn.relu(tf.add(tf.matmul(layer_2, weights['h3']), biases['b3']))
    layer_3 = tf.layers.dropout(layer_3, rate=0.1, training=True)
    out_layer = tf.matmul(layer_3, weights['w_o']) + biases['b_o']
    return out_layer

Body:
I think I found the answer. The key is that it doesn't need to call tf.train.import_meta_graph() if it has already uses saver.restore(sess, tf.train.latest_checkpoint('./')). Here is my code.

# tf Graph input
X = tf.placeholder("float", [None, n_input])
Y = tf.placeholder("float", [None, n_classes])
mlp_layer_name = ['h1', 'b1', 'h2', 'b2', 'h3', 'b3', 'w_o', 'b_o']
logits = multilayer_perceptron(X, n_input, n_classes, mlp_layer_name)
loss_op = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=Y), name='loss_op')
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)
train_op = optimizer.minimize(loss_op, name='train_op')

with tf.Session() as sess:
    saver = tf.train.Saver()
    saver.restore(sess, tf.train.latest_checkpoint('./')) # search for checkpoint file

    graph = tf.get_default_graph()

    for epoch in range(training_epochs):
        avg_cost = 0.

        # Loop over all batches
        for i in range(total_batch):
            batch_x, batch_y = next(train_generator)

            # Run optimization op (backprop) and cost op (to get loss value)
            _, c = sess.run([train_op, loss_op], feed_dict={X: batch_x,
                                                            Y: batch_y})
            # Compute average loss
            avg_cost += c / total_batch

        print("Epoch: {:3d}, cost = {:.6f}".format(epoch+1, avg_cost))


问:
How to find the last child in lodash map object?
I looping the array of lists by lodash map function and I've try to remove the Image on last child. But I couldn't find solution. </p>

```<code> const menus =[
    {
        name: 'Home',
        key:'dashboard'
    },
    {
        name:'change your pin',
        key:'resetpin'
    },
    {
        name:'Contact',
        key:'contact'
    },
    {
        name:'Sign Out',
        key:'signout'
    }
]
const menuList = map(menus, (el, i) => {
        return <Main>
            <Row>
                <Text />
                <Image />
            </Row>
        </Main>
})
</code>```

<p>I don't want the image on last loop </p>

答: why not just do slice? map(menus.slice(0, -1), (el, i) => ...)

Body:
I looping the array of lists by lodash map function and I've try to remove the Image on last child. But I couldn't find solution.

 const menus =[
    {
        name: 'Home',
        key:'dashboard'
    },
    {
        name:'change your pin',
        key:'resetpin'
    },
    {
        name:'Contact',
        key:'contact'
    },
    {
        name:'Sign Out',
        key:'signout'
    }
]
const menuList = map(menus, (el, i) => {
        return
            <Row>
                <Text />
                <Image />
            </Row>

})

I don't want the image on last loop


问:
JVM maxHeapSize and InitialHeapSize are not reflected in htop
I have a linux machine where I'm running a Java application.
I'm running the jvm with those parameters: -Xmx27231m -Xms27231m

However when I look at htop/top.
What I see for the system overall and the process specifically is that the jvm is actually not reserving the 27GB of heap I'm asking it to.
What I see instead is that
Virt: 32.8G
RES: 15.3G
SHR:16536

In all my other prod/qa/dev machines the RES reflects the exact amount (maybe a bit more) as the heap size I'm asking JVM to reserve for me.
However for one particular machine this is not the case.
I'm clueless of why this is happening.

I attached Java Mission Control to that process and I see that the InitialHeapSize and the MaxHeapSize actually have the correct value, however the type is not CommandLine but Ergonomic instead. I don't really know what that means.

Anyone?
Thanks

答:
The JVM doesn't pretouch the pages in advance, to reduce startup time. You can however use this option to force it to.

```<code>-XX:+AlwaysPreTouch -Xmx27g -Xms27g
</code>```

BTW This won't prevent the JVM releasing the memory back to the OS if it is not used (though the JVM rarely does this AFAIK), nor will it lock the heap into main memory to prevent swapping.

However for one particular machine this is not the case.

Most likely it has not had the right activity to cause the memory to be used lazily.

Body:
The JVM doesn't pretouch the pages in advance, to reduce startup time. You can however use this option to force it to.

-XX:+AlwaysPreTouch -Xmx27g -Xms27g

BTW This won't prevent the JVM releasing the memory back to the OS if it is not used (though the JVM rarely does this AFAIK), nor will it lock the heap into main memory to prevent swapping.

However for one particular machine this is not the case.

Most likely it has not had the right activity to cause the memory to be used lazily.


问:
Setting maximum number of characters of `UITextView ` and `UITextField `
I'd like to set a maximum number of characters allowed to be typed both in a UITextView and a UITextField. This number will be then shown in a little label (for user's reference, Twitter Style.)

答:
Swift 4/ Xcode 9.1

```<code>func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {

    let currentText = textView.text ?? ""
    guard let stringRange = Range(range, in: currentText) else { return false }
    let changedText = currentText.replacingCharacters(in: stringRange, with: text)
    return changedText.count <= 399 // Pass your character count here
}
</code>```

Body:
Swift 4/ Xcode 9.1

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {

    let currentText = textView.text ?? ""
    guard let stringRange = Range(range, in: currentText) else { return false }
    let changedText = currentText.replacingCharacters(in: stringRange, with: text)
    return changedText.count <= 399 // Pass your character count here
}


问:
Use python + Selenium to login,but can't find div
```<code># _*_coding:utf-8_*_
from selenium import webdriver

driver=webdriver.Chrome()
url="https://login.alibaba.com"
driver.get(url)
driver.implicitly_wait(3)
print(driver.page_source)
driver.quit()
</code>```

i want to login by selenium, but can't find the login id "fm-login-id"

答:
Alibaba's login is in different iFrame that's why you are not getting its id and got the error "Element not found"

I created one sample for you in java selenium and it's working.

```<code>driver.get("https://passport.alibaba.com/mini_login.htm?lang=en_us&appName=icbu&appEntrance=default&styleType=auto&bizParams=&notLoadSsoView=false&notKeepLogin=true&isMobile=false&ut=B8605a4b80fd5c7e8e8957efccc7ad5ea&showKeepLogin=true&showSnsLogin=true&cssLink=https%3A%2F%2Fu.alicdn.com%2Fcss%2F6v%2Frun%2Fcommon%2Fxman%2Fhavana-thirdpart-login.css&regUrl=https%3A%2F%2Faccounts.alibaba.com%2Fregister%2Fregister.htm%3Freturn_url%3Dhttp%253A%252F%252Fwww.alibaba.com&rnd=0.2729010632370805");
        Thread.sleep(3);
        driver.findElement(By.xpath("//*[@id='fm-login-id']")).sendKeys("Test_User");
</code>```

I ran this code and and it's working fine.

Body:
# _*_coding:utf-8_*_
from selenium import webdriver

driver=webdriver.Chrome()
url="https://login.alibaba.com"
driver.get(url)
driver.implicitly_wait(3)
print(driver.page_source)
driver.quit()

i want to login by selenium, but can't find the login id "fm-login-id"

Body:
Alibaba's login is in different iFrame that's why you are not getting its id and got the error "Element not found"

I created one sample for you in java selenium and it's working.

driver.get("https://passport.alibaba.com/mini_login.htm?lang=en_us&appName=icbu&appEntrance=default&styleType=auto&bizParams=&notLoadSsoView=false&notKeepLogin=true&isMobile=false&ut=B8605a4b80fd5c7e8e8957efccc7ad5ea&showKeepLogin=true&showSnsLogin=true&cssLink=https%3A%2F%2Fu.alicdn.com%2Fcss%2F6v%2Frun%2Fcommon%2Fxman%2Fhavana-thirdpart-login.css&regUrl=https%3A%2F%2Faccounts.alibaba.com%2Fregister%2Fregister.htm%3Freturn_url%3Dhttp%253A%252F%252Fwww.alibaba.com&rnd=0.2729010632370805");
        Thread.sleep(3);
        driver.findElement(By.xpath("//*[@id='fm-login-id']")).sendKeys("Test_User");

I ran this code and and it's working fine.


答:
Are you sure the context is open and it's the same from which your object has been extracted  ? is the object is still connected to the context ?
usually you create a new context in each call, you need to attach the object to the context change it state to modified and than use SaveChanges.
Otherwise, nothing is done.

```<code> context.Customers.Attach(myCustomre);
 context.ObjectStateManager.ChangeObjectState(myCustomre, System.Data.EntityState.Modified);
 context.SaveChanges();
</code>```

and for insert:

```<code>context.Customers.AddObject(newCustomer);
                context.SaveChanges();
</code>```

Title: ASP.NET MVC: No record added to database after POST

Body:
Are you sure the context is open and it's the same from which your object has been extracted  ? is the object is still connected to the context ?
usually you create a new context in each call, you need to attach the object to the context change it state to modified and than use SaveChanges.
Otherwise, nothing is done.

 context.Customers.Attach(myCustomre);
 context.ObjectStateManager.ChangeObjectState(myCustomre, System.Data.EntityState.Modified);
 context.SaveChanges();

and for insert:

context.Customers.AddObject(newCustomer);
                context.SaveChanges();


问:
Accessing a function/state of a component in a wrapping HOC
So I have a component A (extends React.component) and it is wrapped with a higher order component B.

In component B's methods, I need to setState for A, or call a function in A (so that it can do the setState) - how is this generally done?

I can paste actual code here, but I thought it may complicate matters if there are standard ways of handling this situation.

Edit: here's the code - isOpen needs to change for the Modal to close, and it needs to change in handleSubmit....

```<code>import React from 'react';
import Modal from 'react-modal';
import { withFormik, Form, Field } from 'formik';
import Yup from 'yup';

// first part of Formik integration
const formikEnhancer = withFormik({
  mapPropsToValues(props) {
    return {
      personName: props.email || '',
      personSurname: props.surname || '',
      personCongregation: props.congregation || ''
    }
  },
  validationSchema: Yup.object().shape({
    personName: Yup.string().required().min(1),
    personSurname: Yup.string().required().min(2),
    personCongregation: Yup.string().required().min(8)
  }),
  handleSubmit(values, {props, resetForm, setErrors, setSubmitting}) {
    submitNewPerson(values, {resetForm, setErrors, setSubmitting});
    props.testCall;
  }
});

function submitNewPerson(v, {resetForm, setErrors, setSubmitting}) {
  //e.preventDefault();

  congregations = [];
  congregations.push(v.personCongregation);

  const peep = {
    name: v.personName,
    surname: v.personSurname,
    congregations: congregations//,
    //startDate: Number(e.target.componentStartDate.value),
    //endDate: Number(e.target.componentEndDate.value)
  };
    // do the db insert here and check for errors
    setSubmitting(false);
  });
};

class AddPerson extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      error: undefined,
      isOpen: false
    }
  }

  componentWillMount() {
    Modal.setAppElement('body');
  }

  renderCong() {
    // this just maps out a list of select options
  }

  render() {
    return (
      <div>
        <button className="button" onClick={()=> this.setState({isOpen:true, error:undefined})}>+ Add Person</button>
        <Modal isOpen={this.state.isOpen} contentLabel="Add Person"
          className = "boxed-view__box" overlayClassName="boxed-view boxed-view--modal">
          <Form className="boxed-view__form">
            <div>
              <Field type="text" name="personName" placeholder="Name" />
            </div>
            <div>
                <Field type="text" name="personSurname" placeholder="Surname" />
            </div>
            <div>
             <Field component="select" name="personCongregation" value={this.state.cong}>
                <option key="0" value="">- Select Option -</option>
                {this.renderCong()}
              </Field>
            </div>
            <button disabled={this.props.isSubmitting} className="button">Add Person</button>
            <button disabled={this.props.isSubmitting} type="button" className="button button--secondary" onClick={
              ()=> {
                this.props.resetForm();
                this.setState({isOpen:false});
              }}>Cancel</button>
          </Form>

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

答: Figured it out - added my own onClick handler (instead of allowing Formik to call its handleSubmit method) - my handler then calls Formik's handleSubmit and then changes state depending on return value</p>

Body:
So I have a component A (extends React.component) and it is wrapped with a higher order component B.

In component B's methods, I need to setState for A, or call a function in A (so that it can do the setState) - how is this generally done?

I can paste actual code here, but I thought it may complicate matters if there are standard ways of handling this situation.

Edit: here's the code - isOpen needs to change for the Modal to close, and it needs to change in handleSubmit....

import React from 'react';
import Modal from 'react-modal';
import { withFormik, Form, Field } from 'formik';
import Yup from 'yup';

// first part of Formik integration
const formikEnhancer = withFormik({
  mapPropsToValues(props) {
    return {
      personName: props.email || '',
      personSurname: props.surname || '',
      personCongregation: props.congregation || ''
    }
  },
  validationSchema: Yup.object().shape({
    personName: Yup.string().required().min(1),
    personSurname: Yup.string().required().min(2),
    personCongregation: Yup.string().required().min(8)
  }),
  handleSubmit(values, {props, resetForm, setErrors, setSubmitting}) {
    submitNewPerson(values, {resetForm, setErrors, setSubmitting});
    props.testCall;
  }
});

function submitNewPerson(v, {resetForm, setErrors, setSubmitting}) {
  //e.preventDefault();

  congregations = [];
  congregations.push(v.personCongregation);

  const peep = {
    name: v.personName,
    surname: v.personSurname,
    congregations: congregations//,
    //startDate: Number(e.target.componentStartDate.value),
    //endDate: Number(e.target.componentEndDate.value)
  };
    // do the db insert here and check for errors
    setSubmitting(false);
  });
};

class AddPerson extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      error: undefined,
      isOpen: false
    }
  }

  componentWillMount() {
    Modal.setAppElement('body');
  }

  renderCong() {
    // this just maps out a list of select options
  }

  render() {
    return (

        <button className="button" onClick={()=> this.setState({isOpen:true, error:undefined})}>+ Add Person</button>
        <Modal isOpen={this.state.isOpen} contentLabel="Add Person"
          className = "boxed-view__box" overlayClassName="boxed-view boxed-view--modal">
          <Form className="boxed-view__form">

              <Field type="text" name="personName" placeholder="Name" />

                <Field type="text" name="personSurname" placeholder="Surname" />

             <Field component="select" name="personCongregation" value={this.state.cong}>
                <option key="0" value="">- Select Option -</option>
                {this.renderCong()}
              </Field>

            <button disabled={this.props.isSubmitting} className="button">Add Person</button>
            <button disabled={this.props.isSubmitting} type="button" className="button button--secondary" onClick={
              ()=> {
                this.props.resetForm();
                this.setState({isOpen:false});
              }}>Cancel</button>
          </Form>

        </Modal>

    )
  };
};


问:
AngularJS - Sorting data ascending / descending when column is clicked
I have the following view code:

```<code><tr ng-repeat="c in clients | orderBy:'code'">
    <td>{{c.firstname}} {{c.lastname}}</td>
    <td>{{c.telephone}}</td>
    <td>{{c.location}}</td>
    <td>{{c.code}}</td>
</tr>
</code>```

I want to change the orderBy:'code' when column is clicked, assume that the user clicked on the column location, i want the orderBy condition to change to 'location' instead of code, and to be in this form

```<code><tr ng-repeat="c in clients | orderBy:'location'">
</code>```

答:
angular.module('app', []).controller('ctrl', function($scope) {
  $scope.prefix = '+';
  $scope.sort = '';
  $scope.sortFn = function(name) {
    $scope.prefix = $scope.prefix == '-' ? '+' : '-';
    $scope.sort = $scope.prefix + name;
  }
  $scope.arrow = function(name){
    if($scope.sort.indexOf(name) != -1)
      return $scope.prefix == '+' ? '↑' : '↓';
    return '';
  }

  $scope.clients = [
    { name: 'Tom', age: 30 },
    { name: 'Max', age: 20 },
    { name: 'Sam', age: 40 },
    { name: 'Liza', age: 25 },
    { name: 'Henry', age: 35 }
  ]
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>table,
th,
td {
  border: 1px solid black;
  border-collapse: collapse;
}
th{
  cursor: pointer
}</code>```

      Name {{arrow("name")}}
      Age {{arrow("age")}}

      {{c.name}}
      {{c.age}}

```

Body:
I have the following view code:

    {{c.firstname}} {{c.lastname}}
    {{c.telephone}}
    {{c.location}}
    {{c.code}}

I want to change the orderBy:'code' when column is clicked, assume that the user clicked on the column location, i want the orderBy condition to change to 'location' instead of code, and to be in this form

Body:
angular.module('app', []).controller('ctrl', function($scope) {
  $scope.prefix = '+';
  $scope.sort = '';
  $scope.sortFn = function(name) {
    $scope.prefix = $scope.prefix == '-' ? '+' : '-';
    $scope.sort = $scope.prefix + name;
  }
  $scope.arrow = function(name){
    if($scope.sort.indexOf(name) != -1)
      return $scope.prefix == '+' ? '↑' : '↓';
    return '';
  }

  $scope.clients = [
    { name: 'Tom', age: 30 },
    { name: 'Max', age: 20 },
    { name: 'Sam', age: 40 },
    { name: 'Liza', age: 25 },
    { name: 'Henry', age: 35 }
  ]
})

table,
th,
td {
  border: 1px solid black;
  border-collapse: collapse;
}
th{
  cursor: pointer
}

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<table ng-app='app' ng-controller='ctrl'>
  <thead>
    <tr>
      <th ng-click='sortFn("name")'>Name {{arrow("name")}}</th>
      <th ng-click='sortFn("age")'>Age {{arrow("age")}}</th>
    </tr>
  </thead>
  <tbody>
    <tr ng-repeat="c in clients | orderBy:sort">
      <td>{{c.name}}</td>
      <td>{{c.age}}</td>
    </tr>
  </tbody>
</table>


答:
Either -- or a custom data type equivalent to it -- is the only way to do this.  Here's a dumb example:

```<code>stuff :: Int -> Either (Int,Int) [(Int,Int)]
stuff 0 = Left (0, 0)
stuff n = Right [ (x,x) | x <- [0..n] ]
</code>```

Then when somebody calls this function, they can pattern match to find out which of the two types it returned:

```<code>foo n = case stuff n of
            Left (a,b) -> ...
            Right pairs -> ...
</code>```

However, knowing nothing about your problem, in general I would recommend thinking a bit more about the meaning of your function.  What does it take, what does it return?  Be precise, mathematical. The simpler the answer, the more smoothly this function will work with the rest of your program and the concepts of Haskell.  For me, in such descriptions, Either rarely turns up.  How can you unify the two results?  Maybe you just return the singleton list [(a,b)] instead of Left (a,b), if that makes sense for your function.

Haskell does not play well with functions that try to be too smart, the type that you may be used to from Python or jQuery.  Keep it dumb and precise -- get your complexity from composing these simple pieces.  If you are curious about this, ask another question with more details about your problem, what you are trying to accomplish, and why you want it to work that way.  Sorry for the preaching :-)

Title: How to get a function to return different types

Body: So, I have a function with multiple definitions (guards), and depending on which one it matches, I'm trying to have it either return an (a,b) or [(a,b)], however the compiler is throwing up errors 'cause they're different types. I was trying to use Either to solve this, but probably not using it right :P. any help?

Body:
Either -- or a custom data type equivalent to it -- is the only way to do this.  Here's a dumb example:

stuff :: Int -> Either (Int,Int) [(Int,Int)]
stuff 0 = Left (0, 0)
stuff n = Right [ (x,x) | x <- [0..n] ]

Then when somebody calls this function, they can pattern match to find out which of the two types it returned:

foo n = case stuff n of
            Left (a,b) -> ...
            Right pairs -> ...

However, knowing nothing about your problem, in general I would recommend thinking a bit more about the meaning of your function.  What does it take, what does it return?  Be precise, mathematical. The simpler the answer, the more smoothly this function will work with the rest of your program and the concepts of Haskell.  For me, in such descriptions, Either rarely turns up.  How can you unify the two results?  Maybe you just return the singleton list [(a,b)] instead of Left (a,b), if that makes sense for your function.

Haskell does not play well with functions that try to be too smart, the type that you may be used to from Python or jQuery.  Keep it dumb and precise -- get your complexity from composing these simple pieces.  If you are curious about this, ask another question with more details about your problem, what you are trying to accomplish, and why you want it to work that way.  Sorry for the preaching :-)


答:
Maybe this:

```<code>df1$Name[!(df1$Name %in% t(df1[, 2:7]))] <- NA
</code>```

Notice, the , before the 2:7 so that the appropriate columns are selected and the t() which transposes these columns to make the %in% work on the vectors.

This solution is quite close to your second approach.

Title: Check multiple columns for value, replace with NA if not found in R

Body:
I have a data.frame like this:

#df1
ID     a1      a2     a3      b1      b2      b3     Date    Name
3xy    NA      NA     NA     Ben      Bob     Alex   12/3    Bob
4lm    John    Bill   Sue    NA       NA      NA     12/5    Mark

I want those in the "name" column to be replaced by NA if they don't appear in any of the a1 through b3 columns in their row, like this:

ID     a1      a2     a3      b1      b2      b3     Date    Name
3xy    NA      NA     NA     Ben      Bob     Alex   12/3    Bob
4lm    John    Bill   Sue    NA       NA      NA     12/5    NA

I can't figure out why what's below doesn't work:

df1$Name <- with(df1, ifelse(Name %in% df1[2:7], Name, NA))

or

df1$Name[!(df1$Name %in% df1[2:7])] <- NA

Both statements replace the entire "Name" column with NA, failing to preserve the names that appear in columns a1 through b3.

Body:
Maybe this:

df1$Name[!(df1$Name %in% t(df1[, 2:7]))] <- NA

Notice, the , before the 2:7 so that the appropriate columns are selected and the t() which transposes these columns to make the %in% work on the vectors.

This solution is quite close to your second approach.


问:
How to create a fallback intent in Amazon Lex or call a Lamda when error is triggered?
I have a small bot on amazon lex, I am unable to figure out a way to define a default intent or a fallback intent.</p>

答:
As of now, Amazon Lex does not support any fallback intent or default intent. However I have found a workaround. Here's what I did.

Setup an API Gateway and Lambda function in between your chat-client and the Lex.

Your chat-client will send request to API Gateway, API Gateway will forward this to Lambda function and Lambda function will forward the request to Lex (Lex will have one more lambda function). While returning the response from Lex, you can check in the Lambda function if it's an error message and trigger some action.

In the Lambda function we can use something like this:

```<code>import logging
import boto3

logger = logging.getLogger()
logger.setLevel(logging.DEBUG)

client_run = boto3.client('lex-runtime')
client_model = boto3.client('lex-models')

def lambda_handler(event, context):
    response = client_run.post_text(
        botName='name_of_your_bot',
        botAlias='alias_of_your_bot',
        userId='some_id',
        sessionAttributes={
            'key1': 'value1'
        },
        inputText=event['user_query']
    )
    bot_details = client_model.get_bot(
    name='name_of_your_bot',
    versionOrAlias='$LATEST'
    )
    for content in bot_details['clarificationPrompt']['messages']:
        if response["message"] == content['content']:
            return error_handling_method(event)
    for content in bot_details['abortStatement']['messages']:
        if response["message"] == content['content']:
            return error_handling_method(event)
    return response["message"]
</code>```

Hope it helps.

Body:
As of now, Amazon Lex does not support any fallback intent or default intent. However I have found a workaround. Here's what I did.

Setup an API Gateway and Lambda function in between your chat-client and the Lex.

Your chat-client will send request to API Gateway, API Gateway will forward this to Lambda function and Lambda function will forward the request to Lex (Lex will have one more lambda function). While returning the response from Lex, you can check in the Lambda function if it's an error message and trigger some action.

In the Lambda function we can use something like this:

import logging
import boto3

logger = logging.getLogger()
logger.setLevel(logging.DEBUG)

client_run = boto3.client('lex-runtime')
client_model = boto3.client('lex-models')

def lambda_handler(event, context):
    response = client_run.post_text(
        botName='name_of_your_bot',
        botAlias='alias_of_your_bot',
        userId='some_id',
        sessionAttributes={
            'key1': 'value1'
        },
        inputText=event['user_query']
    )
    bot_details = client_model.get_bot(
    name='name_of_your_bot',
    versionOrAlias='$LATEST'
    )
    for content in bot_details['clarificationPrompt']['messages']:
        if response["message"] == content['content']:
            return error_handling_method(event)
    for content in bot_details['abortStatement']['messages']:
        if response["message"] == content['content']:
            return error_handling_method(event)
    return response["message"]

Hope it helps.


问:
Jenkins Play! Plugin: Failure to configure auto-install on Cloudbees server
I have installed the Jenkins plugin for the Play! framework: https://wiki.jenkins-ci.org/display/JENKINS/play-plugin

However, I run into a problem configuring that plugin. The Jenkins server doesn't have Play installed, so I tried to configure the auto-install, using the "Install automatically" option. Unfortunately, when I pass the URL to the Typesafe Activator's ZIP archive, I get a handshake failure.

The Jenkins server is a part of the Cloudbees cloud.

Any ideas on what is going wrong and how to deal with it?

EDIT: Changing "https" to "http" resolves the handshake problem. However, Play does not get installed on the Jenkins server. The build does not find the "activator" executable. I suspect this may be an issue with the Play plugin for Jenkins.

答:
it seems your java cacerts is not having correct certificate. you may try following steps.

Step 1 : Get root certificate of https://www.google.com

Open https://www.google.com in a chrome browser.

Select Inspect from context menu(right clicking on page) and navigate to security tab

Click on view certificates

Click on top most certificate on hierarchy and confirm it is tailed with Root CA phrase.

drag and drop that image which you saw written certificate on desktop.

Thats it! you got your root certificate!

Step 2 : install certificate to your java cacerts

please verify you have system variable JAVA_HOME declared and you will perform these steps on that jre cacerts only!

Navigate to cacerts by JAVA_HOME/jre/lib/security/cacerts

Download and install keytool explorer it is available for all platforms

open cacerts in that tool and import cetificate by "import trusted certificate" button.

Save your changes (you may come across issue if it is mac and you do not have write access!)

Step 3 : Restart jenkins

You should not get ssl handshake problem now onwards.


问:
css accordion right arrow and down arrow not working properly
hai I am tyring use accordion, by default it was showing "V" down arrow on starting if click a tab(On first open) it shows same down arrow, and if i hide the tab it is getting back to normal ">" right arrow and then show and hide works good.

I need the right arrow to be shown on default if i click open arrow should move down, i tried many things and couldnt get the desired result please check out the fiddle

.panel-heading .accordion-toggle:after {
    /* symbol for "opening" panels */
    font-family: 'Glyphicons Halflings';  /* essential for enabling glyphicon */
    content: "\e114";    /* adjust as needed, taken from bootstrap.css */
    float: right;        /* adjust as needed */
    color: grey;         /* adjust as needed */
}
.panel-heading .accordion-toggle.collapsed:after {
    /* symbol for "collapsed" panels */
    content: "\e080";    /* adjust as needed, taken from bootstrap.css */
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- Latest compiled and minified Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">

<div class = "container">

  <div class="panel-group" id="accordion">
  <div class="panel panel-default">
    <div class="panel-heading">
      <h4 class="panel-title">

          Collapsible Group Item #1

      </h4>
    </div>
    <div id="collapseOne" class="panel-collapse collapse">
      <div class="panel-body">
        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
      </div>
    </div>
  </div>
  <div class="panel panel-default">
    <div class="panel-heading">
      <h4 class="panel-title">

          Collapsible Group Item #2

      </h4>
    </div>
    <div id="collapseTwo" class="panel-collapse collapse">
      <div class="panel-body">
        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
      </div>
    </div>
  </div>
  <div class="panel panel-default">
    <div class="panel-heading">
      <h4 class="panel-title">

          Collapsible Group Item #3

      </h4>
    </div>
    <div id="collapseThree" class="panel-collapse collapse">
      <div class="panel-body">
        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
      </div>
    </div>
  </div>
</div>

</div> <!-- end container -->

<!-- Latest compiled and minified JavaScript -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script></code>```

答:
Add class collapsed on your  tags. They render first as open because of the missing class

https://jsfiddle.net/jpgc24rg/

```<code><a class="accordion-toggle collapsed" data-toggle="collapse" data-parent="#accordion" href="#collapseOne">
</code>```

Body:
hai I am tyring use accordion, by default it was showing "V" down arrow on starting if click a tab(On first open) it shows same down arrow, and if i hide the tab it is getting back to normal ">" right arrow and then show and hide works good.

I need the right arrow to be shown on default if i click open arrow should move down, i tried many things and couldnt get the desired result please check out the fiddle

.panel-heading .accordion-toggle:after {
    /* symbol for "opening" panels */
    font-family: 'Glyphicons Halflings';  /* essential for enabling glyphicon */
    content: "\e114";    /* adjust as needed, taken from bootstrap.css */
    float: right;        /* adjust as needed */
    color: grey;         /* adjust as needed */
}
.panel-heading .accordion-toggle.collapsed:after {
    /* symbol for "collapsed" panels */
    content: "\e080";    /* adjust as needed, taken from bootstrap.css */
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">

          Collapsible Group Item #1

        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.

          Collapsible Group Item #2

        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.

          Collapsible Group Item #3

        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.

Body:
Add class collapsed on your <a> tags. They render first as open because of the missing class

https://jsfiddle.net/jpgc24rg/

<a class="accordion-toggle collapsed" data-toggle="collapse" data-parent="#accordion" href="#collapseOne">


问:
Why doesn't HTML5 read my css?
No matter what i tried or changed it didnt work. My CSS file is in the same folder as my HTML. Here's the code:

```<code> <!DOCTYPE html>
    <html>
     <head>
      <link rel="stylesheet" type="text/css" href="style.css">
       <title>Photos'r'us</title>
      <div="header">
         <img id="banner" src="https://i.imgur.com/iTt5U3E.jpg" alt:"pic">
          <ul id="navigation">
             <li>Home</li>
             <li>About</li>
             <li>Portfolio</li>
             <li>Contact</li>
              </ul>
        </div>
      </head>
      <body>
      </body>
       </html>
</code>```

and this is the CSS:

```<code>@charset "UTF-8";

#header {
height: 230px;
background-image: url(https://i.imgur.com/iTt5U3E.jpg);
background-repeat: no-repeat;
font-family: 'Ariel', sans-serif;
}
#banner {
float: left;
width: 100px;
height: 400px;
margin: 20px;
}
#navigation {
display: inline;
}
</code>```

please help.

答:
You are using wrong attribute syntax

@charset "UTF-8";

#header {
height: 230px;
background-image: url(https://i.imgur.com/iTt5U3E.jpg);
background-repeat: no-repeat;
font-family: 'Ariel', sans-serif;
}
#banner {
float: left;
width: 100px;
height: 80px;
margin: 20px;
}
#navigation {
display: inline;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
    <html>
     <head>
      <link rel="stylesheet" type="text/css" href="style.css">
       <title>Photos'r'us</title>
      </head>
      <body>
      <div id="header">
         <img id="banner" src="https://i.imgur.com/iTt5U3E.jpg"  alt="pic">
          <ul id="navigation">
             <li>Home</li>
             <li>About</li>
             <li>Portfolio</li>
             <li>Contact</li>
              </ul>
        </div>
      </body>
       </html></code>```

id was missing here

alt="pic" was set wrongly

I changed width:80px; to better display, And its working .

Title: Why doesn't HTML5 read my css?

Body:
No matter what i tried or changed it didnt work. My CSS file is in the same folder as my HTML. Here's the code:

 <!DOCTYPE html>

      <link rel="stylesheet" type="text/css" href="style.css">
       <title>Photos'r'us</title>

Home

About

Portfolio

Contact

and this is the CSS:

@charset "UTF-8";

#header {
height: 230px;
background-image: url(https://i.imgur.com/iTt5U3E.jpg);
background-repeat: no-repeat;
font-family: 'Ariel', sans-serif;
}
#banner {
float: left;
width: 100px;
height: 400px;
margin: 20px;
}
#navigation {
display: inline;
}

please help.

Body:
You are using wrong attribute syntax

@charset "UTF-8";

#header {
height: 230px;
background-image: url(https://i.imgur.com/iTt5U3E.jpg);
background-repeat: no-repeat;
font-family: 'Ariel', sans-serif;
}
#banner {
float: left;
width: 100px;
height: 80px;
margin: 20px;
}
#navigation {
display: inline;
}

<!DOCTYPE html>
    <html>
     <head>
      <link rel="stylesheet" type="text/css" href="style.css">
       <title>Photos'r'us</title>
      </head>
      <body>
      <div id="header">
         <img id="banner" src="https://i.imgur.com/iTt5U3E.jpg"  alt="pic">
          <ul id="navigation">
             <li>Home</li>
             <li>About</li>
             <li>Portfolio</li>
             <li>Contact</li>
              </ul>
        </div>
      </body>
       </html>

id was missing here <div id="header">

alt="pic" was set wrongly

I changed width:80px; to better display, And its working .


问:
iphone - how to refresh a uiview with a scrollview?
any advice welcome! :)

My screen design is landscape with text on the left (this is in the main view) and a scrollview on the right (which contains an interactive map image)

The mainviewcontroller contains the scrollview as an outlet.
In the scrollviewcontroller I add a 'map' view into the scrollview.
In the mapviewcontroller I update an array in the appdelegate, depending on the user input.

I would now like to refresh the main uiview that contains the scrollview to display the updated text from the appdel array - whenever the user clicks a button.

答:
You should call your view's -(void)setNeedsDisplay method to cause it to redraw.

```<code>[myView setNeedsDisplay];
</code>```

See Apple's reference documentation here: http://developer.apple.com/library/ios/#documentation/uikit/reference/UIView_Class/UIView/UIView.html%23//apple_ref/doc/uid/TP40006816-CH3-BBCCADHC

Body:
You should call your view's -(void)setNeedsDisplay method to cause it to redraw.

[myView setNeedsDisplay];

See Apple's reference documentation here: http://developer.apple.com/library/ios/#documentation/uikit/reference/UIView_Class/UIView/UIView.html%23//apple_ref/doc/uid/TP40006816-CH3-BBCCADHC