问:
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?

答:
What worked for me:

I used IO Spring Platform for resolving dependencies and spring library versions in pom.xml:

```<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>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>io.spring.platform</groupId>
            <artifactId>platform-bom</artifactId>
            <version>Brussels-SR6</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-jpa</artifactId>
    </dependency>

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.5.2</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.5.2</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>2.5.2</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>${javax.servlet-api.version}</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>

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.21</version> <!-- or use LATEST -->
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-simple</artifactId>
        <version>1.7.21</version> <!-- or use LATEST -->
    </dependency>
</dependencies>
</code>```

Added EntityManager, TransactionManager and DataSource beans to my config:

```<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;
}

@Bean
public JdbcTemplate jdbcTemplate(DataSource dataSource) {
    JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
    jdbcTemplate.setResultsMapCaseInsensitive(true);
    return jdbcTemplate;
}

@Bean
public EntityManagerFactory entityManagerFactory() {

    HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
    vendorAdapter.setGenerateDdl(true);

    LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
    factory.setJpaVendorAdapter(vendorAdapter);
    factory.setPackagesToScan("com.kspt.pms");
    factory.setDataSource(dataSource());
    factory.setPersistenceUnitName("my-pms");
    factory.setPersistenceProviderClass(HibernatePersistenceProvider.class);
    factory.afterPropertiesSet();
    return factory.getObject();
}

@Bean
public PlatformTransactionManager transactionManager() {

    JpaTransactionManager txManager = new JpaTransactionManager();
    txManager.setEntityManagerFactory(entityManagerFactory());
    return txManager;
}
</code>```

Added persistence.xml file to resources/META-INF and declared my persistance unit in it:

```<code><persistence-unit name="my-pms">
    <class>com.kspt.pms.entity.BugReport</class>
    <class>com.kspt.pms.entity.Comment</class>
    <class>com.kspt.pms.entity.Message</class>
    <class>com.kspt.pms.entity.Milestone</class>
    <class>com.kspt.pms.entity.Project</class>
    <class>com.kspt.pms.entity.Ticket</class>
    <class>com.kspt.pms.entity.User</class>
</persistence-unit>
</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:
What worked for me:

I used IO Spring Platform for resolving dependencies and spring library versions in pom.xml:

<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>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>io.spring.platform</groupId>
            <artifactId>platform-bom</artifactId>
            <version>Brussels-SR6</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-jpa</artifactId>
    </dependency>

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.5.2</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.5.2</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>2.5.2</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>${javax.servlet-api.version}</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>

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.21</version> <!-- or use LATEST -->
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-simple</artifactId>
        <version>1.7.21</version> <!-- or use LATEST -->
    </dependency>
</dependencies>

Added EntityManager, TransactionManager and DataSource beans to my config:

@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;
}

@Bean
public JdbcTemplate jdbcTemplate(DataSource dataSource) {
    JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
    jdbcTemplate.setResultsMapCaseInsensitive(true);
    return jdbcTemplate;
}

@Bean
public EntityManagerFactory entityManagerFactory() {

    HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
    vendorAdapter.setGenerateDdl(true);

    LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
    factory.setJpaVendorAdapter(vendorAdapter);
    factory.setPackagesToScan("com.kspt.pms");
    factory.setDataSource(dataSource());
    factory.setPersistenceUnitName("my-pms");
    factory.setPersistenceProviderClass(HibernatePersistenceProvider.class);
    factory.afterPropertiesSet();
    return factory.getObject();
}

@Bean
public PlatformTransactionManager transactionManager() {

    JpaTransactionManager txManager = new JpaTransactionManager();
    txManager.setEntityManagerFactory(entityManagerFactory());
    return txManager;
}

Added persistence.xml file to resources/META-INF and declared my persistance unit in it:

<persistence-unit name="my-pms">
    <class>com.kspt.pms.entity.BugReport</class>
    <class>com.kspt.pms.entity.Comment</class>
    <class>com.kspt.pms.entity.Message</class>
    <class>com.kspt.pms.entity.Milestone</class>
    <class>com.kspt.pms.entity.Project</class>
    <class>com.kspt.pms.entity.Ticket</class>
    <class>com.kspt.pms.entity.User</class>
</persistence-unit>


来源: stackexchange

问:
JS search in object values
I have an array of homogeneous objects like so;

```<code>[
  {
    "foo" : "bar",
    "bar" : "sit"
  },
  {
    "foo" : "lorem",
    "bar" : "ipsum"
  },
  {
    "foo" : "dolor",
    "bar" : "amet"
  }
]
</code>```

I'd like to search these objects' values (not keys) with a keyword, and return an array of objects that contain the keyword in any of the values.

So for example, with a keyword r, I would get all the objects ("baR" in object #1, "loRem" in object #2 and "doloR" in object #3). With a keyword lo, I would get objects 2 and 3 ("LOrem" and "doLOr"), with a, I'd get objects 1 and 3, ("bAr" and "Amet"). With the keyword foo however, I would get an empty array, since "foo" is a key, and isn't found in any of the values (unlike "bar")... you get the idea.

How would I go about doing this? Thanks a lot in advance!

答:
Just another variation using ES6, this is what I use.

```<code>// searched keywords
const searchedWord = "My searched exp";

// array of objects
let posts = [
    {
        text_field: "lorem ipsum doleri imet",
        _id: "89789UFJHDKJEH98JDKFD98"
    },
    {
        text_field: "ipsum doleri imet",
        _id: "JH738H3JKJKHJK93IOHLKL"
    }
];

// search results will be pushed here
let matches = [];

// regular exp for searching
let regexp = new RegExp(searchedWord, 'g');

// looping through posts to find the word
posts.forEach((post) => {
    if (post["text_field"].match(regexp)) matches.push(post);
});
</code>```

ContentLicense: CC BY-SA 3.0

Title: JS search in object values

Body:
I have an array of homogeneous objects like so;

[
  {
    "foo" : "bar",
    "bar" : "sit"
  },
  {
    "foo" : "lorem",
    "bar" : "ipsum"
  },
  {
    "foo" : "dolor",
    "bar" : "amet"
  }
]

I'd like to search these objects' values (not keys) with a keyword, and return an array of objects that contain the keyword in any of the values.

So for example, with a keyword r, I would get all the objects ("baR" in object #1, "loRem" in object #2 and "doloR" in object #3). With a keyword lo, I would get objects 2 and 3 ("LOrem" and "doLOr"), with a, I'd get objects 1 and 3, ("bAr" and "Amet"). With the keyword foo however, I would get an empty array, since "foo" is a key, and isn't found in any of the values (unlike "bar")... you get the idea.

How would I go about doing this? Thanks a lot in advance!

Body:
Just another variation using ES6, this is what I use.

// searched keywords
const searchedWord = "My searched exp";

// array of objects
let posts = [
    {
        text_field: "lorem ipsum doleri imet",
        _id: "89789UFJHDKJEH98JDKFD98"
    },
    {
        text_field: "ipsum doleri imet",
        _id: "JH738H3JKJKHJK93IOHLKL"
    }
];

// search results will be pushed here
let matches = [];

// regular exp for searching
let regexp = new RegExp(searchedWord, 'g');

// looping through posts to find the word
posts.forEach((post) => {
    if (post["text_field"].match(regexp)) matches.push(post);
});

ContentLicense: CC BY-SA 4.0


问:
Am learning basic java and i got wrong output
In the code below I am trying to convert char to int. Then I want to print the value of b, but I am getting 155 as output. </p>

```<code>public class Maths {

    static int age = 39, age2 = 49;

    public static void main(String Args[]) {
        int a = 's';
        int b = a;
        System.out.println(a);
        System.out.println(b);
    }
}
</code>```

答:
Change your code to this for printing your character 's' and 115 both:

```<code>public class cn{

    static int age=39 , age2=49 ;

     public static void main (String Args[])

            {
            int a='s'; // Storing ASCII of 's' i.e. 115
            int b=a; // Coping 115 in b

            System.out.printf("%c\n",a); // to print s using char literal
            System.out.println(b); // this print 115

        }
    }
