问:
Error: UnsatisfiedDependencyException with mySQL
I make by my own shema in MySQL, named project, and I have following code and following error, and don't know how to fix it. Please if you help me. It is my first project like this, i already tried everything I founded on stackoverflow

Service:

```<code>  package service;

    import java.util.List;

    import model.User;

    public interface UserService {
        public User findOne(Long id);
        public List<User> find();
        public User save(User user);
        public void delete(User user);
        public User update(User newUser, Long userId);
        public User findByUsername(String username);

    }

Implementation of service:

 import java.util.List;

    import javax.transaction.Transactional;

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;

    import model.User;
    import repository.UserRepository;
    import service.UserService;
    @Service
    @Transactional
    public class UserServiceJpa implements UserService {
        @Autowired
        private UserRepository userRepository;

        @Override
        public User findOne(Long id) {
            User user = userRepository.findOne(id);

            return user;
        }

        @Override
        public List<User> find() {
            // TODO Auto-generated method stub
            return userRepository.findAll();
        }
    //...
    }
</code>```

Repository:

```<code>import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import model.User;

@Repository
public interface UserRepository extends JpaRepository<User, Long>{
    public User findByUsername(String username);

    public User findOne(Long id);
}
</code>```

Model class:

```<code>import javax.persistence.Entity;
import javax.persistence.Table;

@Entity
@Table(name = "user")
public class User {
    private long id;
    private String username;
    private String password;
    private String name;
    private String surname;
    private UserType type;
    private String dateOfReg;
    private ProfileUser profile;

    public User() {
    }
    //...
    }
</code>```

pom.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>project</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.7</java.version>
    </properties>

    <dependencies>
        <!-- Spring -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cloud-connectors</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>javax.persistence</artifactId>
            <version>2.0.0</version>
        </dependency>

        <!-- Hibernate -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-pool</groupId>
            <artifactId>commons-pool</artifactId>
        </dependency>

        <!-- MySQL -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>spring-releases</id>
            <url>https://repo.spring.io/libs-release</url>
        </repository>

        <repository>
            <id>codehaus</id>
            <url>http://repository.codehaus.org/org/codehaus</url>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>spring-releases</id>
            <url>https://repo.spring.io/libs-release</url>
        </pluginRepository>
    </pluginRepositories>

</project>
</code>```

.properties:

```<code>spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/project?verifyServerCertificate=false&useSSL=true
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.useSSL=false

sping.jpa.hibernate.dialect=org.hibernate.dialect.MySQLDialect
spring.jpa.hibernate.show_sql=true
spring.jpa.hibernate.format_sql=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.hibernate.jdbc.batch_size=50
spring.jpa.hibernate.connection.CharSet=utf8
spring.jpa.hibernate.connection.characterEncoding=utf8
spring.jpa.hibernate.connection.useUnicode=true
</code>```

error:

org.springframework.beans.factory.UnsatisfiedDependencyException:
  Error creating bean with name
  'org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration':
  Unsatisfied dependency expressed through constructor parameter 0;
  nested exception is
  org.springframework.beans.factory.BeanCreationException: Error
  creating bean with name 'dataSource' defined in class path resource
  [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Tomcat.class]:
  Bean instantiation via factory method failed; nested exception is
  org.springframework.beans.BeanInstantiationException: Failed to
  instantiate [org.apache.tomcat.jdbc.pool.DataSource]: Factory method
  'dataSource' threw exception; nested exception is
  java.lang.IllegalStateException: Cannot load driver class:
  com.mysql.cj.jdbc.Driver  at
  org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:749)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:189)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1193)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1095)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:372)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1173)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1067)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1078)
  ~[spring-context-4.3.9.RELEASE.jar:4.3.9.RELEASE]     at
  org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:857)
  ~[spring-context-4.3.9.RELEASE.jar:4.3.9.RELEASE]     at
  org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543)
  ~[spring-context-4.3.9.RELEASE.jar:4.3.9.RELEASE]     at
  org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122)
  ~[spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE]    at
  org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693)
  [spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE]     at
  org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360)
  [spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE]     at
  org.springframework.boot.SpringApplication.run(SpringApplication.java:303)
  [spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE]     at
  org.springframework.boot.SpringApplication.run(SpringApplication.java:1118)
  [spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE]     at
  org.springframework.boot.SpringApplication.run(SpringApplication.java:1107)
  [spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE]     at
  com.example.Sbz3Application.main(Sbz3Application.java:10)
  [classes/:na] Caused by:
  org.springframework.beans.factory.BeanCreationException: Error
  creating bean with name 'dataSource' defined in class path resource
  [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Tomcat.class]:
  Bean instantiation via factory method failed; nested exception is
  org.springframework.beans.BeanInstantiationException: Failed to
  instantiate [org.apache.tomcat.jdbc.pool.DataSource]: Factory method
  'dataSource' threw exception; nested exception is
  java.lang.IllegalStateException: Cannot load driver class:
  com.mysql.cj.jdbc.Driver  at
  org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1173)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1067)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:208)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1138)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:835)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:741)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   ... 28 common frames
  omitted Caused by:
  org.springframework.beans.BeanInstantiationException: Failed to
  instantiate [org.apache.tomcat.jdbc.pool.DataSource]: Factory method
  'dataSource' threw exception; nested exception is
  java.lang.IllegalStateException: Cannot load driver class:
  com.mysql.cj.jdbc.Driver  at
  org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   ... 41 common frames
  omitted Caused by: java.lang.IllegalStateException: Cannot load driver
  class: com.mysql.cj.jdbc.Driver   at
  org.springframework.util.Assert.state(Assert.java:70)
  ~[spring-core-4.3.9.RELEASE.jar:4.3.9.RELEASE]    at
  org.springframework.boot.autoconfigure.jdbc.DataSourceProperties.determineDriverClassName(DataSourceProperties.java:231)
  ~[spring-boot-autoconfigure-1.5.4.RELEASE.jar:1.5.4.RELEASE]  at
  org.springframework.boot.autoconfigure.jdbc.DataSourceProperties.initializeDataSourceBuilder(DataSourceProperties.java:183)
  ~[spring-boot-autoconfigure-1.5.4.RELEASE.jar:1.5.4.RELEASE]  at
  org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration.createDataSource(DataSourceConfiguration.java:42)
  ~[spring-boot-autoconfigure-1.5.4.RELEASE.jar:1.5.4.RELEASE]  at
  org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration$Tomcat.dataSource(DataSourceConfiguration.java:56)
  ~[spring-boot-autoconfigure-1.5.4.RELEASE.jar:1.5.4.RELEASE]  at
  sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  ~[na:1.8.0_25]    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown
  Source) ~[na:1.8.0_25]    at
  sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
  ~[na:1.8.0_25]    at java.lang.reflect.Method.invoke(Unknown Source)
  ~[na:1.8.0_25]    at
  org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   ... 42 common frames
  omitted

答:
Your project is using Mysql5.1, and the Driver class you are attempting to load does not exist there (com.mysql.cj.jdbc.Driver).
See if this helps - change the application.properties line from

```<code>spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
</code>```

to

```<code>spring.datasource.driver-class-name=com.mysql.jdbc.Driver
</code>```

Body:
I make by my own shema in MySQL, named project, and I have following code and following error, and don't know how to fix it. Please if you help me. It is my first project like this, i already tried everything I founded on stackoverflow

Service:

  package service;

    import java.util.List;

    import model.User;

    public interface UserService {
        public User findOne(Long id);
        public List<User> find();
        public User save(User user);
        public void delete(User user);
        public User update(User newUser, Long userId);
        public User findByUsername(String username);

    }

Implementation of service:

 import java.util.List;

    import javax.transaction.Transactional;

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;

    import model.User;
    import repository.UserRepository;
    import service.UserService;
    @Service
    @Transactional
    public class UserServiceJpa implements UserService {
        @Autowired
        private UserRepository userRepository;

        @Override
        public User findOne(Long id) {
            User user = userRepository.findOne(id);

            return user;
        }

        @Override
        public List<User> find() {
            // TODO Auto-generated method stub
            return userRepository.findAll();
        }
    //...
    }

Repository:

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import model.User;

@Repository
public interface UserRepository extends JpaRepository<User, Long>{
    public User findByUsername(String username);

    public User findOne(Long id);
}

Model class:

import javax.persistence.Entity;
import javax.persistence.Table;

@Entity
@Table(name = "user")
public class User {
    private long id;
    private String username;
    private String password;
    private String name;
    private String surname;
    private UserType type;
    private String dateOfReg;
    private ProfileUser profile;

    public User() {
    }
    //...
    }

pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>project</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.4.RELEASE</version>
        <relativePath/>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.7</java.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cloud-connectors</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>javax.persistence</artifactId>
            <version>2.0.0</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-pool</groupId>
            <artifactId>commons-pool</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>spring-releases</id>
            <url>https://repo.spring.io/libs-release</url>
        </repository>

        <repository>
            <id>codehaus</id>
            <url>http://repository.codehaus.org/org/codehaus</url>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>spring-releases</id>
            <url>https://repo.spring.io/libs-release</url>
        </pluginRepository>
    </pluginRepositories>

</project>

.properties:

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/project?verifyServerCertificate=false&useSSL=true
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.useSSL=false

sping.jpa.hibernate.dialect=org.hibernate.dialect.MySQLDialect
spring.jpa.hibernate.show_sql=true
spring.jpa.hibernate.format_sql=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.hibernate.jdbc.batch_size=50
spring.jpa.hibernate.connection.CharSet=utf8
spring.jpa.hibernate.connection.characterEncoding=utf8
spring.jpa.hibernate.connection.useUnicode=true

error:

org.springframework.beans.factory.UnsatisfiedDependencyException:
  Error creating bean with name
  'org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration':
  Unsatisfied dependency expressed through constructor parameter 0;
  nested exception is
  org.springframework.beans.factory.BeanCreationException: Error
  creating bean with name 'dataSource' defined in class path resource
  [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Tomcat.class]:
  Bean instantiation via factory method failed; nested exception is
  org.springframework.beans.BeanInstantiationException: Failed to
  instantiate [org.apache.tomcat.jdbc.pool.DataSource]: Factory method
  'dataSource' threw exception; nested exception is
  java.lang.IllegalStateException: Cannot load driver class:
  com.mysql.cj.jdbc.Driver  at
  org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:749)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:189)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1193)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1095)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:372)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1173)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1067)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1078)
  ~[spring-context-4.3.9.RELEASE.jar:4.3.9.RELEASE]     at
  org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:857)
  ~[spring-context-4.3.9.RELEASE.jar:4.3.9.RELEASE]     at
  org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543)
  ~[spring-context-4.3.9.RELEASE.jar:4.3.9.RELEASE]     at
  org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122)
  ~[spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE]    at
  org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693)
  [spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE]     at
  org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360)
  [spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE]     at
  org.springframework.boot.SpringApplication.run(SpringApplication.java:303)
  [spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE]     at
  org.springframework.boot.SpringApplication.run(SpringApplication.java:1118)
  [spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE]     at
  org.springframework.boot.SpringApplication.run(SpringApplication.java:1107)
  [spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE]     at
  com.example.Sbz3Application.main(Sbz3Application.java:10)
  [classes/:na] Caused by:
  org.springframework.beans.factory.BeanCreationException: Error
  creating bean with name 'dataSource' defined in class path resource
  [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Tomcat.class]:
  Bean instantiation via factory method failed; nested exception is
  org.springframework.beans.BeanInstantiationException: Failed to
  instantiate [org.apache.tomcat.jdbc.pool.DataSource]: Factory method
  'dataSource' threw exception; nested exception is
  java.lang.IllegalStateException: Cannot load driver class:
  com.mysql.cj.jdbc.Driver  at
  org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1173)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1067)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:208)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1138)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:835)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:741)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   ... 28 common frames
  omitted Caused by:
  org.springframework.beans.BeanInstantiationException: Failed to
  instantiate [org.apache.tomcat.jdbc.pool.DataSource]: Factory method
  'dataSource' threw exception; nested exception is
  java.lang.IllegalStateException: Cannot load driver class:
  com.mysql.cj.jdbc.Driver  at
  org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   ... 41 common frames
  omitted Caused by: java.lang.IllegalStateException: Cannot load driver
  class: com.mysql.cj.jdbc.Driver   at
  org.springframework.util.Assert.state(Assert.java:70)
  ~[spring-core-4.3.9.RELEASE.jar:4.3.9.RELEASE]    at
  org.springframework.boot.autoconfigure.jdbc.DataSourceProperties.determineDriverClassName(DataSourceProperties.java:231)
  ~[spring-boot-autoconfigure-1.5.4.RELEASE.jar:1.5.4.RELEASE]  at
  org.springframework.boot.autoconfigure.jdbc.DataSourceProperties.initializeDataSourceBuilder(DataSourceProperties.java:183)
  ~[spring-boot-autoconfigure-1.5.4.RELEASE.jar:1.5.4.RELEASE]  at
  org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration.createDataSource(DataSourceConfiguration.java:42)
  ~[spring-boot-autoconfigure-1.5.4.RELEASE.jar:1.5.4.RELEASE]  at
  org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration$Tomcat.dataSource(DataSourceConfiguration.java:56)
  ~[spring-boot-autoconfigure-1.5.4.RELEASE.jar:1.5.4.RELEASE]  at
  sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  ~[na:1.8.0_25]    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown
  Source) ~[na:1.8.0_25]    at
  sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
  ~[na:1.8.0_25]    at java.lang.reflect.Method.invoke(Unknown Source)
  ~[na:1.8.0_25]    at
  org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   ... 42 common frames
  omitted

Body:
Your project is using Mysql5.1, and the Driver class you are attempting to load does not exist there (com.mysql.cj.jdbc.Driver).
See if this helps - change the application.properties line from

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

to

spring.datasource.driver-class-name=com.mysql.jdbc.Driver


来源: stackexchange

问:
How to check if the mouse is clicked in a certain area (pygame)
I am trying to make a program in pygame which will print something if the mouse is pressed in a certain area. I have tried using the mouse.get_pos and mouse.get_pressed but I am not sure if I am using them correctly. Here is my code    </p>

```<code>while True:
    DISPLAYSURF.fill(BLACK)
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            mpos = pygame.mouse.get_pos()
            mpress = pygame.mouse.get_pressed()
            if mpos[0] >= 400 and mpos[1] <= 600 and mpress == True:
                print "Switching Tab"
</code>```

答:
Use a pygame.Rect to define the area, check if the mouse button was pressed in the event loop and use the collidepoint method of the area rect to see if it collides with the event.pos (alternatively pygame.mouse.get_pos()).

```<code>import sys
import pygame as pg

def main():
    screen = pg.display.set_mode((640, 480))
    clock = pg.time.Clock()
    # A pygame.Rect to define the area.
    area = pg.Rect(100, 150, 200, 124)

    done = False

    while not done:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                done = True
            if event.type == pg.MOUSEBUTTONDOWN:
                if event.button == 1:  # Left mouse button.
                    # Check if the rect collides with the mouse pos.
                    if area.collidepoint(event.pos):
                        print('Area clicked.')

        screen.fill((30, 30, 30))
        pg.draw.rect(screen, (100, 200, 70), area)

        pg.display.flip()
        clock.tick(30)

if __name__ == '__main__':
    pg.init()
    main()
    pg.quit()
    sys.exit()
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to make a program in pygame which will print something if the mouse is pressed in a certain area. I have tried using the mouse.get_pos and mouse.get_pressed but I am not sure if I am using them correctly. Here is my code

while True:
    DISPLAYSURF.fill(BLACK)
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            mpos = pygame.mouse.get_pos()
            mpress = pygame.mouse.get_pressed()
            if mpos[0] >= 400 and mpos[1] <= 600 and mpress == True:
                print "Switching Tab"

Body:
Use a pygame.Rect to define the area, check if the mouse button was pressed in the event loop and use the collidepoint method of the area rect to see if it collides with the event.pos (alternatively pygame.mouse.get_pos()).

import sys
import pygame as pg

def main():
    screen = pg.display.set_mode((640, 480))
    clock = pg.time.Clock()
    # A pygame.Rect to define the area.
    area = pg.Rect(100, 150, 200, 124)

    done = False

    while not done:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                done = True
            if event.type == pg.MOUSEBUTTONDOWN:
                if event.button == 1:  # Left mouse button.
                    # Check if the rect collides with the mouse pos.
                    if area.collidepoint(event.pos):
                        print('Area clicked.')

        screen.fill((30, 30, 30))
        pg.draw.rect(screen, (100, 200, 70), area)

        pg.display.flip()
        clock.tick(30)

if __name__ == '__main__':
    pg.init()
    main()
    pg.quit()
    sys.exit()


问:
Unable to connect to SQL Server with PHP
Connection to sqlsrv string not working.

```<code>$login = new PDO("sqlsrv:server=MYSQLSERVER\SQLEXPRESS;Database=db_name", "user", "passw");
</code>```

And i have error message:
Fatal error: Invalid handle returned.

I'm 101% sure that login details is OK. Because it works on other projects. Could be a problem PHP 7?

答:
There's a problem with PHP Sql Server driver

You should update it to new version

As you mentioned you are using windows, this version is fully working on windows

https://github.com/Microsoft/msphpsql/releases/tag/v4.1.1-Windows

Body:
Connection to sqlsrv string not working.

$login = new PDO("sqlsrv:server=MYSQLSERVER\SQLEXPRESS;Database=db_name", "user", "passw");

And i have error message:
Fatal error: Invalid handle returned.

I'm 101% sure that login details is OK. Because it works on other projects. Could be a problem PHP 7?


问:
Swift Alamofire Getting Token from Refresh Token Request Error
I'm pretty new to using Alamofire, and I am banging my head against the wall with this request. I'm using GIDSignIn, and successfully get a token and refresh token for the user, with the scope ["https://www.googleapis.com/auth/youtube.readonly"].