</code>```

In your code you are initializing int with a char that is storing ASCII of 's'(115) and then you copied that in b so the value in b is 115.

Body:
In the code below I am trying to convert char to int. Then I want to print the value of b, but I am getting 155 as output.

public class Maths {

    static int age = 39, age2 = 49;

    public static void main(String Args[]) {
        int a = 's';
        int b = a;
        System.out.println(a);
        System.out.println(b);
    }
}

Body:
Change your code to this for printing your character 's' and 115 both:

public class cn{

    static int age=39 , age2=49 ;

     public static void main (String Args[])

            {
            int a='s'; // Storing ASCII of 's' i.e. 115
            int b=a; // Coping 115 in b

            System.out.printf("%c\n",a); // to print s using char literal
            System.out.println(b); // this print 115

        }
    }

In your code you are initializing int with a char that is storing ASCII of 's'(115) and then you copied that in b so the value in b is 115.


问:
PHP Calling a model method multiple times with having different value for parameter in codeiginter
I created a method in the model to get data from the database and then call it in the controller for multiple time with different method parameters($param) values. This is working for only one parameter value which one comes first. I Know i am doing it in wrong way but i am unable to find the solution for this. please help.

Actually, I am trying to have category based on their type('wordpress', 'magento', 'shopify') form database

My_model.php

```<code>class My_model extends CI_Model{

  public function fun_name($param){
       return $this->db->get_where('categories', array('type' => '$param'));
  }

}
</code>```

My_controller.php

```<code>class My_controller extends CI_Controller{
   public function get_data(){
       $this->load->model('my_model');
       $data = array(
           'first'   =>   $this->my_model->fun_name('wordpress'),
           'second'  =>   $this->my_model->fun_name('magento'),
           'third'   =>   $this->my_model->fun_name('shopify')
        );
       $this->load->view('index', $data);
   }
}
</code>```

答:
Can you try?

your controller

```<code>class My_controller extends CI_Controller{
   public function get_data(){
       $this->load->model('my_model');
       $data['data'] = array(
           'first'   =>   $this->my_model->fun_name('param1'),
           'second'  =>   $this->my_model->fun_name('param2'),
           'third'   =>   $this->my_model->fun_name('param3')
        );
       $this->load->view('index', $data);
   }
}
</code>```

model

```<code>class My_model extends CI_Model{

  public function fun_name($param){
       return $this->db->get_where('categories', array('type' => $param))->row()->category_name;
  }

}
</code>```

view

```<code><table>
    <tr>
        <td>id</td>
        <td>name</td>
        <td>type</td>
    </tr>
    <?php
    $i = 0;
    foreach($data as $key => $value) {
        $i++;
        ?>
    <tr>
        <td><?php echo $i; ?></td>
        <td><?php echo $key; ?></td>
        <td><?php echo $value; ?></td>
    </tr>
    <?php } ?>
</table>
</code>```

Body:
I created a method in the model to get data from the database and then call it in the controller for multiple time with different method parameters($param) values. This is working for only one parameter value which one comes first. I Know i am doing it in wrong way but i am unable to find the solution for this. please help.

Actually, I am trying to have category based on their type('wordpress', 'magento', 'shopify') form database

My_model.php

class My_model extends CI_Model{

  public function fun_name($param){
       return $this->db->get_where('categories', array('type' => '$param'));
  }

}

My_controller.php

class My_controller extends CI_Controller{
   public function get_data(){
       $this->load->model('my_model');
       $data = array(
           'first'   =>   $this->my_model->fun_name('wordpress'),
           'second'  =>   $this->my_model->fun_name('magento'),
           'third'   =>   $this->my_model->fun_name('shopify')
        );
       $this->load->view('index', $data);
   }
}

Body:
Can you try?

your controller

class My_controller extends CI_Controller{
   public function get_data(){
       $this->load->model('my_model');
       $data['data'] = array(
           'first'   =>   $this->my_model->fun_name('param1'),
           'second'  =>   $this->my_model->fun_name('param2'),
           'third'   =>   $this->my_model->fun_name('param3')
        );
       $this->load->view('index', $data);
   }
}

model

class My_model extends CI_Model{

  public function fun_name($param){
       return $this->db->get_where('categories', array('type' => $param))->row()->category_name;
  }

}

view

<table>
    <tr>
        <td>id</td>
        <td>name</td>
        <td>type</td>
    </tr>
    <?php
    $i = 0;
    foreach($data as $key => $value) {
        $i++;
        ?>
    <tr>
        <td><?php echo $i; ?></td>
        <td><?php echo $key; ?></td>
        <td><?php echo $value; ?></td>
    </tr>
    <?php } ?>
</table>


问:
Using Django's Paginator class with a MongoDB cursor
Is there a known method of extending the MongoDB cursor object to make it compatible with Django's django.core.paginator.Paginator class?

Or, maybe, extend Django's class?

答:
I was facing the same issue and implemented my own Paginator class that works. Here's the code:

```<code>from django.core.paginator import Paginator, Page

class MongoPaginator(Paginator):
    """
    Custom subclass of Django's Paginator to work with Mongo cursors.
    """
    def _get_page(self, *args, **kwargs):
        """
        Returns an instance of a single page. Replaced with our custom
        MongoPage class.
        """
        return MongoPage(*args, **kwargs)

    def page(self, number):
        """
        Returns a Page object for the given 1-based page number.
        Important difference to standard Paginator: Creates a clone of the
        cursor so we can get multiple slices.
        """
        number = self.validate_number(number)
        bottom = (number - 1) * self.per_page
        top = bottom + self.per_page
        if top + self.orphans >= self.count:
            top = self.count
        return self._get_page(
            self.object_list.clone()[bottom:top], number, self
        )

class MongoPage(Page):
    """
    Custom Page class for our MongoPaginator. Just makes sure the cursor is
    directly converted to list so that we can use len(object_list).
    """
    def __init__(self, object_list, number, paginator):
        self.object_list = list(object_list)
        self.number = number
        self.paginator = paginator
</code>```

The main changes are:

Each Page should get a clone of the cursor, because slices work only once per cursor

Each Page should also directly convert it to a list so that len() works

Here is a helper function to use it in views:

```<code>def get_paginated_cursor(request, cursor, per_page=25, param='page'):
    """
    Helper to deal with some standard pagination. Pass a request and a
    cursor and it will return a paginated version of it.
    """
    paginator = MongoPaginator(cursor, per_page)

    page = request.GET.get(param, 1)
    try:
        cursor = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        cursor = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        cursor = paginator.page(paginator.num_pages)

    return cursor
</code>```

Then you can do:

```<code>def some_view_function(request):
    messages_cursor = db.messages.find({})
    messages = get_paginated_cursor(request, messages_cursor)