I'm trying to complete this request, as shown as an example on the site. The site says to ignore using client_secret for iOS, which I do.

```<code>POST /oauth2/v4/token HTTP/1.1
Host: www.googleapis.com
Content-Type: application/x-www-form-urlencoded

client_id=<your_client_id>&
client_secret=<your_client_secret>&
refresh_token=<refresh_token>&
grant_type=refresh_token
</code>```

Below is how I've implemented it with Alamofire. My client_id is the value from the CLIENT_ID key in the GoogleService-Info.Plist, a string ending in .apps.googleusercontent.com. The refresh_token also seems to have the right format from other examples I've seen online.

```<code>let endpoint = "https://www.googleapis.com/oauth2/v4/token"
let parameters = [
    "client_id" : client_id,
    "refresh_token" : refresh_token,
    "grant_type" : "refresh_token"
]

Alamofire.request(endpoint, method: .post,
                  parameters: parameters,
                  encoding: JSONEncoding.default)

        .responseJSON { (data) in
            print("data: \(data)")
            let json = JSON(data.result)
        }
</code>```

The data response is

```<code>data: SUCCESS: {
    error = "unsupported_grant_type";
    "error_description" = "Invalid grant_type: ";
}
</code>```

Not terribly successful. Do I need to configure my request differently, or get appropriate access / permission to get the token? Thank you so much!

答:
@BikeshThakur helped me figure it out! The URLEncoding.httpBody did the trick! I don't need any headers either.</p>

```<code>Alamofire.request(endpoint, method: .post,
                  parameters: parameters,
                  encoding: URLEncoding.httpBody)
</code>```

Body:
I'm pretty new to using Alamofire, and I am banging my head against the wall with this request. I'm using GIDSignIn, and successfully get a token and refresh token for the user, with the scope ["https://www.googleapis.com/auth/youtube.readonly"].

I'm trying to complete this request, as shown as an example on the site. The site says to ignore using client_secret for iOS, which I do.

POST /oauth2/v4/token HTTP/1.1
Host: www.googleapis.com
Content-Type: application/x-www-form-urlencoded

client_id=<your_client_id>&
client_secret=<your_client_secret>&
refresh_token=<refresh_token>&
grant_type=refresh_token

Below is how I've implemented it with Alamofire. My client_id is the value from the CLIENT_ID key in the GoogleService-Info.Plist, a string ending in .apps.googleusercontent.com. The refresh_token also seems to have the right format from other examples I've seen online.

let endpoint = "https://www.googleapis.com/oauth2/v4/token"
let parameters = [
    "client_id" : client_id,
    "refresh_token" : refresh_token,
    "grant_type" : "refresh_token"
]

Alamofire.request(endpoint, method: .post,
                  parameters: parameters,
                  encoding: JSONEncoding.default)

        .responseJSON { (data) in
            print("data: \(data)")
            let json = JSON(data.result)
        }

The data response is

data: SUCCESS: {
    error = "unsupported_grant_type";
    "error_description" = "Invalid grant_type: ";
}

Not terribly successful. Do I need to configure my request differently, or get appropriate access / permission to get the token? Thank you so much!

Body:
@BikeshThakur helped me figure it out! The URLEncoding.httpBody did the trick! I don't need any headers either.

Alamofire.request(endpoint, method: .post,
                  parameters: parameters,
                  encoding: URLEncoding.httpBody)


问:
Using set doesn't affect view with Data Binding
I'm trying to change different EditText properties using data binding but it doesn't seem to be working.

custom_edittext.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
    <data>
        <variable
            name="textVar"
            type="String"/>
    </data>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <EditText
            android:id="@+id/descriptionTextEdit"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentStart="true"
            android:ems="12"
            android:inputType="textMultiLine"
            android:text="@{textVar}"/>
    </RelativeLayout>
</layout>
</code>```

My class extends RelativeLayout

```<code>public class CustomEditText extends RelativeLayout {
public CustomEditText(Context context) {
        super(context);
        init(context, null);
    }

    public CustomEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public CustomEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }
}
</code>```

and my init:

```<code>private void init(Context context, AttributeSet attrs){
         View.inflate(context, R.layout.custom_edittext, this);

         CustomEdittextBinding stomEdittextBinding = DataBindingUtil.inflate(LayoutInflater.from(context), R.layout.custom_edittext, null, false);

         Drawable drawableButton = context.getResources().getDrawable(R.drawable.ic_action_name);//context.getResources().getDrawable(R.drawable.ic_action_name);
         customEdittextBinding.setTextVar("new text"); //it should change the text, shouldn't it?
         }
</code>```

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

```<code>    customEditText = findViewById(R.id.custom);
}
</code>```

and inside the activity_main.xml I've added my CustomEditText like this but there is an error - The following classes could not be found.

```<code><com.example.xxx.app.CustomEditText
        android:id="@+id/custom"
        android:layout_width="344dp"
        android:layout_height="50dp"
        android:paddingLeft="100dp"
        tools:layout_editor_absoluteX="8dp"
        tools:layout_editor_absoluteY="8dp"></com.example.xxx.app.CustomEditText >
</code>```

答: Ok, I've solved this problem by adding addView(customEdittextBinding.getRoot()); after instantiating CustomEdittextBinding.

Body:
I'm trying to change different EditText properties using data binding but it doesn't seem to be working.

custom_edittext.xml:

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
    <data>
        <variable
            name="textVar"
            type="String"/>
    </data>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <EditText
            android:id="@+id/descriptionTextEdit"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentStart="true"
            android:ems="12"
            android:inputType="textMultiLine"
            android:text="@{textVar}"/>
    </RelativeLayout>
</layout>

My class extends RelativeLayout

public class CustomEditText extends RelativeLayout {
public CustomEditText(Context context) {
        super(context);
        init(context, null);
    }

    public CustomEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public CustomEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }
}

and my init:

private void init(Context context, AttributeSet attrs){
         View.inflate(context, R.layout.custom_edittext, this);

         CustomEdittextBinding stomEdittextBinding = DataBindingUtil.inflate(LayoutInflater.from(context), R.layout.custom_edittext, null, false);

         Drawable drawableButton = context.getResources().getDrawable(R.drawable.ic_action_name);//context.getResources().getDrawable(R.drawable.ic_action_name);
         customEdittextBinding.setTextVar("new text"); //it should change the text, shouldn't it?
         }

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

    customEditText = findViewById(R.id.custom);
}

and inside the activity_main.xml I've added my CustomEditText like this but there is an error - The following classes could not be found.

<com.example.xxx.app.CustomEditText
        android:id="@+id/custom"
        android:layout_width="344dp"
        android:layout_height="50dp"
        android:paddingLeft="100dp"
        tools:layout_editor_absoluteX="8dp"
        tools:layout_editor_absoluteY="8dp"></com.example.xxx.app.CustomEditText >


问:
Update ttl for all records in aerospike
I was stuck in a situation that I have initialised a namesapce with
default-ttl to 30 days. There was about 5 million data with that (30-day calculated) ttl-value. Actually, my requirement is that ttl should be zero(0), but It(ttl-30d) was kept with unaware or un-recognise.

So, Now I want to update prev(old) 5 million data with new ttl-value (Zero).

I've checked/tried "set-disable-eviction true", but it is not working, it is removing data according to (old)ttl-value.

How do I overcome out this? (and I want to retrieve the removed data, How can I?).

Someone help me.

答:
First, eviction and expiration are two different mechanisms. You can disable evictions in various ways, such as the set-disable-eviction config parameter you've used. You cannot disable the cleanup of expired records. There's a good knowledge base FAQ What are Expiration, Eviction and Stop-Writes?. Unfortunately, the expired records that have been cleaned up are gone if their void time is in the past. If those records were merely evicted (i.e. removed before their void time due to crossing the namespace high-water mark for memory or disk) you can cold restart your node, and those records with a future TTL will come back. They won't return if either they were durably deleted or if their TTL is in the past (such records gets skipped).

As for resetting TTLs, the easiest way would be to do this through a record UDF that is applied to all the records in your namespace using a scan.

The UDF for your situation would be very simple:

ttl.lua

```<code>function to_zero_ttl(rec)
  local rec_ttl = record.ttl(rec)
  if rec_ttl > 0 then
    record.set_ttl(rec, -1)
    aerospike:update(rec)
  end
end
</code>```

In AQL:

```<code>$ aql
Aerospike Query Client
Version 3.12.0
C Client Version 4.1.4
Copyright 2012-2017 Aerospike. All rights reserved.
aql> register module './ttl.lua'
OK, 1 module added.

aql> execute ttl.to_zero_ttl() on test.foo
</code>```

Title: Update ttl for all records in aerospike

Body:
First, eviction and expiration are two different mechanisms. You can disable evictions in various ways, such as the set-disable-eviction config parameter you've used. You cannot disable the cleanup of expired records. There's a good knowledge base FAQ What are Expiration, Eviction and Stop-Writes?. Unfortunately, the expired records that have been cleaned up are gone if their void time is in the past. If those records were merely evicted (i.e. removed before their void time due to crossing the namespace high-water mark for memory or disk) you can cold restart your node, and those records with a future TTL will come back. They won't return if either they were durably deleted or if their TTL is in the past (such records gets skipped).

As for resetting TTLs, the easiest way would be to do this through a record UDF that is applied to all the records in your namespace using a scan.

The UDF for your situation would be very simple:

ttl.lua

function to_zero_ttl(rec)
  local rec_ttl = record.ttl(rec)
  if rec_ttl > 0 then
    record.set_ttl(rec, -1)
    aerospike:update(rec)
  end
end

In AQL:

$ aql
Aerospike Query Client
Version 3.12.0
C Client Version 4.1.4
Copyright 2012-2017 Aerospike. All rights reserved.
aql> register module './ttl.lua'
OK, 1 module added.

aql> execute ttl.to_zero_ttl() on test.foo

ContentLicense: CC BY-SA 4.0


问:
JQuery/javascript: How to run a 'complete' eventlistener on a custom function?
I have the following call

```<code>$('.fblikes span').fblikecount();

$.fn.fblikecount = function(){

    //DO SOME JSON XHR stuff to get FB like counts and update the # on page ...
}
</code>```

which will run through all my fblikes classes (about 30) and run my 'socialscore' function on them, which basically updates the facebook like count for each one.

After ALL of them are completed, I wanted to run another function, I was thinking a callback is the way to go and have it run as an eventlistener for when the facebooklikecount() function is completed for all iterations of the .fblikes class.  I can succussfully run a callback for each individual call of fblikecount but I just want to run the callback ONCE when ALL of the fblikecount functions have completed.

My ideal solution would be something like this

```<code>$('.fblikes span').fblikecount().on( "complete", function() {
  //do something
});
</code>```

Possible?

答:
I would use a counter... And an Ajax global event like .ajaxComplete().

```<code>// Start by counting how many element are targetted.
var fblikesTotal = $('.fblikes span').length;

// Your function call.
$('.fblikes span').fblikecount();

// Your function.
$.fn.fblikecount = function(){

    //DO SOME JSON XHR stuff to get FB like counts and update the # on page ...

}

// On each ajax request completed
// Decrement fblikesTotal
// And check if it is all done.
$( document ).ajaxComplete(function(){

  // Decrement fblikesTotal
  fblikesTotal--;

  if(fblikesTotal==0){

    // Call your second function here.
    // ...

  }
});
</code>```

Body:
I have the following call

$('.fblikes span').fblikecount();

$.fn.fblikecount = function(){

    //DO SOME JSON XHR stuff to get FB like counts and update the # on page ...
}

which will run through all my fblikes classes (about 30) and run my 'socialscore' function on them, which basically updates the facebook like count for each one.

After ALL of them are completed, I wanted to run another function, I was thinking a callback is the way to go and have it run as an eventlistener for when the facebooklikecount() function is completed for all iterations of the .fblikes class.  I can succussfully run a callback for each individual call of fblikecount but I just want to run the callback ONCE when ALL of the fblikecount functions have completed.

My ideal solution would be something like this

$('.fblikes span').fblikecount().on( "complete", function() {
  //do something
});

Possible?

Body:
I would use a counter... And an Ajax global event like .ajaxComplete().

// Start by counting how many element are targetted.
var fblikesTotal = $('.fblikes span').length;

// Your function call.
$('.fblikes span').fblikecount();

// Your function.
$.fn.fblikecount = function(){

    //DO SOME JSON XHR stuff to get FB like counts and update the # on page ...

}

// On each ajax request completed
// Decrement fblikesTotal
// And check if it is all done.
$( document ).ajaxComplete(function(){

  // Decrement fblikesTotal
  fblikesTotal--;

  if(fblikesTotal==0){

    // Call your second function here.
    // ...

  }
});


问:
getToken() failed. Status BAD_AUTHENTICATION error
I've found the following error when running my android application in android studio. app couldn't get installed on my device because of this error. Didn't find the solution :(
please help

Auth: [GoogleAccountDataServiceImpl] getToken() failed.
  Status BAD_AUTHENTICATION,
  Account: ,
  App:com.android.vending,
  Service: androidmarket com.google.android.gms.auth.be.account.b.d: Long live credential not
  available.

答:
I had the same issue what helped me was that I had wrong credentials in my google-services.json file and after getting a new file my problem was fixed.

in the process of resolving this issue I also updated my google play services but I do not think this is necessary .


问:
Why are aggregate and fold two different APIs in Spark?
When using the Scala standard lib, I can do somthing like this:

```<code>scala> val scalaList = List(1,2,3)
scalaList: List[Int] = List(1, 2, 3)