</code>```

Body:
I was facing the same issue and implemented my own Paginator class that works. Here's the code:

from django.core.paginator import Paginator, Page

class MongoPaginator(Paginator):
    """
    Custom subclass of Django's Paginator to work with Mongo cursors.
    """
    def _get_page(self, *args, **kwargs):
        """
        Returns an instance of a single page. Replaced with our custom
        MongoPage class.
        """
        return MongoPage(*args, **kwargs)

    def page(self, number):
        """
        Returns a Page object for the given 1-based page number.
        Important difference to standard Paginator: Creates a clone of the
        cursor so we can get multiple slices.
        """
        number = self.validate_number(number)
        bottom = (number - 1) * self.per_page
        top = bottom + self.per_page
        if top + self.orphans >= self.count:
            top = self.count
        return self._get_page(
            self.object_list.clone()[bottom:top], number, self
        )

class MongoPage(Page):
    """
    Custom Page class for our MongoPaginator. Just makes sure the cursor is
    directly converted to list so that we can use len(object_list).
    """
    def __init__(self, object_list, number, paginator):
        self.object_list = list(object_list)
        self.number = number
        self.paginator = paginator

The main changes are:

Each Page should get a clone of the cursor, because slices work only once per cursor

Each Page should also directly convert it to a list so that len() works

Here is a helper function to use it in views:

def get_paginated_cursor(request, cursor, per_page=25, param='page'):
    """
    Helper to deal with some standard pagination. Pass a request and a
    cursor and it will return a paginated version of it.
    """
    paginator = MongoPaginator(cursor, per_page)

    page = request.GET.get(param, 1)
    try:
        cursor = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        cursor = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        cursor = paginator.page(paginator.num_pages)

    return cursor

Then you can do:

def some_view_function(request):
    messages_cursor = db.messages.find({})
    messages = get_paginated_cursor(request, messages_cursor)


问:
How can I check if an XMLHttpRequest to my public API is from my own webapp or from a third-party client (to ensure priority)?
Does anybody know of a way of checking on the API side if a XMLHttpRequest has been made from my own web-application (ie. from the JS I have written) or from a third-party application...

The problem, to me, seems to be that because the JS is run on the client and thus accessible to anyone I have no way of secretly communicating to the API server who I am. I think this is useful because otherwise I cannot prioritize requests from my own application over third-party clients in case of high usage.

I could obviously send some non-documented parameters but these can be spoofed.

Anybody with some ideas?

答:
A couple of ideas come to mind.  I understand that secrets never last, so I agree that's not a good option.

You could run another instance on a different unadvertised port

You could do it over SSL and use certs to identify the client

A simple but less secure way would be to use cookies

You could go by IP address, but that could be an administrative nightmare

ContentLicense: CC BY-SA 2.5


问:
Unable to change image for the button in swift 3?
In my code for checkmark I used button to change images for selected and unselected but unable to implement if I click on it's changing to unchecked but again selecting button it's unable to change to check image can anyone help me how to resolve this ?</p>

```<code>var checkedImage = UIImage(named: "check")! as UIImage
var uncheckedImage = UIImage(named: "uncheck")! as UIImage
var isChecked: Bool = true
var checkMarkSelected = 0