scala> scalaList.foldLeft(0)((acc,n)=>acc+n)
res0: Int = 6
</code>```

Making one Int out of many Ints.

And I can do something like this:

```<code>scala> scalaList.foldLeft("")((acc,n)=>acc+n.toString)
res1: String = 123
</code>```

Making one String out of many Ints.

So, foldLeft could be either homogeneous or heterogeneous, whichever we want, it's in one API.

While in Spark, if I want one Int out of many Ints, I can do this:

```<code>scala> val rdd = sc.parallelize(List(1,2,3))
rdd: org.apache.spark.rdd.RDD[Int] = ParallelCollectionRDD[1] at parallelize at <console>:12
scala> rdd.fold(0)((acc,n)=>acc+n)
res1: Int = 6
</code>```

The fold API is similar to foldLeft, but it is only homogeneous, a RDD[Int] can only produce Int with fold.

There is a aggregate API in spark too:

```<code>scala> rdd.aggregate("")((acc,n)=>acc+n.toString, (s1,s2)=>s1+s2)
res11: String = 132
</code>```

It is heterogeneous, a RDD[Int] can produce a String now.

So, why are fold and aggregate implemented as two different APIs in Spark?

Why are they not designed like foldLeft that could be both homogeneous and heterogeneous?

(I am very new to Spark, please excuse me if this is a silly question.)

答:
foldLeft, foldRight, reduceLeft, reduceRight, scanLeft and scanRight are operations where the accumulated parameter can be different from the input parameters ((A, B) -> B) and those operations can only be executed sequentially.

fold is an operation where the accumulated parameter has to be the same type of the input parameters ((A, A) -> A). Then it can be executed in parallel.

aggregation is an operation where the accumulated parameter can be of different type as the input parameters, but then you have to provide an additional function that defines how the accumulated parameters can be aggregated in the final result. This operation allows parallel execution. The aggregation operation is a combination of foldLeft and fold.

For more detailed information, you can have a look at the coursera videos for the "Parallel programming" course:

https://www.coursera.org/learn/parprog1/lecture/efzVT/data-parallel-operations-i

https://www.coursera.org/learn/parprog1/lecture/shwKn/data-parallel-operations-ii

Body:
When using the Scala standard lib, I can do somthing like this:

scala> val scalaList = List(1,2,3)
scalaList: List[Int] = List(1, 2, 3)

scala> scalaList.foldLeft(0)((acc,n)=>acc+n)
res0: Int = 6

Making one Int out of many Ints.

And I can do something like this:

scala> scalaList.foldLeft("")((acc,n)=>acc+n.toString)
res1: String = 123

Making one String out of many Ints.

So, foldLeft could be either homogeneous or heterogeneous, whichever we want, it's in one API.

While in Spark, if I want one Int out of many Ints, I can do this:

scala> val rdd = sc.parallelize(List(1,2,3))
rdd: org.apache.spark.rdd.RDD[Int] = ParallelCollectionRDD[1] at parallelize at <console>:12
scala> rdd.fold(0)((acc,n)=>acc+n)
res1: Int = 6

The fold API is similar to foldLeft, but it is only homogeneous, a RDD[Int] can only produce Int with fold.

There is a aggregate API in spark too:

scala> rdd.aggregate("")((acc,n)=>acc+n.toString, (s1,s2)=>s1+s2)
res11: String = 132

It is heterogeneous, a RDD[Int] can produce a String now.

So, why are fold and aggregate implemented as two different APIs in Spark?

Why are they not designed like foldLeft that could be both homogeneous and heterogeneous?

(I am very new to Spark, please excuse me if this is a silly question.)


问:
Redirect User to encoded URL-Variable
I am currently working on a URL, which encodes the URL entered by URL variable. The user is then redirected to http://example.net/?enc_url=THE ENCODED LINK.

This is my previous code:

```<code><!DOCTYPE html>
<html>
    <script type="text/javascript">
        setTimeout(function() {
            var uri = <?php echo $_GET["url"]; ?>
            var res = encodeURI(uri)
            location.href = 'http://example.com"/?enc_url={$res}'
        }
    </script>
</html>
</code>```

Please help me, but remember that I do not have much experience with PHP yet. Thanks for any help!

Greetings!

答:
You're trying to use PHP syntax in Javascript. In Javascript use concatenation.

```<code>var res = encodeURIComponent(uri);
location.href = 'http://example.com/?enc_url=' + res;
</code>```

You're also missing the closing ) for the setTimeout() call. And you should be using encodeURIComponent, not encodeURI; see Should I use encodeURI or encodeURIComponent for encoding URLs?

Title: Redirect User to encoded URL-Variable

Body:
I am currently working on a URL, which encodes the URL entered by URL variable. The user is then redirected to http://example.net/?enc_url=THE ENCODED LINK.

This is my previous code:

<!DOCTYPE html>

Please help me, but remember that I do not have much experience with PHP yet. Thanks for any help!

Greetings!

Body:
You're trying to use PHP syntax in Javascript. In Javascript use concatenation.

var res = encodeURIComponent(uri);
location.href = 'http://example.com/?enc_url=' + res;

You're also missing the closing ) for the setTimeout() call. And you should be using encodeURIComponent, not encodeURI; see Should I use encodeURI or encodeURIComponent for encoding URLs?


问:
compare two text files using linq?
I have 4 text files in one folder and a pattern.txt to compare these text files..In pattern.txt i have

```<code>insert
update
delete
drop
</code>```

I need to compare this text file with those four text files and if these patterns matches any line in that text files i have to write those lines in another log file...i had read those files using linq..i need to compare those files and write in a text file with line number..here is my code

```<code>var foldercontent = Directory.GetFiles(pathA)
                    .Select(filename => File.ReadAllText(filename))
                    .Aggregate(new StringBuilder(),
                    (sb, s) => sb.Append(s).Append(Environment.NewLine),
                    sb => sb.ToString());

 var pattern =  File.ReadAllLines(pathB).Aggregate(new StringBuilder(),
                    (sb, s) => sb.Append(s).Append(Environment.NewLine),
                    sb => sb.ToString());

using (var dest = File.AppendText(Path.Combine(_logFolderPath, "log.txt")))
            {
      //dest.WriteLine("LineNo : " + counter.ToString() + " : " + "" + line);
            }
</code>```

EDIT
I have already used c# to compare two text files but i need this in linq

```<code>while ((line = file.ReadLine()) != null)
{
if (line.IndexOf(line2, StringComparison.CurrentCultureIgnoreCase) != -1)
{
dest.WriteLine("LineNo : " + counter.ToString() + " : " + " " + line.TrimStart());
}
counter++;
}
file.BaseStream.Seek(0, SeekOrigin.Begin);
counter = 1;
</code>```

答:
There might be a simpler solution, but this is at least working if you really want to use LINQ:

```<code>var foldercontent = Directory.GetFiles(pathA)
                    .Select(filename => new
                    {
                        Filename = filename,
                        Lines = File.ReadAllLines(filename)
                    })
                    .SelectMany(file => file.Lines.Select((line, idx) => new
                    {
                        LineNumber = idx + 1,
                        Text = line,
                        FileName = file.Filename
                    }));

var pattern = File.ReadAllLines(pathB);

var result = from fileLine in foldercontent
             where pattern.Any(p => fileLine.Text.IndexOf(p, StringComparison.CurrentCultureIgnoreCase) != -1)
             select fileLine;

foreach (var match in result)
{
    System.Diagnostics.Debug.WriteLine("File: {0} LineNo: {1}: Text: {2}", match.FileName, match.LineNumber, match.Text);
}
</code>```

Or if you want, you can combine that into one LINQ query (but thats not very readable i think):

```<code>var result = from fileLine in (Directory.GetFiles(pathA)
                    .Select(filename => new
                    {
                        Filename = filename,
                        Lines = File.ReadAllLines(filename)
                    })
                    .SelectMany(file => file.Lines.Select((line, idx) => new
                    {
                        LineNumber = idx + 1,
                        Text = line,
                        FileName = file.Filename
                    })))
                where File.ReadAllLines(pathB).Any(p => fileLine.Text.IndexOf(p, StringComparison.CurrentCultureIgnoreCase) != -1)
                select fileLine;
</code>```

ContentLicense: CC BY-SA 2.5

Title: compare two text files using linq?

Body:
I have 4 text files in one folder and a pattern.txt to compare these text files..In pattern.txt i have

insert
update
delete
drop

I need to compare this text file with those four text files and if these patterns matches any line in that text files i have to write those lines in another log file...i had read those files using linq..i need to compare those files and write in a text file with line number..here is my code

var foldercontent = Directory.GetFiles(pathA)
                    .Select(filename => File.ReadAllText(filename))
                    .Aggregate(new StringBuilder(),
                    (sb, s) => sb.Append(s).Append(Environment.NewLine),
                    sb => sb.ToString());

 var pattern =  File.ReadAllLines(pathB).Aggregate(new StringBuilder(),
                    (sb, s) => sb.Append(s).Append(Environment.NewLine),
                    sb => sb.ToString());

using (var dest = File.AppendText(Path.Combine(_logFolderPath, "log.txt")))
            {
      //dest.WriteLine("LineNo : " + counter.ToString() + " : " + "" + line);
            }

EDIT
I have already used c# to compare two text files but i need this in linq

while ((line = file.ReadLine()) != null)
{
if (line.IndexOf(line2, StringComparison.CurrentCultureIgnoreCase) != -1)
{
dest.WriteLine("LineNo : " + counter.ToString() + " : " + " " + line.TrimStart());
}
counter++;
}
file.BaseStream.Seek(0, SeekOrigin.Begin);
counter = 1;

Body:
There might be a simpler solution, but this is at least working if you really want to use LINQ:

var foldercontent = Directory.GetFiles(pathA)
                    .Select(filename => new
                    {
                        Filename = filename,
                        Lines = File.ReadAllLines(filename)
                    })
                    .SelectMany(file => file.Lines.Select((line, idx) => new
                    {
                        LineNumber = idx + 1,
                        Text = line,
                        FileName = file.Filename
                    }));

var pattern = File.ReadAllLines(pathB);

var result = from fileLine in foldercontent
             where pattern.Any(p => fileLine.Text.IndexOf(p, StringComparison.CurrentCultureIgnoreCase) != -1)
             select fileLine;

foreach (var match in result)
{
    System.Diagnostics.Debug.WriteLine("File: {0} LineNo: {1}: Text: {2}", match.FileName, match.LineNumber, match.Text);
}

Or if you want, you can combine that into one LINQ query (but thats not very readable i think):

var result = from fileLine in (Directory.GetFiles(pathA)
                    .Select(filename => new
                    {
                        Filename = filename,
                        Lines = File.ReadAllLines(filename)
                    })
                    .SelectMany(file => file.Lines.Select((line, idx) => new
                    {
                        LineNumber = idx + 1,
                        Text = line,
                        FileName = file.Filename
                    })))
                where File.ReadAllLines(pathB).Any(p => fileLine.Text.IndexOf(p, StringComparison.CurrentCultureIgnoreCase) != -1)
                select fileLine;


问:
c# regex to match only hyphen words
Basically if I have aaa-aaa it should be match.
If it's aaaa-bbbb--- it should match aaaa-bbbb
If its only aaaa it should NOT match.

I want to do it with regex, Any ideas ?

Currently I have

```<code>(?=\\S*[-])([a-zA-Z-]+)
</code>```

答:
You could use a Whitespace boundary on the front and a Word boundary at the  back.

(?<!\S)[^-\s]+-[^-\s]+\b

Title: c# regex to match only hyphen words

Body:
Basically if I have aaa-aaa it should be match.
If it's aaaa-bbbb--- it should match aaaa-bbbb
If its only aaaa it should NOT match.

I want to do it with regex, Any ideas ?

Currently I have

(?=\\S*[-])([a-zA-Z-]+)


答:
Only PHP:

```<code><?php
$enc_url = urlencode($_GET['url']);
header("Location: http://example.com/?enc_url=$enc_url");
?>
</code>```

JavaScript:

```<code><!DOCTYPE html>
<html>
<script type="text/javascript">
setTimeout(function() {
    var uri = "<?php echo urlencode($_GET["url"]); ?>";
    location.href = `http://example.com/?enc_url=${uri}`;
}, 3000);
</script>
</html>
</code>```

Title: Redirect User to encoded URL-Variable

Body:
Only PHP:

<?php
$enc_url = urlencode($_GET['url']);
header("Location: http://example.com/?enc_url=$enc_url");
?>

JavaScript:

<!DOCTYPE html>
<html>
<script type="text/javascript">
setTimeout(function() {
    var uri = "<?php echo urlencode($_GET["url"]); ?>";
    location.href = `http://example.com/?enc_url=${uri}`;
}, 3000);
</script>
</html>


问:
When creating a database model in Django, how can I create fields that will only accept a month and year, respectively?
If I use something like

```<code>   year_published = models.DateField()
</code>```

then I have to enter in a day and month, in addition to a year. But in this field I only want to enter a year. Likewise, I only want to enter a month in

```<code>   month_published = models.DateField()
</code>```

Any idea how to do this?