checkMarkButton.addTarget(self, action: #selector(checkMarkAction(button:)), for: .touchUpInside)

func checkMarkAction(button : UIButton) {
        if isChecked == true {
            checkMarkButton.setImage(checkedImage, for: .selected)
            isChecked = false
            checkMarkSelected = 1
        }
        else {
            checkMarkButton.setImage(uncheckedImage, for: .normal)
            isChecked = true
            checkMarkSelected = 0
        }
    }
</code>```

答:
I think that you should add the action in the viewDidLoad() function of your view controller for that button or, if you are declaring it in a stand-alone UIButton inherited class in order to reuse it in the future in many view controllers, you should add the target in the initialiser of the UIButton.

If the code is written in that way is even strange that Xcode is not giving you warnings...

EDIT: This is a code snippet of how I would do it

```<code>//Comments

import UIKit

class ViewController: UIViewController {

  //link this to the checkmark buttons
  //subclass UIButton making a button with the property isChecked: Bool
  @IBOutlet weak var checkmarkButton: UICheckButton!

  var checkMarkSelected = 0

  override function viewDidLoad() {
    //do stuff with your viewdidload
  }

  //link this to the checkmark buttons
  @IBAction func checkMarkAction(sender: UICheckButton) {
        if sender.isChecked == false {
            let checkedImage = UIImage(named: "check")
            checkMarkButton.setImage(checkedImage, for: .normal)
            sender.isChecked = true
            checkMarkSelected += checkMarkSelected
        } else {
            let uncheckedImage = UIImage(named: "uncheck")
            checkMarkButton.setImage(uncheckedImage, for: .normal)
            sender.isChecked = false
            checkMarkSelected -= checkMarkSelected
        }
  }
</code>```

Body:
In my code for checkmark I used button to change images for selected and unselected but unable to implement if I click on it's changing to unchecked but again selecting button it's unable to change to check image can anyone help me how to resolve this ?

var checkedImage = UIImage(named: "check")! as UIImage
var uncheckedImage = UIImage(named: "uncheck")! as UIImage
var isChecked: Bool = true
var checkMarkSelected = 0

checkMarkButton.addTarget(self, action: #selector(checkMarkAction(button:)), for: .touchUpInside)

func checkMarkAction(button : UIButton) {
        if isChecked == true {
            checkMarkButton.setImage(checkedImage, for: .selected)
            isChecked = false
            checkMarkSelected = 1
        }
        else {
            checkMarkButton.setImage(uncheckedImage, for: .normal)
            isChecked = true
            checkMarkSelected = 0
        }
    }

Body:
I think that you should add the action in the viewDidLoad() function of your view controller for that button or, if you are declaring it in a stand-alone UIButton inherited class in order to reuse it in the future in many view controllers, you should add the target in the initialiser of the UIButton.

If the code is written in that way is even strange that Xcode is not giving you warnings...

EDIT: This is a code snippet of how I would do it

//Comments

import UIKit

class ViewController: UIViewController {

  //link this to the checkmark buttons
  //subclass UIButton making a button with the property isChecked: Bool
  @IBOutlet weak var checkmarkButton: UICheckButton!

  var checkMarkSelected = 0

  override function viewDidLoad() {
    //do stuff with your viewdidload
  }

  //link this to the checkmark buttons
  @IBAction func checkMarkAction(sender: UICheckButton) {
        if sender.isChecked == false {
            let checkedImage = UIImage(named: "check")
            checkMarkButton.setImage(checkedImage, for: .normal)
            sender.isChecked = true
            checkMarkSelected += checkMarkSelected
        } else {
            let uncheckedImage = UIImage(named: "uncheck")
            checkMarkButton.setImage(uncheckedImage, for: .normal)
            sender.isChecked = false
            checkMarkSelected -= checkMarkSelected
        }
  }


问:
Multidimensional Map
I am programming an Android app in university.

The user is asked questions they have to answer.

I get the questions via HTTP request / response from a server. They are delivered as a string. This string looks something like this with 2 questions:

```<code>(requestedQuestion):

    id: 1
    question: Mit was stylet man HTML?
    answer1: PHP
    answer2: C++
    answer3: Java
    answer4: CSS
    answerR: 4
    picture:
    kind: 4
    category: Webprogrammierung
    semester: 2
    difficulty: 1
    ranking:
    report:
    moderated:
    id: 2
    question: Wie viele Bits hat ein Byte?
    answer1: 4
    answer2: 8
    answer3:
    answer4:
    answerR: 2
    picture:
    kind: 2
    category: Informatik
    semester: 1
    difficulty: 2
    ranking:
    report:
    moderated:
</code>```

I thought to put the string into a multi-dimensional map to better access each attribute.

At the moment we have a simple Map-generator that should generate a normal map but this is not working right:

```<code>HashMap<String, String> map = new HashMap();
  String payload = requestedQuestion;
  String[] keyVals = payload.split("\\s*\n");
  for(String keyVal:keyVals) {
    String[] parts = keyVal.split(":", 2);
    map.put(parts[0],parts[1]);
  }
</code>```

I want to have a multi-dimensional (JSON Response) map like this so we can access each question with its attributes:

```<code>Map: {question1=
        {
        id= 1,
        question= Mit was stylet man HTML?,
        answer1= PHP,
        answer2= C++,
        answer3= Java,
        answer4= CSS,
        answerR= 4,
        picture=,
        kind= 4,
        category= Webprogrammierung,
        semester= 2,
        difficulty= 1,
        ranking=,
        report=,
        moderated=
        },
      question2=
        {
        id= 2,
        question= Wie viele Bits hat ein Byte?,
        answer1= 4,
        answer2= 8,
        answer3=,
        answer4=,
        answerR= 2,
        picture=,
        kind= 2,
        category= Informatik,
        semester= 1,
        difficulty= 2,
        ranking=,
        report=,
        moderated=
        }
     }
</code>```

答:
It's more natural to provide JSON answer from the server:

```<code>{
    "id": 1,
    "question": "Mit was stylet man HTML?",
    "answers" : [
        { "value": "PHP" },
        { "value" : "C++"},
        { "value" : "Java"},
        { "value" : "CSS"}
    ],
    "rightAnswer": 4,
    "kind": 4,
    "category": "Webprogrammierung",
    "semester": 2,
    "difficulty": 1
}
</code>```

For more information about JSON, you can look at this link

Then in Android you can use GSON or some other library to parse JSON responses.

You need to create POJO object and map them with GSON annotations. This is examples of Objects for JSON whic I've provide earlier:

Question:

```<code>public class Question {

    @SerializedName("id")
    @Expose
    private Integer id;
    @SerializedName("question")
    @Expose
    private String question;
    @SerializedName("answers")
    @Expose
    private List<Answer> answers = null;
    @SerializedName("rightAnswer")
    @Expose
    private Integer rightAnswer;
    @SerializedName("kind")
    @Expose
    private Integer kind;
    @SerializedName("category")
    @Expose
    private String category;
    @SerializedName("semester")
    @Expose
    private Integer semester;
    @SerializedName("difficulty")
    @Expose
    private Integer difficulty;

    public Integer getId() {
        return id;
    }

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

    public String getQuestion() {
        return question;
    }

    public void setQuestion(String question) {
        this.question = question;
    }

    public List<Answer> getAnswers() {
        return answers;
    }

    public void setAnswers(List<Answer> answers) {
        this.answers = answers;
    }

    public Integer getRightAnswer() {
        return rightAnswer;
    }

    public void setRightAnswer(Integer rightAnswer) {
        this.rightAnswer = rightAnswer;
    }

    public Integer getKind() {
        return kind;
    }

    public void setKind(Integer kind) {
        this.kind = kind;
    }

    public String getCategory() {
        return category;
    }

    public void setCategory(String category) {
        this.category = category;
    }

    public Integer getSemester() {
        return semester;
    }

    public void setSemester(Integer semester) {
        this.semester = semester;
    }

    public Integer getDifficulty() {
        return difficulty;
    }

    public void setDifficulty(Integer difficulty) {
        this.difficulty = difficulty;
    }
}
</code>```

Answer:

```<code>    public class Answer {

    @SerializedName("value")
    @Expose
    private String value;

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

}
</code>```

And let us suppose that you get your response in String format and store it in response variable

```<code>String response; // store here response of your server request
</code>```

Then simply use GSON to parse that String:

```<code>Gson gson = new Gson();
Qustion question = gson.fromJson(response, Question.class);
</code>```

Now you have Question object. You can access fields in a next way

```<code>List<Answer> answers = quesion.getAnswers();
</code>```

Title: Multidimensional Map

Body:
I am programming an Android app in university.

The user is asked questions they have to answer.

I get the questions via HTTP request / response from a server. They are delivered as a string. This string looks something like this with 2 questions:

(requestedQuestion):

    id: 1
    question: Mit was stylet man HTML?
    answer1: PHP
    answer2: C++
    answer3: Java
    answer4: CSS
    answerR: 4
    picture:
    kind: 4
    category: Webprogrammierung
    semester: 2
    difficulty: 1
    ranking:
    report:
    moderated:
    id: 2
    question: Wie viele Bits hat ein Byte?
    answer1: 4
    answer2: 8
    answer3:
    answer4:
    answerR: 2
    picture:
    kind: 2
    category: Informatik
    semester: 1
    difficulty: 2
    ranking:
    report:
    moderated:

I thought to put the string into a multi-dimensional map to better access each attribute.

At the moment we have a simple Map-generator that should generate a normal map but this is not working right:

HashMap<String, String> map = new HashMap();
  String payload = requestedQuestion;
  String[] keyVals = payload.split("\\s*\n");
  for(String keyVal:keyVals) {
    String[] parts = keyVal.split(":", 2);
    map.put(parts[0],parts[1]);
  }

I want to have a multi-dimensional (JSON Response) map like this so we can access each question with its attributes:

Map: {question1=
        {
        id= 1,
        question= Mit was stylet man HTML?,
        answer1= PHP,
        answer2= C++,
        answer3= Java,
        answer4= CSS,
        answerR= 4,
        picture=,
        kind= 4,
        category= Webprogrammierung,
        semester= 2,
        difficulty= 1,
        ranking=,
        report=,
        moderated=
        },
      question2=
        {
        id= 2,
        question= Wie viele Bits hat ein Byte?,
        answer1= 4,
        answer2= 8,
        answer3=,
        answer4=,
        answerR= 2,
        picture=,
        kind= 2,
        category= Informatik,
        semester= 1,
        difficulty= 2,
        ranking=,
        report=,
        moderated=
        }
     }

Body:
It's more natural to provide JSON answer from the server:

{
    "id": 1,
    "question": "Mit was stylet man HTML?",
    "answers" : [
        { "value": "PHP" },
        { "value" : "C++"},
        { "value" : "Java"},
        { "value" : "CSS"}
    ],
    "rightAnswer": 4,
    "kind": 4,
    "category": "Webprogrammierung",
    "semester": 2,
    "difficulty": 1
}

For more information about JSON, you can look at this link

Then in Android you can use GSON or some other library to parse JSON responses.

You need to create POJO object and map them with GSON annotations. This is examples of Objects for JSON whic I've provide earlier:

Question:

public class Question {

    @SerializedName("id")
    @Expose
    private Integer id;
    @SerializedName("question")
    @Expose
    private String question;
    @SerializedName("answers")
    @Expose
    private List<Answer> answers = null;
    @SerializedName("rightAnswer")
    @Expose
    private Integer rightAnswer;
    @SerializedName("kind")
    @Expose
    private Integer kind;
    @SerializedName("category")
    @Expose
    private String category;
    @SerializedName("semester")
    @Expose
    private Integer semester;
    @SerializedName("difficulty")
    @Expose
    private Integer difficulty;

    public Integer getId() {
        return id;
    }

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

    public String getQuestion() {
        return question;
    }

    public void setQuestion(String question) {
        this.question = question;
    }

    public List<Answer> getAnswers() {
        return answers;
    }

    public void setAnswers(List<Answer> answers) {
        this.answers = answers;
    }

    public Integer getRightAnswer() {
        return rightAnswer;
    }

    public void setRightAnswer(Integer rightAnswer) {
        this.rightAnswer = rightAnswer;
    }

    public Integer getKind() {
        return kind;
    }

    public void setKind(Integer kind) {
        this.kind = kind;
    }

    public String getCategory() {
        return category;
    }

    public void setCategory(String category) {
        this.category = category;
    }

    public Integer getSemester() {
        return semester;
    }

    public void setSemester(Integer semester) {
        this.semester = semester;
    }

    public Integer getDifficulty() {
        return difficulty;
    }

    public void setDifficulty(Integer difficulty) {
        this.difficulty = difficulty;
    }
}

Answer:

    public class Answer {

    @SerializedName("value")
    @Expose
    private String value;

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

}

And let us suppose that you get your response in String format and store it in response variable

String response; // store here response of your server request

Then simply use GSON to parse that String:

Gson gson = new Gson();
Qustion question = gson.fromJson(response, Question.class);

Now you have Question object. You can access fields in a next way

List<Answer> answers = quesion.getAnswers();


问:
AMP and code blocks
I have a web about programming and it has some articles with code blocks. Now Google Webmaster tools reports me that I have some issues with my AMP implementation.

I have searched a bit and I think that the problem is the usage of code blocks like this:

```<code><pre lang="c">
#include <stdlib.h>
#include <stdio.h>
#include <gmp.h>
...
```
```

AMP tools analyze this code and report me some issues, for example:

The tag "stdio.h" isn't allowed

The tag "stdlib.h" isn't allowed

I have read the AMP documentation and I haven't found any solution, so do you know how to fix it?

PD: Post the code as image isn't a valid solution for mine.

答:
You need to escape '<' and '>' in your source code </p>

```<code><pre lang="c">
#include <stdlib.h>
#include <stdio.h>
#include <gmp.h>
...
```
</code>```

Title: AMP and code blocks

Body:
I have a web about programming and it has some articles with code blocks. Now Google Webmaster tools reports me that I have some issues with my AMP implementation.

I have searched a bit and I think that the problem is the usage of code blocks like this:

#include <stdlib.h>
#include <stdio.h>
#include <gmp.h>
...

AMP tools analyze this code and report me some issues, for example:

The tag "stdio.h" isn't allowed

The tag "stdlib.h" isn't allowed

I have read the AMP documentation and I haven't found any solution, so do you know how to fix it?

PD: Post the code as image isn't a valid solution for mine.

Body:
You need to escape '<' and '>' in your source code

<pre lang="c">
#include &lt;stdlib.h&gt;
#include &lt;stdio.h&gt;
#include &lt;gmp.h&gt;
...
</pre>


问:
SQL Server Left Join Counting
I got this sample code

```<code>create table #Reservation
(id int identity(1,1),
 name varchar(50)
);

create table #Reservation_details
(id int identity(1,1),
 reservation_id int,
 reservation_date date,
 seated tinyint
);

create table #Payment
(id int identity(1,1),
 reservation_id int,
 payment decimal(18,2)
);

insert into #Reservation(name)
values ('Spiderman'),('Superman'),('Batman'),('Hulk');

insert into #Reservation_details(reservation_id,reservation_date,seated)
values (1,'2017-12-07',0),(2,'2017-12-08',0),(3,'2017-12-08',1),(4,'2017-12-08',0);

insert into #Payment(reservation_id,payment)
values(1,220),(2,1000)

select
 A.id,
 A.name,
 B.reservation_date,
 B.seated,
 C.payment
from #Reservation A
inner join #Reservation_details B
on B.reservation_id = A.id
left join #Payment C
on C.reservation_id = B.reservation_id
where reservation_date = '2017-12-08'

drop table #Reservation
drop table #Reservation_details
drop table #Payment
</code>```

I wanted to get the count of all reservations where date is '2017-12-08' and seated = 1 or payment is not null

I've tried putting where date is '2017-12-08' and seated = 1 or payment is not
null

but instead it showed me the past date also how do use where as count?

答:
```<code>select
A.id,
A.name,
B.reservation_date,
B.seated,
C.payment
from (#Reservation A
inner join #Reservation_details B
on B.reservation_id = A.id
left join #Payment C
on C.reservation_id = B.reservation_id)
where B.reservation_date = '2017-12-08'
AND (B.seated =1 or  C.payment is null)
</code>```

You can use COUNT function by using HAVING in WHERE clause , it should be last statement and after the GROUP BY clause

Title: SQL Server Left Join Counting

Body:
I got this sample code

create table #Reservation
(id int identity(1,1),
 name varchar(50)
);

create table #Reservation_details
(id int identity(1,1),
 reservation_id int,
 reservation_date date,
 seated tinyint
);

create table #Payment
(id int identity(1,1),
 reservation_id int,
 payment decimal(18,2)
);

insert into #Reservation(name)
values ('Spiderman'),('Superman'),('Batman'),('Hulk');

insert into #Reservation_details(reservation_id,reservation_date,seated)
values (1,'2017-12-07',0),(2,'2017-12-08',0),(3,'2017-12-08',1),(4,'2017-12-08',0);

insert into #Payment(reservation_id,payment)
values(1,220),(2,1000)

select
 A.id,
 A.name,
 B.reservation_date,
 B.seated,
 C.payment
from #Reservation A
inner join #Reservation_details B
on B.reservation_id = A.id
left join #Payment C
on C.reservation_id = B.reservation_id
where reservation_date = '2017-12-08'

drop table #Reservation
drop table #Reservation_details
drop table #Payment

I wanted to get the count of all reservations where date is '2017-12-08' and seated = 1 or payment is not null

I've tried putting where date is '2017-12-08' and seated = 1 or payment is not
null

but instead it showed me the past date also how do use where as count?

Body:
select
A.id,
A.name,
B.reservation_date,
B.seated,
C.payment
from (#Reservation A
inner join #Reservation_details B
on B.reservation_id = A.id
left join #Payment C
on C.reservation_id = B.reservation_id)
where B.reservation_date = '2017-12-08'
AND (B.seated =1 or  C.payment is null)

You can use COUNT function by using HAVING in WHERE clause , it should be last statement and after the GROUP BY clause


问:
Opening less connections with rethinkDB
My question is; Can i have less connections open when using rethindb? Right now I'm opening a new one every time I want to insert or get some data. Im afraid that this is not a right thing to do. Is there any way I can open just one and use it instead? I'm using nodejs.</p>

答: I'd advise you to use rethinkdbdash, an "advanced Node.js RethinkDB driver" that includes connection pools and some other advanced features. It has many more stars and contributors than rethinkdb-pool.</p>

Title: Opening less connections with rethinkDB


问:
Canvas binding in silverlight
I'm trying to create a canvas, with items located at specefied locations on the canvast, as i can not bind an source and a template directly to a Canvas, have i used a ItemsControl.
But there are a problem all the items are located at 0,0. And i have tested the Bindings they do not return 0,0.
How can i make this work so the items are located at the right place?

Also is it poissible to create 2 layers on the canvas, where each layer is binded to a diffrent source, and uses a diffrent template?

This is in Silverlight

```<code><ItemsControl Grid.Row="1" Grid.Column="1"
                Width="650" Height="650"
                ItemsSource="{Binding Skills}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <Canvas Margin="0"
                Width="650" Height="650" />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <StackPanel Canvas.Top="{Binding Top}" Canvas.Left="{Binding Left}">
                    <TextBlock Text="{Binding Name}" />
                <Image Source="{Binding Icon}" />
                <StackPanel Orientation="Horizontal" >
                    <TextBlock FontWeight="Bold" TextAlignment="Center" Text="{Binding SkillPointsStatusText}" />
                </StackPanel>
            </StackPanel>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>
</code>```

Test with ItemContainerStyle

```<code><ItemsControl Grid.Row="1" Grid.Column="1"
                Width="650" Height="650"
                ItemsSource="{Binding Skills}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <Canvas Margin="0"
                Width="650" Height="650" />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <TextBlock Text="{Binding Name}" />
                <Image Source="{Binding Icon}" />
                <TextBlock FontWeight="Bold" TextAlignment="Center" Text="{Binding SkillPointsStatusText}" />
            </StackPanel>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
    <ItemsControl.ItemContainerStyle>
        <Style>
            <Setter Property="Canvas.Top" Value="{Binding Top}" />
            <Setter Property="Canvas.Left" Value="{Binding Left}" />
        </Style>
    </ItemsControl.ItemContainerStyle>
</ItemsControl>
</code>```

Well i have droped the project, but i will leave the question open should one have an anwser

答:
All of the following does not work in SL4 since it depends on bindings in a Setter.Value.

Try setting the binding in the ItemContainerStyle since your StackPanel is not the root element; your template will be placed in a ContentPresenter, so your attached properties for canvas positioning in the StackPanel will be ignored.

```<code><ItemsControl.ItemContainerStyle>
    <Style>
        <Setter Property="Canvas.Top" Value="{Binding Top}" />
        <Setter Property="Canvas.Left" Value="{Binding Left}" />
    </Style>
</ItemsControl.ItemContainerStyle>
</code>```

Edit: If Silverlight does not support ItemContainerStyle you can set the universal style for ContentPresenters which should work just as well:

```<code>    <ItemsControl ItemsSource="{Binding Data}">
        <ItemsControl.Resources>
            <Style TargetType="ContentPresenter">
                <Setter Property="Canvas.Left" Value="{Binding Left}"/>
                <Setter Property="Canvas.Top" Value="{Binding Top}"/>
            </Style>
        </ItemsControl.Resources>
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <Canvas/>
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                ...
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
</code>```

Title: Canvas binding in silverlight

Body:
I'm trying to create a canvas, with items located at specefied locations on the canvast, as i can not bind an source and a template directly to a Canvas, have i used a ItemsControl.
But there are a problem all the items are located at 0,0. And i have tested the Bindings they do not return 0,0.
How can i make this work so the items are located at the right place?

Also is it poissible to create 2 layers on the canvas, where each layer is binded to a diffrent source, and uses a diffrent template?

This is in Silverlight

<ItemsControl Grid.Row="1" Grid.Column="1"
                Width="650" Height="650"
                ItemsSource="{Binding Skills}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <Canvas Margin="0"
                Width="650" Height="650" />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <StackPanel Canvas.Top="{Binding Top}" Canvas.Left="{Binding Left}">
                    <TextBlock Text="{Binding Name}" />
                <Image Source="{Binding Icon}" />
                <StackPanel Orientation="Horizontal" >
                    <TextBlock FontWeight="Bold" TextAlignment="Center" Text="{Binding SkillPointsStatusText}" />
                </StackPanel>
            </StackPanel>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

Test with ItemContainerStyle

<ItemsControl Grid.Row="1" Grid.Column="1"
                Width="650" Height="650"
                ItemsSource="{Binding Skills}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <Canvas Margin="0"
                Width="650" Height="650" />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <TextBlock Text="{Binding Name}" />
                <Image Source="{Binding Icon}" />
                <TextBlock FontWeight="Bold" TextAlignment="Center" Text="{Binding SkillPointsStatusText}" />
            </StackPanel>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
    <ItemsControl.ItemContainerStyle>

    </ItemsControl.ItemContainerStyle>
</ItemsControl>

Well i have droped the project, but i will leave the question open should one have an anwser

Body:
All of the following does not work in SL4 since it depends on bindings in a Setter.Value.

Try setting the binding in the ItemContainerStyle since your StackPanel is not the root element; your template will be placed in a ContentPresenter, so your attached properties for canvas positioning in the StackPanel will be ignored.

<ItemsControl.ItemContainerStyle>
    <Style>
        <Setter Property="Canvas.Top" Value="{Binding Top}" />
        <Setter Property="Canvas.Left" Value="{Binding Left}" />
    </Style>
</ItemsControl.ItemContainerStyle>

Edit: If Silverlight does not support ItemContainerStyle you can set the universal style for ContentPresenters which should work just as well:

    <ItemsControl ItemsSource="{Binding Data}">
        <ItemsControl.Resources>
            <Style TargetType="ContentPresenter">
                <Setter Property="Canvas.Left" Value="{Binding Left}"/>
                <Setter Property="Canvas.Top" Value="{Binding Top}"/>
            </Style>
        </ItemsControl.Resources>
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <Canvas/>
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                ...
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>


问:
How to prevent android SearchView Query toggling while text is typing
I got my view with SearchView component. The problem is every new symbol in the input field toggling Query action, so there are some http request are fire etc, so it starts to working slow.

I want it to run only after I click on search button on virtual keyboard (bellow button ).

Is there any properties for that in SearchView?

layout code:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:local="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <SearchView
        android:id="@+id/search"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:clickable="true"
        local:MvxBind="Query SearchString" />

</LinearLayout>
</code>```

Or I should make something like custom binding which detects keyboard key click?

UPD:

Some code to make clear part of how search works:

View model

```<code>public class RemoteMusicSearchViewModel : MvxViewModel
    {
        private IMvxNavigationService _mvxNavigationService;
        private IRemoteMusicDataService _remoteMusicDataService;
        private int _currentPage;

        public RemoteMusicSearchViewModel(IMvxNavigationService mvxNavigationService,
            IRemoteMusicDataService remoteMusicDataService)
        {
            _mvxNavigationService = mvxNavigationService;
            _remoteMusicDataService = remoteMusicDataService;
        }

        public override void Start()
        {
            base.Start();

            _currentPage = 0;
        }

        private string _searchString;

        public string SearchString
        {
            get { return _searchString; }

            set
            {
                _searchString = value;
                RaisePropertyChanged(() => SearchString);
                PerformBasicSearch().ConfigureAwait(false);
            }
        }

        private ObservableCollection<DownloadableEntity> _foundItems;

        public ObservableCollection<DownloadableEntity> FoundItems
        {
            get { return _foundItems; }

            set
            {
                if (_currentPage > 0)
                {
                    _foundItems = new ObservableCollection<DownloadableEntity>(_foundItems.Concat(value));
                }
                else
                {
                    _foundItems = value;
                }

                RaisePropertyChanged(() => FoundItems);
            }
        }

        private async Task PerformBasicSearch(int page = 0)
        {
            string request = SearchString;
            string result = await _remoteMusicDataService.SearchByProperty(request, MusicSearchType.ByTracks, page).ConfigureAwait(false);
            var searchResult = MusicSearchResult.FromJson(result);

            await PrepareDataForOutput(searchResult).ConfigureAwait(false);
        }
    }
</code>```

full layout code:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:local="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <SearchView
        android:id="@+id/search"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:clickable="true"
        local:MvxBind="Query SearchString"
        />

    <MvvmCross.Binding.Droid.Views.MvxListView
        android:id="@+id/searchlist"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        local:MvxBind="ItemsSource FoundItems"
        local:MvxItemTemplate="@layout/listitem"/>

</LinearLayout>
</code>```

答:
I am guessing you are looking for a manual solution for the problem.

With each key event you get you can fire a delayed action after a certain threshold 500 milliseconds for example.

Maybe using Handler.postDelayed()

Then there three scenarios

Another event comes before that fires, so you call Handler.removeCallbacks() and fire another delayed action

Another event comes while the request is already fired, but no result yet, so you cancel the request and fire your delayed action.

An event comes while no delayed action pending or request pending, so you just fire a delayed action.

However, if you are willing to use any Reactive variant, there are more sophisticated solutions for that, by basically debouncing the events of keyboard strokes.

Body:
I got my view with SearchView component. The problem is every new symbol in the input field toggling Query action, so there are some http request are fire etc, so it starts to working slow.

I want it to run only after I click on search button on virtual keyboard (bellow button ).

Is there any properties for that in SearchView?

layout code:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:local="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <SearchView
        android:id="@+id/search"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:clickable="true"
        local:MvxBind="Query SearchString" />

</LinearLayout>

Or I should make something like custom binding which detects keyboard key click?

UPD:

Some code to make clear part of how search works:

View model

public class RemoteMusicSearchViewModel : MvxViewModel
    {
        private IMvxNavigationService _mvxNavigationService;
        private IRemoteMusicDataService _remoteMusicDataService;
        private int _currentPage;

        public RemoteMusicSearchViewModel(IMvxNavigationService mvxNavigationService,
            IRemoteMusicDataService remoteMusicDataService)
        {
            _mvxNavigationService = mvxNavigationService;
            _remoteMusicDataService = remoteMusicDataService;
        }

        public override void Start()
        {
            base.Start();

            _currentPage = 0;
        }

        private string _searchString;

        public string SearchString
        {
            get { return _searchString; }

            set
            {
                _searchString = value;
                RaisePropertyChanged(() => SearchString);
                PerformBasicSearch().ConfigureAwait(false);
            }
        }

        private ObservableCollection<DownloadableEntity> _foundItems;

        public ObservableCollection<DownloadableEntity> FoundItems
        {
            get { return _foundItems; }

            set
            {
                if (_currentPage > 0)
                {
                    _foundItems = new ObservableCollection<DownloadableEntity>(_foundItems.Concat(value));
                }
                else
                {
                    _foundItems = value;
                }

                RaisePropertyChanged(() => FoundItems);
            }
        }

        private async Task PerformBasicSearch(int page = 0)
        {
            string request = SearchString;
            string result = await _remoteMusicDataService.SearchByProperty(request, MusicSearchType.ByTracks, page).ConfigureAwait(false);
            var searchResult = MusicSearchResult.FromJson(result);

            await PrepareDataForOutput(searchResult).ConfigureAwait(false);
        }
    }

full layout code:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:local="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <SearchView
        android:id="@+id/search"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:clickable="true"
        local:MvxBind="Query SearchString"
        />

    <MvvmCross.Binding.Droid.Views.MvxListView
        android:id="@+id/searchlist"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        local:MvxBind="ItemsSource FoundItems"
        local:MvxItemTemplate="@layout/listitem"/>

</LinearLayout>


问:
how to find min and max in loadash
```<code>{
  "item_name": "Chicken Tangy Combo",
  "item_key": "mezvts3qv1rl56vj",
  "item_price": 22,
  "quantity": 1,
  "ingredients": [
    {
      "group_key": "9lleke6mc60ulon1",
      "key": "qjuejdqhhcyz0orm",
      "ingredient_name": "2 Bread",
      "price": 1,
      "qun": 1,
      "max": 1,
      "min": 0
    },
    {
      "group_key": "qctfdwlc54v8xdet",
      "key": "rkgqnzkpktjfkfwz",
      "ingredient_name": "Onion Rings",
      "price": 3,
      "qun": 1,
      "max": 2,
      "min": 1
    }
  ]
}
</code>```

how to find max and min by using loadash

i used _(this.item.ingredients).groupBy('group_key').map((objs, key) => ({ 'group_key': key, 'total': _.sumBy(objs, 'qun'), 'max':_.maxBy(objs, 'max')})).value();

the groupBy and sumBy working fine but can't able to get the max vale instead i get the whole object

答:
I know nothing about Loadash and when searching for it, I found Lodash and selected _.max in the menu..

https://lodash.com/docs#max , https://lodash.com/docs#maxBy

Perhaps this: _(this.item.ingredients).groupBy('group_key').map((objs, key) => ({ 'group_key': key, 'total': _.sumBy(objs, 'qun'), 'max':_.max(objs, 'max')})).value();

Title: how to find min and max in loadash

Body:
{
  "item_name": "Chicken Tangy Combo",
  "item_key": "mezvts3qv1rl56vj",
  "item_price": 22,
  "quantity": 1,
  "ingredients": [
    {
      "group_key": "9lleke6mc60ulon1",
      "key": "qjuejdqhhcyz0orm",
      "ingredient_name": "2 Bread",
      "price": 1,
      "qun": 1,
      "max": 1,
      "min": 0
    },
    {
      "group_key": "qctfdwlc54v8xdet",
      "key": "rkgqnzkpktjfkfwz",
      "ingredient_name": "Onion Rings",
      "price": 3,
      "qun": 1,
      "max": 2,
      "min": 1
    }
  ]
}

how to find max and min by using loadash

i used _(this.item.ingredients).groupBy('group_key').map((objs, key) => ({ 'group_key': key, 'total': _.sumBy(objs, 'qun'), 'max':_.maxBy(objs, 'max')})).value();

the groupBy and sumBy working fine but can't able to get the max vale instead i get the whole object


问:
How do i download the 3 latest files from a ftp server using an array in php

How Do i download the 3 latest files from the ftp server

i have tried using(array_slice($contents, -3, 3, true)and that worked fine on the var_dumpfor showing the content, here is only the 3 latest files shown

I Need the 3 files to be downloaded and saved by these names on my local computerpv_inverter_1 and pv_inverter_2 and pv_inverter_3

Can i also use array_slice(???, -3, 3, true) to do so ???.

```<code>// get contents of the current directory
$contents = ftp_nlist($conn_id, ".");

// output $contents
var_dump (array_slice($contents, -3, 3, true));

$mostRecent = array(
'time' => 0,
'file' => null

);

foreach ($contents as $file) {
// get the last modified time for the file
$time = ftp_mdtm($conn_id, $file);

if ($time > $mostRecent['time']) {
    // this file is the most recent so far
    $mostRecent['time'] = $time;
    $mostRecent['file'] = $file;
    }
}

 if (ftp_get($conn_id, "pv_inverter_1.csv", $mostRecent['file'],FTP_BINARY)) {

     echo "Files Successfully Downloaded\n";
 }

 else {

    echo "There was a problem\n";
}
</code>```

答:
If you want to download the last three files returned by the server in directory listing:

```<code>$files = ftp_nlist($conn_id, ".");

$last_3_files = array_slice($files, -3);

$i = 0;
foreach ($last_3_files as $file)
{
    if (ftp_get($conn_id, "pv_inverter_$i.csv", $file, FTP_BINARY))
    {
        echo "$file downloaded\n";
    }
    else
    {
        echo "There was a problem downloading $file\n";
    }
    $i++;
}
</code>```

Though note that "last" and "latest" is not the same.

Body:
How Do i download the 3 latest files from the ftp server

i have tried using(array_slice($contents, -3, 3, true)and that worked fine on the var_dumpfor showing the content, here is only the 3 latest files shown

I Need the 3 files to be downloaded and saved by these names on my local computerpv_inverter_1 and pv_inverter_2 and pv_inverter_3

Can i also use array_slice(???, -3, 3, true) to do so ???.

// get contents of the current directory
$contents = ftp_nlist($conn_id, ".");

// output $contents
var_dump (array_slice($contents, -3, 3, true));

$mostRecent = array(
'time' => 0,
'file' => null

);

foreach ($contents as $file) {
// get the last modified time for the file
$time = ftp_mdtm($conn_id, $file);

if ($time > $mostRecent['time']) {
    // this file is the most recent so far
    $mostRecent['time'] = $time;
    $mostRecent['file'] = $file;
    }
}

 if (ftp_get($conn_id, "pv_inverter_1.csv", $mostRecent['file'],FTP_BINARY)) {

     echo "Files Successfully Downloaded\n";
 }

 else {

    echo "There was a problem\n";
}

Body:
If you want to download the last three files returned by the server in directory listing:

$files = ftp_nlist($conn_id, ".");

$last_3_files = array_slice($files, -3);

$i = 0;
foreach ($last_3_files as $file)
{
    if (ftp_get($conn_id, "pv_inverter_$i.csv", $file, FTP_BINARY))
    {
        echo "$file downloaded\n";
    }
    else
    {
        echo "There was a problem downloading $file\n";
    }
    $i++;
}

Though note that "last" and "latest" is not the same.


问:
 ‘Remember Me’ Login in CodeIgniter
How do you implement this in CodeIgniter?</p>

答:
You might want to reconsider the suggestion from 'Improved Persistent Login Cookie Best Practice'. I've posted my analysis of the problem on the site, but the gist of it is this:

You can not prevent cookie stealing without a secure line, no matter what

(*By 'secure line', I mean SSL / VPN tunneling / public-key encryption - or a robust challenge-response scheme *)

I'm all for persistent login best practices, but there's a point where no amount of trickery is going to help, and where the only way up is SSL.

OwnerDisplayName: andyk

Title: ‘Remember Me’ Login in CodeIgniter

LastEditorDisplayName: andyk

OwnerDisplayName: Jens Roland

LastEditorDisplayName: Jens Roland


答:
It is a rounding error inherent in the IEEE single-float format.</p>

```<code>CL-USER> (exp 1.0d0)
2.718281828459045d0
</code>```

Title: exp in SBCL is wrong?

Body:
CL-USER> (exp 1)

2.7182817

Why? It should be 2.7182818 (rounded from 2.7182818284590452353602874713526624977572470936999595749669...)

SBCL 1.0.29.11.debian

Body:
It is a rounding error inherent in the IEEE single-float format.

CL-USER> (exp 1.0d0)
2.718281828459045d0


问:
Sonarqube : Create a custom page using react
I would like to create a custom page using react but I cannot find the documentation to do this. On the Sonarqube documentation, there only the way to create a custom page using javascript only and I don’t understand how the example plugin works with react.
Can you tell me if there is a documentation that I can use.</p>

答:
Short answer: There isn't. There is barely anyone (no one in fact, as far as I've seen) using custom pages currently.

However, it IS possible. You need to create a react project with Webpack (or a similar JS packager).

I also recommend using Create-React-App. This fixes a lot of the setup for you. After that, in your index.js you use the example code from the SonarQube wiki.

Here is an example:

```<code>/*
    PRODUCTION ENTRYPOINT
 */
import React from 'react';
import ReactDOM from 'react-dom';
import Project from './components/Project';
import './main.css';

window.registerExtension('myplugin/coverage', function (options) {

    appendCustomCSS();
    let isDisplayed = true;

    window.SonarRequest.getJSON('/api/measures/component', {
        component: options.component.key,
        metricKeys: 'coverage'
    }).then(function (response) {
        if (isDisplayed) {
            let obj = JSON.parse(response.component.measures[0].value);
            let div = document.createElement('div');
            render(obj, div);
            options.el.appendChild(div);
        }
    });

    return function () {
        isDisplayed = false;
    };
});

function appendCustomCSS() {
    let fileref = document.createElement("link");
    fileref.setAttribute("rel", "stylesheet");
    fileref.setAttribute("type", "text/css");
    fileref.setAttribute("href", "/static/myplugin/coverage.css");
    document.head.append(fileref);
}

function render(objectArray, container) {
    ReactDOM.render(<div className="Coverage"><Project objects={objectArray}/></div>, container);
}
</code>```

Body:
Short answer: There isn't. There is barely anyone (no one in fact, as far as I've seen) using custom pages currently.

However, it IS possible. You need to create a react project with Webpack (or a similar JS packager).

I also recommend using Create-React-App. This fixes a lot of the setup for you. After that, in your index.js you use the example code from the SonarQube wiki.

Here is an example:

/*
    PRODUCTION ENTRYPOINT
 */
import React from 'react';
import ReactDOM from 'react-dom';
import Project from './components/Project';
import './main.css';

window.registerExtension('myplugin/coverage', function (options) {

    appendCustomCSS();
    let isDisplayed = true;

    window.SonarRequest.getJSON('/api/measures/component', {
        component: options.component.key,
        metricKeys: 'coverage'
    }).then(function (response) {
        if (isDisplayed) {
            let obj = JSON.parse(response.component.measures[0].value);
            let div = document.createElement('div');
            render(obj, div);
            options.el.appendChild(div);
        }
    });

    return function () {
        isDisplayed = false;
    };
});

function appendCustomCSS() {
    let fileref = document.createElement("link");
    fileref.setAttribute("rel", "stylesheet");
    fileref.setAttribute("type", "text/css");
    fileref.setAttribute("href", "/static/myplugin/coverage.css");
    document.head.append(fileref);
}

function render(objectArray, container) {
    ReactDOM.render(<div className="Coverage"><Project objects={objectArray}/></div>, container);
}


问:
PHP file inside one folder is executing but not inside few others
There is a folder on centos server named as v2_3, and it contains a file named as test.php and on the browser, it's able to execute this file.

I cloned the code from git that has code similar to v2_3 with new changes inside its branch and named it as v2_3-git, then I executed test.php from this folder and it returned 404 error.

I thought it might be some issue with .htaccess on root which has Joomla project on a root. So I tried to rename v2_3-git to v2_3 and the original v2_3 to v2_3-git and thought that it should work now. But now test.php inside v2_3-git is executing properly but not inside v2_3 (code from git). Then I thought, something must be wrong with the code inside v2_3 (from git), but I tried to create another folder on root and created index.php inside it, and it didn't execute either. When I tried to execute .html files, they are working fine everywhere.

I tried to restart apache but the issue didn't resolve.

So what's happening to PHP files here? I don't see any difference between executing test.php from a v2_3 folder and v2_3-git folder or some other random folder with index.php file. I checked the permissions and ownership of folder v2_3 and v2_3-git and they are same, then what's wrong.?

答: As per Joomla, the folder should have 755 and files should have 644 permissions.</p>


问:
How to do math formula in the sql query for desc sorting (res.a div res.b)
I have a large mySql table with user given finger up/down ratings. At the moment I have two basic sorting options for table to choose from:

```<code> ['likes desc', 'id desc'],
 ['dislikes desc', 'id desc'],
</code>```

I would like to add 3rd sorting option, that would convert above n/o of likes OR dislikes to one easy 1..5 star rating system with this kind of formula:

```<code>$rank = ($this->getLikes() / ($this->getDislikes() + $this->getLikes()))*5 ;
</code>```

What is the highest performance option to do this math on sql level itself, would it be possible to do sorting for "result.likes div result.dislikes" formula inside the SQl query itself, or should I make a few queries to get a proper output somehow?  I dont want to make a third column for this purpose.

答:
You can use the formula directly in the order by clause:

```<code>ORDER BY
  (likes/(likes+dislikes))*5
</code>```

If this is performant is up to you to check, this depends on many factors.

Body:
I have a large mySql table with user given finger up/down ratings. At the moment I have two basic sorting options for table to choose from:

 ['likes desc', 'id desc'],
 ['dislikes desc', 'id desc'],

I would like to add 3rd sorting option, that would convert above n/o of likes OR dislikes to one easy 1..5 star rating system with this kind of formula:

$rank = ($this->getLikes() / ($this->getDislikes() + $this->getLikes()))*5 ;

What is the highest performance option to do this math on sql level itself, would it be possible to do sorting for "result.likes div result.dislikes" formula inside the SQl query itself, or should I make a few queries to get a proper output somehow?  I dont want to make a third column for this purpose.

Body:
You can use the formula directly in the order by clause:

ORDER BY
  (likes/(likes+dislikes))*5

If this is performant is up to you to check, this depends on many factors.