答:
If you only store the year, how will you sort on Month and Date? Instead, store the full datetime object or split out the full date into three fields.  As already mentioned, these would normally be Char fields, but can be Int and can be converted back to date to sort and compare/diff.  See:

How to convert integer into date object python?

Or simply store the full date natively and then get the chunks you need from it as you need it.  You might check out the Pendulum Package which opens up a lot more options on date operations.

Body:
If I use something like

   year_published = models.DateField()

then I have to enter in a day and month, in addition to a year. But in this field I only want to enter a year. Likewise, I only want to enter a month in

   month_published = models.DateField()

Any idea how to do this?


问:
Why is this UrlFetch function not working properly?
This is the function I'm trying to run through the JavaScript Tool on my Google Spreadsheet chart, the function is currently working on 4 different websites, where in this example:

$id is the imported value from my spreadsheet cell (belacoin)

```<code>function CoinmarketcapPrice($id) {
  var response = UrlFetchApp.fetch("https://api.coinmarketcap.com/v1/ticker/" + $id);
  var html = JSON.parse(response.getContentText());
  try
  {
    return parseFloat(html["price_btc"]);
  }
  catch(err)
  {
    return null;
  }
}
</code>```

this is what that UrlFetch returns:

```<code>[
    {
        "id": "belacoin",
        "name": "BelaCoin",
        "symbol": "BELA",
        "rank": "176",
        "price_usd": "0.212823",
        "price_btc": "0.00008400",
        "24h_volume_usd": "534995.0",
        "market_cap_usd": "7694903.0",
        "available_supply": "36156350.0",
        "total_supply": "36156350.0",
        "percent_change_1h": "0.63",
        "percent_change_24h": "1.88",
        "percent_change_7d": "-17.03",
        "last_updated": "1499549044"
    }
]
</code>```

答: try html.price_btc or html[0].price_btc</p>

Body:
This is the function I'm trying to run through the JavaScript Tool on my Google Spreadsheet chart, the function is currently working on 4 different websites, where in this example:

$id is the imported value from my spreadsheet cell (belacoin)

function CoinmarketcapPrice($id) {
  var response = UrlFetchApp.fetch("https://api.coinmarketcap.com/v1/ticker/" + $id);
  var html = JSON.parse(response.getContentText());
  try
  {
    return parseFloat(html["price_btc"]);
  }
  catch(err)
  {
    return null;
  }
}

this is what that UrlFetch returns:

[
    {
        "id": "belacoin",
        "name": "BelaCoin",
        "symbol": "BELA",
        "rank": "176",
        "price_usd": "0.212823",
        "price_btc": "0.00008400",
        "24h_volume_usd": "534995.0",
        "market_cap_usd": "7694903.0",
        "available_supply": "36156350.0",
        "total_supply": "36156350.0",
        "percent_change_1h": "0.63",
        "percent_change_24h": "1.88",
        "percent_change_7d": "-17.03",
        "last_updated": "1499549044"
    }
]

Body: try html.price_btc or html[0].price_btc


问:
Server hangs all requests after a while
Our Rails 4.0 application (Ruby 2.1.2) is running on Nginx with Puma 2.9.0.

I recently noticed that all requests to our application hang after a while (usually 1 or 2 days).

When checking the log, which is set to debug mode, I noticed the following log stack up:

```<code>[2014-10-11T00:02:31.727382 #23458]  INFO -- : Started GET "/" for ...
</code>```

It does mean that requests actually hit the Rails app but somehow it isn't proceeded, while normally it would be:

```<code>I, [2014-10-11T00:02:31.727382 #23458]  INFO -- : Started GET "/" for ....
I, [2014-10-11T00:02:31.729393 #23458]  INFO -- : Processing by HomeController#index as HTML
</code>```

My puma config is the following:

```<code>threads 16,32
workers 4
</code>```

Our application is only for internal usage as now, so the RPM is very low, and none of the requests are take longer than 2s.

What is/are the reasons that could lead to this problem? (puma config, database connection, etc.)

Thank you in advance.

Update:
After installing the gem rack_timer to log the time spent on each middleware, I realized that our requests has been stuck at the ActiveRecord::QueryCache when the hang occurred, with huge amount of time on it:

```<code>Rack Timer (incoming) -- ActiveRecord::QueryCache: 925626.7731189728 ms
</code>```

I removed this middleware for now and it seems to be back to normal. However, I understand the purpose of this middleware is to increase the performance, so removing it is just a temporary solution. Please help me find out the possible cause of this issue.

FYI, we're using mysql (5.1.67) with adapter mysql2 (0.3.13)

答:
It could be a symptom of RAM starvation due to the query cache getting too big.  We saw this in one of our apps running on Heroku.  The default query cache is set to 1000.  Lowering the limit eased the RAM usage for us with no noticeable performance degradation:

database.yml:

```<code>default: &default
  adapter: postgresql
  pool: <%= ENV["DB_POOL"] || ENV['MAX_THREADS'] || 5 %>
  timeout: 5000
  port: 5432
  host: localhost
  statement_limit: <%= ENV["DB_STATEMENT_LIMIT"] || 200 %>
</code>```

However searching for "activerecord querycache slow" returns other causes, such as perhaps outdated versions of Ruby or Puma or rack-timeout: https://stackoverflow.com/a/44158724/126636

Or maybe a too large value for read_timeout: https://stackoverflow.com/a/30526430/126636

Title: Server hangs all requests after a while

Body:
Our Rails 4.0 application (Ruby 2.1.2) is running on Nginx with Puma 2.9.0.

I recently noticed that all requests to our application hang after a while (usually 1 or 2 days).

When checking the log, which is set to debug mode, I noticed the following log stack up:

[2014-10-11T00:02:31.727382 #23458]  INFO -- : Started GET "/" for ...

It does mean that requests actually hit the Rails app but somehow it isn't proceeded, while normally it would be:

I, [2014-10-11T00:02:31.727382 #23458]  INFO -- : Started GET "/" for ....
I, [2014-10-11T00:02:31.729393 #23458]  INFO -- : Processing by HomeController#index as HTML

My puma config is the following:

threads 16,32
workers 4

Our application is only for internal usage as now, so the RPM is very low, and none of the requests are take longer than 2s.

What is/are the reasons that could lead to this problem? (puma config, database connection, etc.)

Thank you in advance.

Update:
After installing the gem rack_timer to log the time spent on each middleware, I realized that our requests has been stuck at the ActiveRecord::QueryCache when the hang occurred, with huge amount of time on it:

Rack Timer (incoming) -- ActiveRecord::QueryCache: 925626.7731189728 ms

I removed this middleware for now and it seems to be back to normal. However, I understand the purpose of this middleware is to increase the performance, so removing it is just a temporary solution. Please help me find out the possible cause of this issue.

FYI, we're using mysql (5.1.67) with adapter mysql2 (0.3.13)

Body:
It could be a symptom of RAM starvation due to the query cache getting too big.  We saw this in one of our apps running on Heroku.  The default query cache is set to 1000.  Lowering the limit eased the RAM usage for us with no noticeable performance degradation:

database.yml:

default: &default
  adapter: postgresql
  pool: <%= ENV["DB_POOL"] || ENV['MAX_THREADS'] || 5 %>
  timeout: 5000
  port: 5432
  host: localhost
  statement_limit: <%= ENV["DB_STATEMENT_LIMIT"] || 200 %>

However searching for "activerecord querycache slow" returns other causes, such as perhaps outdated versions of Ruby or Puma or rack-timeout: https://stackoverflow.com/a/44158724/126636

Or maybe a too large value for read_timeout: https://stackoverflow.com/a/30526430/126636


问:
How to make a function that out puts a div inside the_content right below the opening  tag?
I have a plugin with a settings page and am wanting certain things inside the wordpress site to display when the fields are filled inside the settings page.

So for example, my global settings page has a google analytics ID field, when its entered, the google analytics tracking code will display right above the closing  tag using the wp_head, and that works totally fine.

My next problem is that I am trying to do this in the_content, but the div i am wanting to appear is not in the right spot, even though you can see that i set add_action( 'the_content', 'hawp_header_schema_opening_div', 1 ); with a priority of 1.

I am very new to this I just need help with what im doing wrong.

```<code><?php
/**
 * Plugin Name: Hawp Media Developer Settings
 * Plugin URI: https://.com
 * Description: This plugin implements additional search engine optimization into the backend of the site.
 * Version: 1.0.0
 * Author: Hawp Media
 * Author URI: https://.com
 * License: GPL2
 */

/*----------------------------------------------------------------------------
 * Hawp Media Global Settings Page
 * ---------------------------------------------------------------------------*/
// The page content surrounding the settings fields
function hawp_global_settings_page(){
  ?>
  <div class="wrap">
    <h1>Hawp Media Settings</h1>
    <p>This information is used around the website, so changing these here will update them across the website.</p>
    <form method="post" action="options.php">
      <?php
      settings_fields("company_information");
      do_settings_sections("hawp-settings");
      submit_button();
      ?>
    </form>
  </div>
  <?php
}

// Here are the settings fields to display you can use inputs, textareas, checkboxes and multi-selects
function display_hawp_opt_logo(){ ?>
  <input type="url" name="hawp_opt_logo" placeholder="Enter LOGO URL" value="<?php echo get_option('hawp_opt_logo'); ?>" size="65">
<?php }
function display_hawp_opt_branding(){ ?>
  <input type="text" name="hawp_opt_branding" placeholder="Enter BRANDING" value="<?php echo get_option('hawp_opt_branding'); ?>" size="65">
<?php }
function display_hawp_opt_phone(){ ?>
  <input type="tel" name="hawp_opt_phone" placeholder="Enter PHONE #" value="<?php echo get_option('hawp_opt_phone'); ?>" size="65">
<?php }
function display_hawp_opt_keyphrase(){ ?>
  <input type="text" name="hawp_opt_keyphrase" placeholder="Enter PRIMARY KEYPHRASE" value="<?php echo get_option('hawp_opt_keyphrase'); ?>" size="65">
<?php }
function display_hawp_opt_street(){ ?>
  <input type="text" name="hawp_opt_street" placeholder="Enter STREET ADDRESS" value="<?php echo get_option('hawp_opt_street'); ?>" size="65">
<?php }
function display_hawp_opt_city(){ ?>
  <input type="text" name="hawp_opt_city" placeholder="Enter CITY" value="<?php echo get_option('hawp_opt_city'); ?>" size="65">
<?php }
function display_hawp_opt_state(){ ?>
  <input type="text" name="hawp_opt_state" placeholder="Enter 2 digit STATE CODE" value="<?php echo get_option('hawp_opt_state'); ?>" size="65">
<?php }
function display_hawp_opt_zip(){ ?>
  <input type="text" name="hawp_opt_zip" placeholder="Enter ZIP" value="<?php echo get_option('hawp_opt_zip'); ?>" size="65">
<?php }
function display_hawp_opt_globalcta(){ ?>
  <textarea type="text" name="hawp_opt_globalcta" placeholder="Enter GLOBAL CTA (also used for social sharing message)" value="<?php echo get_option('hawp_opt_globalcta'); ?>" cols="65" rows="3"><?php echo get_option('hawp_opt_globalcta'); ?></textarea>
<?php }
function display_hawp_opt_bodyschema(){ ?>
  <input type="text" name="hawp_opt_bodyschema" placeholder="SCHEMA TYPE IE LocalBusiness" value="<?php echo get_option('hawp_opt_bodyschema'); ?>" size="65">
<?php }
function display_hawp_opt_productontology(){ ?>
  <input type="text" name="hawp_opt_productontology" placeholder="PRODUCTONTOLOGY PAGE Not Full URL" value="<?php echo get_option('hawp_opt_productontology'); ?>" size="65">
<?php }
function display_hawp_opt_analytics(){ ?>
  <input type="text" name="hawp_opt_analytics" placeholder="ANALYTICS UA CODE Not Full script" value="<?php echo get_option('hawp_opt_analytics'); ?>" size="65">
<?php }

// This tells WP what to enqueue into the <form> area. You need:  1. add_settings_section  2. add_settings_field  3. register_setting
function display_custom_info_fields(){
  add_settings_section("company_information", "Company Information", null, "hawp-settings");
  add_settings_field("hawp_opt_logo", "Company Logo URL", "display_hawp_opt_logo", "hawp-settings", "company_information");
  add_settings_field("hawp_opt_branding", "Business Name", "display_hawp_opt_branding", "hawp-settings", "company_information");
  add_settings_field("hawp_opt_phone", "Primary Phone", "display_hawp_opt_phone", "hawp-settings", "company_information");
  add_settings_field("hawp_opt_keyphrase", "Primary Keyphrase", "display_hawp_opt_keyphrase", "hawp-settings", "company_information");
  add_settings_field("hawp_opt_street", "Primary Street Address", "display_hawp_opt_street", "hawp-settings", "company_information");
  add_settings_field("hawp_opt_city", "Primary City", "display_hawp_opt_city", "hawp-settings", "company_information");
  add_settings_field("hawp_opt_state", "Primary State", "display_hawp_opt_state", "hawp-settings", "company_information");
  add_settings_field("hawp_opt_zip", "Primary Zip", "display_hawp_opt_zip", "hawp-settings", "company_information");
  add_settings_field("hawp_opt_globalcta", "Global/Share CTA", "display_hawp_opt_globalcta", "hawp-settings", "company_information");
  add_settings_field("hawp_opt_bodyschema", "Body Tag Schema", "display_hawp_opt_bodyschema", "hawp-settings", "company_information");
  add_settings_field("hawp_opt_productontology", "Productontology Page", "display_hawp_opt_productontology", "hawp-settings", "company_information");
  add_settings_field("hawp_opt_analytics", "Analytics UA Code", "display_hawp_opt_analytics", "hawp-settings", "company_information");
  register_setting("company_information", "hawp_opt_logo");
  register_setting("company_information", "hawp_opt_branding");
  register_setting("company_information", "hawp_opt_phone");
  register_setting("company_information", "hawp_opt_keyphrase");
  register_setting("company_information", "hawp_opt_street");
  register_setting("company_information", "hawp_opt_city");
  register_setting("company_information", "hawp_opt_state");
  register_setting("company_information", "hawp_opt_zip");
  register_setting("company_information", "hawp_opt_globalcta");
  register_setting("company_information", "hawp_opt_bodyschema");
  register_setting("company_information", "hawp_opt_productontology");
  register_setting("company_information", "hawp_opt_analytics");
}
add_action("admin_init", "display_custom_info_fields");

// This adds the settings page to the WordPress admin and sets the url slug
function hawp_settings_menu(){
  add_menu_page( 'Hawp Settings', 'Hawp Settings', 'manage_options', 'hawp_global_settings', 'hawp_global_settings_page', 'http://dev.hawpmedia.com/hawpbetheme/wp-content/themes/betheme-child/images/admin-ico.jpg', '60');
}
add_action('admin_menu', 'hawp_settings_menu');

/*----------------------------------------------------------------------------
 * Google Analytics Tracking Code
 *
 * If hawp_opt_analytics ID is filled in the settings page, the Google
 * analytics code will display with the analytics ID you entered.
 * ---------------------------------------------------------------------------*/
if ( get_option('hawp_opt_analytics') ) {
    function hawp_media_google_analytics() {
    ?>
        <!-- Google Analytics Code Open -->
        <script>
        (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
        (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
        m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
        })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

        ga('create', '<?php echo get_option('hawp_opt_analytics'); ?>', 'auto');
        ga('send', 'pageview');
        </script>
        <!-- Google Analytics Code Close -->
    <?php
    }
    add_action( 'wp_head', 'hawp_media_google_analytics', 99999 );
}

/*----------------------------------------------------------------------------
 * Header Schema Div
 *
 * If hawp_opt_bodyschema is filled in the settings page, the Schema div will
 * display & if the hawp_opt_productontology is filled in the settings page,
 * the link tag will display under the schema div in the top of the_content
 * ---------------------------------------------------------------------------*/

// Displays opening schema div on the top of the_content
if ( get_option('hawp_opt_bodyschema') ) {
    function hawp_header_schema_opening_div() {
    ?>
        <!-- Body Schema Open -->
        <div id="<?php echo get_option('hawp_opt_bodyschema'); ?>" itemscope itemtype="http://schema.org/<?php echo get_option('hawp_opt_bodyschema'); ?>" itemref="<?php echo preg_replace('/\s+/', '-',get_option('hawp_opt_city')); ?>-Location">
        <?php
        if(get_option('hawp_opt_productontology')) {
          echo '<link id="more-specific" itemprop="additionalType" href="http://www.productontology.org/id/'. get_option('hawp_opt_productontology') .'">';
        }
        ?>
        <!-- Body Schema Close -->
    <?php
    }
    add_action( 'the_content', 'hawp_header_schema_opening_div', 1 );
}

// Displays closing schema div
if ( get_option('hawp_opt_bodyschema') ) {
    function hawp_header_schema_closing_div() {
    ?>
        </div><!-- Body Schema Closing Div -->
    <?php
    }
    add_action( 'the_content', 'hawp_header_schema_closing_div', 99999 );
}
</code>```

答:
There is no action on the_content. However, there is a filter on it. Change your code to:

```<code> add_filter("the_content" ,  ...) ;
</code>```

Or, hook your code into, lets say, wp_head action:

```<code> add_action("wp_head" , ....) ;
</code>```

Read the docs here.

Title: How to make a function that out puts a div inside the_content right below the opening <body> tag?

Body:
I have a plugin with a settings page and am wanting certain things inside the wordpress site to display when the fields are filled inside the settings page.

So for example, my global settings page has a google analytics ID field, when its entered, the google analytics tracking code will display right above the closing  tag using the wp_head, and that works totally fine.

My next problem is that I am trying to do this in the_content, but the div i am wanting to appear is not in the right spot, even though you can see that i set add_action( 'the_content', 'hawp_header_schema_opening_div', 1 ); with a priority of 1.

I am very new to this I just need help with what im doing wrong.

<?php
/**
 * Plugin Name: Hawp Media Developer Settings
 * Plugin URI: https://.com
 * Description: This plugin implements additional search engine optimization into the backend of the site.
 * Version: 1.0.0
 * Author: Hawp Media
 * Author URI: https://.com
 * License: GPL2
 */

/*----------------------------------------------------------------------------
 * Hawp Media Global Settings Page
 * ---------------------------------------------------------------------------*/
// The page content surrounding the settings fields
function hawp_global_settings_page(){
  ?>

Hawp Media Settings

This information is used around the website, so changing these here will update them across the website.

    <form method="post" action="options.php">
      <?php
      settings_fields("company_information");
      do_settings_sections("hawp-settings");
      submit_button();
      ?>
    </form>

  <?php
}

// Here are the settings fields to display you can use inputs, textareas, checkboxes and multi-selects
function display_hawp_opt_logo(){ ?>
  <input type="url" name="hawp_opt_logo" placeholder="Enter LOGO URL" value="<?php echo get_option('hawp_opt_logo'); ?>" size="65">
<?php }
function display_hawp_opt_branding(){ ?>
  <input type="text" name="hawp_opt_branding" placeholder="Enter BRANDING" value="<?php echo get_option('hawp_opt_branding'); ?>" size="65">
<?php }
function display_hawp_opt_phone(){ ?>
  <input type="tel" name="hawp_opt_phone" placeholder="Enter PHONE #" value="<?php echo get_option('hawp_opt_phone'); ?>" size="65">
<?php }
function display_hawp_opt_keyphrase(){ ?>
  <input type="text" name="hawp_opt_keyphrase" placeholder="Enter PRIMARY KEYPHRASE" value="<?php echo get_option('hawp_opt_keyphrase'); ?>" size="65">
<?php }
function display_hawp_opt_street(){ ?>
  <input type="text" name="hawp_opt_street" placeholder="Enter STREET ADDRESS" value="<?php echo get_option('hawp_opt_street'); ?>" size="65">
<?php }
function display_hawp_opt_city(){ ?>
  <input type="text" name="hawp_opt_city" placeholder="Enter CITY" value="<?php echo get_option('hawp_opt_city'); ?>" size="65">
<?php }
function display_hawp_opt_state(){ ?>
  <input type="text" name="hawp_opt_state" placeholder="Enter 2 digit STATE CODE" value="<?php echo get_option('hawp_opt_state'); ?>" size="65">
<?php }
function display_hawp_opt_zip(){ ?>
  <input type="text" name="hawp_opt_zip" placeholder="Enter ZIP" value="<?php echo get_option('hawp_opt_zip'); ?>" size="65">
<?php }
function display_hawp_opt_globalcta(){ ?>
  <textarea type="text" name="hawp_opt_globalcta" placeholder="Enter GLOBAL CTA (also used for social sharing message)" value="<?php echo get_option('hawp_opt_globalcta'); ?>" cols="65" rows="3"><?php echo get_option('hawp_opt_globalcta'); ?></textarea>
<?php }
function display_hawp_opt_bodyschema(){ ?>
  <input type="text" name="hawp_opt_bodyschema" placeholder="SCHEMA TYPE IE LocalBusiness" value="<?php echo get_option('hawp_opt_bodyschema'); ?>" size="65">
<?php }
function display_hawp_opt_productontology(){ ?>
  <input type="text" name="hawp_opt_productontology" placeholder="PRODUCTONTOLOGY PAGE Not Full URL" value="<?php echo get_option('hawp_opt_productontology'); ?>" size="65">
<?php }
function display_hawp_opt_analytics(){ ?>
  <input type="text" name="hawp_opt_analytics" placeholder="ANALYTICS UA CODE Not Full script" value="<?php echo get_option('hawp_opt_analytics'); ?>" size="65">
<?php }

// This tells WP what to enqueue into the <form> area. You need:  1. add_settings_section  2. add_settings_field  3. register_setting
function display_custom_info_fields(){
  add_settings_section("company_information", "Company Information", null, "hawp-settings");
  add_settings_field("hawp_opt_logo", "Company Logo URL", "display_hawp_opt_logo", "hawp-settings", "company_information");
  add_settings_field("hawp_opt_branding", "Business Name", "display_hawp_opt_branding", "hawp-settings", "company_information");
  add_settings_field("hawp_opt_phone", "Primary Phone", "display_hawp_opt_phone", "hawp-settings", "company_information");
  add_settings_field("hawp_opt_keyphrase", "Primary Keyphrase", "display_hawp_opt_keyphrase", "hawp-settings", "company_information");
  add_settings_field("hawp_opt_street", "Primary Street Address", "display_hawp_opt_street", "hawp-settings", "company_information");
  add_settings_field("hawp_opt_city", "Primary City", "display_hawp_opt_city", "hawp-settings", "company_information");
  add_settings_field("hawp_opt_state", "Primary State", "display_hawp_opt_state", "hawp-settings", "company_information");
  add_settings_field("hawp_opt_zip", "Primary Zip", "display_hawp_opt_zip", "hawp-settings", "company_information");
  add_settings_field("hawp_opt_globalcta", "Global/Share CTA", "display_hawp_opt_globalcta", "hawp-settings", "company_information");
  add_settings_field("hawp_opt_bodyschema", "Body Tag Schema", "display_hawp_opt_bodyschema", "hawp-settings", "company_information");
  add_settings_field("hawp_opt_productontology", "Productontology Page", "display_hawp_opt_productontology", "hawp-settings", "company_information");
  add_settings_field("hawp_opt_analytics", "Analytics UA Code", "display_hawp_opt_analytics", "hawp-settings", "company_information");
  register_setting("company_information", "hawp_opt_logo");
  register_setting("company_information", "hawp_opt_branding");
  register_setting("company_information", "hawp_opt_phone");
  register_setting("company_information", "hawp_opt_keyphrase");
  register_setting("company_information", "hawp_opt_street");
  register_setting("company_information", "hawp_opt_city");
  register_setting("company_information", "hawp_opt_state");
  register_setting("company_information", "hawp_opt_zip");
  register_setting("company_information", "hawp_opt_globalcta");
  register_setting("company_information", "hawp_opt_bodyschema");
  register_setting("company_information", "hawp_opt_productontology");
  register_setting("company_information", "hawp_opt_analytics");
}
add_action("admin_init", "display_custom_info_fields");

// This adds the settings page to the WordPress admin and sets the url slug
function hawp_settings_menu(){
  add_menu_page( 'Hawp Settings', 'Hawp Settings', 'manage_options', 'hawp_global_settings', 'hawp_global_settings_page', 'http://dev.hawpmedia.com/hawpbetheme/wp-content/themes/betheme-child/images/admin-ico.jpg', '60');
}
add_action('admin_menu', 'hawp_settings_menu');

/*----------------------------------------------------------------------------
 * Google Analytics Tracking Code
 *
 * If hawp_opt_analytics ID is filled in the settings page, the Google
 * analytics code will display with the analytics ID you entered.
 * ---------------------------------------------------------------------------*/
if ( get_option('hawp_opt_analytics') ) {
    function hawp_media_google_analytics() {
    ?>

    <?php
    }
    add_action( 'wp_head', 'hawp_media_google_analytics', 99999 );
}

/*----------------------------------------------------------------------------
 * Header Schema Div
 *
 * If hawp_opt_bodyschema is filled in the settings page, the Schema div will
 * display & if the hawp_opt_productontology is filled in the settings page,
 * the link tag will display under the schema div in the top of the_content
 * ---------------------------------------------------------------------------*/

// Displays opening schema div on the top of the_content
if ( get_option('hawp_opt_bodyschema') ) {
    function hawp_header_schema_opening_div() {
    ?>

        <div id="<?php echo get_option('hawp_opt_bodyschema'); ?>" itemscope itemtype="http://schema.org/<?php echo get_option('hawp_opt_bodyschema'); ?>" itemref="<?php echo preg_replace('/\s+/', '-',get_option('hawp_opt_city')); ?>-Location">
        <?php
        if(get_option('hawp_opt_productontology')) {
          echo '<link id="more-specific" itemprop="additionalType" href="http://www.productontology.org/id/'. get_option('hawp_opt_productontology') .'">';
        }
        ?>

    <?php
    }
    add_action( 'the_content', 'hawp_header_schema_opening_div', 1 );
}

// Displays closing schema div
if ( get_option('hawp_opt_bodyschema') ) {
    function hawp_header_schema_closing_div() {
    ?>

    <?php
    }
    add_action( 'the_content', 'hawp_header_schema_closing_div', 99999 );
}

Body:
There is no action on the_content. However, there is a filter on it. Change your code to:

 add_filter("the_content" ,  ...) ;

Or, hook your code into, lets say, wp_head action:

 add_action("wp_head" , ....) ;

Read the docs here.