问:
java.sql.SQLException: Unable to load class: com.mysql.jdbc.Driver
I want to be able to connect a program of mine to a database. But since I have never worked with databases before I am following a tutorial found here: https://www.javacodegeeks.com/2016/03/springboot-working-jdbctemplate.html. After following all the steps (to the best of my knowledge) of the tutorial I get the following stack trace:

```<code>java.sql.SQLException: Unable to load class: com.mysql.jdbc.Driver from ClassLoader:sun.misc.Launcher$AppClassLoader@34a245ab;ClassLoader:sun.misc.Launcher$AppClassLoader@34a245ab
at org.apache.tomcat.jdbc.pool.PooledConnection.connectUsingDriver(PooledConnection.java:283) ~[tomcat-jdbc-8.5.4.jar:na]
at org.apache.tomcat.jdbc.pool.PooledConnection.connect(PooledConnection.java:203) ~[tomcat-jdbc-8.5.4.jar:na]
at org.apache.tomcat.jdbc.pool.ConnectionPool.createConnection(ConnectionPool.java:716) [tomcat-jdbc-8.5.4.jar:na]
at org.apache.tomcat.jdbc.pool.ConnectionPool.borrowConnection(ConnectionPool.java:648) [tomcat-jdbc-8.5.4.jar:na]
at org.apache.tomcat.jdbc.pool.ConnectionPool.init(ConnectionPool.java:468) [tomcat-jdbc-8.5.4.jar:na]
at org.apache.tomcat.jdbc.pool.ConnectionPool.<init>(ConnectionPool.java:143) [tomcat-jdbc-8.5.4.jar:na]
at org.apache.tomcat.jdbc.pool.DataSourceProxy.pCreatePool(DataSourceProxy.java:118) [tomcat-jdbc-8.5.4.jar:na]
at org.apache.tomcat.jdbc.pool.DataSourceProxy.createPool(DataSourceProxy.java:107) [tomcat-jdbc-8.5.4.jar:na]
at org.apache.tomcat.jdbc.pool.DataSourceProxy.getConnection(DataSourceProxy.java:131) [tomcat-jdbc-8.5.4.jar:na]
at org.springframework.jdbc.datasource.DataSourceUtils.doGetConnection(DataSourceUtils.java:111) [spring-jdbc-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:77) [spring-jdbc-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.jdbc.datasource.init.DatabasePopulatorUtils.execute(DatabasePopulatorUtils.java:46) [spring-jdbc-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.boot.autoconfigure.jdbc.DataSourceInitializer.runScripts(DataSourceInitializer.java:176) [spring-boot-autoconfigure-1.4.0.RELEASE.jar:1.4.0.RELEASE]
at org.springframework.boot.autoconfigure.jdbc.DataSourceInitializer.runSchemaScripts(DataSourceInitializer.java:85) [spring-boot-autoconfigure-1.4.0.RELEASE.jar:1.4.0.RELEASE]
at org.springframework.boot.autoconfigure.jdbc.DataSourceInitializer.init(DataSourceInitializer.java:77) [spring-boot-autoconfigure-1.4.0.RELEASE.jar:1.4.0.RELEASE]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_92]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_92]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_92]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_92]
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleElement.invoke(InitDestroyAnnotationBeanPostProcessor.java:365) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleMetadata.invokeInitMethods(InitDestroyAnnotationBeanPostProcessor.java:310) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:133) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:408) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1570) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:220) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:353) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:334) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.boot.autoconfigure.jdbc.DataSourceInitializerPostProcessor.postProcessAfterInitialization(DataSourceInitializerPostProcessor.java:62) [spring-boot-autoconfigure-1.4.0.RELEASE.jar:1.4.0.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization(AbstractAutowireCapableBeanFactory.java:422) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1583) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:207) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1214) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1054) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1019) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:835) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:741) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:189) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1143) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1046) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:372) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1123) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1018) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1076) [spring-context-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:851) [spring-context-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:541) [spring-context-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) [spring-boot-1.4.0.RELEASE.jar:1.4.0.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:759) [spring-boot-1.4.0.RELEASE.jar:1.4.0.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:369) [spring-boot-1.4.0.RELEASE.jar:1.4.0.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:313) [spring-boot-1.4.0.RELEASE.jar:1.4.0.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1185) [spring-boot-1.4.0.RELEASE.jar:1.4.0.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1174) [spring-boot-1.4.0.RELEASE.jar:1.4.0.RELEASE]
at edu.demo.SpringbootJdbcDemoApplication.main(SpringbootJdbcDemoApplication.java:9) [classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_92]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_92]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_92]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_92]
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147) [idea_rt.jar:na]
</code>```

Is anyone familiar with this type of error? It's probably something pretty simple. The IDE I am using is IntelliJ. I have put my code below:

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>edu.demo</groupId>
    <artifactId>SpringbootJdbcDemoApplication</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

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

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.0.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.8</java.version>
    </properties>

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

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

        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
        </dependency>

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

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

SpringbootJdbcDemoApplication.java

```<code>package edu.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringbootJdbcDemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringbootJdbcDemoApplication.class, args);
    }
}
</code>```

User.java

```<code>    package edu.demo;

    public class User{
        private Integer id;
        private String name;
        private String email;

    public User(int number, String strName, String strEmail){
        id = number;
        name = strName;
        email = strEmail;
    }

    public User(){

    }
    public Integer getId() {
        return id;
    }

    public String getEmail() {
        return email;
    }

    public String getName() {
        return name;
    }

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

    public void setEmail(String email) {
        this.email = email;
    }

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

SpringbootJdbcDemoApplicationTests.java

```<code>package edu.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;

import org.junit.*;

@org.junit.runner.RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(SpringbootJdbcDemoApplication.class)
public class SpringbootJdbcDemoApplicationTests {
        @Autowired
        private UserRepository userRepository;

        @org.junit.Test
        public void findAllUsers() {
                List<User> users = userRepository.findAll();
                Assert.assertNotNull(users);
                Assert.assertTrue(!users.isEmpty());
        }

        @Test
        public void findUserById() {
                User user = userRepository.findUserById(1);
                Assert.assertNotNull(user);
        }

        @Test
        public void createUser() {
                User user = new User(0, "John", "john@gmail.com");
                User savedUser = userRepository.create(user);
                User newUser = userRepository.findUserById(savedUser.getId());
                Assert.assertNotNull(newUser);
                Assert.assertEquals("John", newUser.getName());
                Assert.assertEquals("john@gmail.com", newUser.getEmail());
        }
}
</code>```

UserRepository.java

```<code>package edu.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;

import org.junit.*;

@org.junit.runner.RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(SpringbootJdbcDemoApplication.class)
public class SpringbootJdbcDemoApplicationTests {
        @Autowired
        private UserRepository userRepository;

        @org.junit.Test
        public void findAllUsers() {
                List<User> users = userRepository.findAll();
                Assert.assertNotNull(users);
                Assert.assertTrue(!users.isEmpty());
        }

        @Test
        public void findUserById() {
                User user = userRepository.findUserById(1);
                Assert.assertNotNull(user);
        }

        @Test
        public void createUser() {
                User user = new User(0, "John", "john@gmail.com");
                User savedUser = userRepository.create(user);
                User newUser = userRepository.findUserById(savedUser.getId());
                Assert.assertNotNull(newUser);
                Assert.assertEquals("John", newUser.getName());
                Assert.assertEquals("john@gmail.com", newUser.getEmail());
        }
}
</code>```

答:
For folks who are building a datasource manually, besides loading the mysql-connector-dependency, ensure that the driver class name is set correctly.

```<code>DataSourceFactory factory = new DataSourceFactory();
factory.setUrl("..");
factory.setUser("..");
factory.setDriverClass("com.mysql.jdbc.Driver"); //Important
...
DBI dbi = new DBI(factory.build(new MetricRegistry(), "mysql"));
</code>```

Otherwise, DataSourceFactory.driverClass instance field gets set to "". When the application class loader tries to load a class with a name of "", it will throw a ClassNotFoundException

Body:
I want to be able to connect a program of mine to a database. But since I have never worked with databases before I am following a tutorial found here: https://www.javacodegeeks.com/2016/03/springboot-working-jdbctemplate.html. After following all the steps (to the best of my knowledge) of the tutorial I get the following stack trace:

java.sql.SQLException: Unable to load class: com.mysql.jdbc.Driver from ClassLoader:sun.misc.Launcher$AppClassLoader@34a245ab;ClassLoader:sun.misc.Launcher$AppClassLoader@34a245ab
at org.apache.tomcat.jdbc.pool.PooledConnection.connectUsingDriver(PooledConnection.java:283) ~[tomcat-jdbc-8.5.4.jar:na]
at org.apache.tomcat.jdbc.pool.PooledConnection.connect(PooledConnection.java:203) ~[tomcat-jdbc-8.5.4.jar:na]
at org.apache.tomcat.jdbc.pool.ConnectionPool.createConnection(ConnectionPool.java:716) [tomcat-jdbc-8.5.4.jar:na]
at org.apache.tomcat.jdbc.pool.ConnectionPool.borrowConnection(ConnectionPool.java:648) [tomcat-jdbc-8.5.4.jar:na]
at org.apache.tomcat.jdbc.pool.ConnectionPool.init(ConnectionPool.java:468) [tomcat-jdbc-8.5.4.jar:na]
at org.apache.tomcat.jdbc.pool.ConnectionPool.<init>(ConnectionPool.java:143) [tomcat-jdbc-8.5.4.jar:na]
at org.apache.tomcat.jdbc.pool.DataSourceProxy.pCreatePool(DataSourceProxy.java:118) [tomcat-jdbc-8.5.4.jar:na]
at org.apache.tomcat.jdbc.pool.DataSourceProxy.createPool(DataSourceProxy.java:107) [tomcat-jdbc-8.5.4.jar:na]
at org.apache.tomcat.jdbc.pool.DataSourceProxy.getConnection(DataSourceProxy.java:131) [tomcat-jdbc-8.5.4.jar:na]
at org.springframework.jdbc.datasource.DataSourceUtils.doGetConnection(DataSourceUtils.java:111) [spring-jdbc-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:77) [spring-jdbc-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.jdbc.datasource.init.DatabasePopulatorUtils.execute(DatabasePopulatorUtils.java:46) [spring-jdbc-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.boot.autoconfigure.jdbc.DataSourceInitializer.runScripts(DataSourceInitializer.java:176) [spring-boot-autoconfigure-1.4.0.RELEASE.jar:1.4.0.RELEASE]
at org.springframework.boot.autoconfigure.jdbc.DataSourceInitializer.runSchemaScripts(DataSourceInitializer.java:85) [spring-boot-autoconfigure-1.4.0.RELEASE.jar:1.4.0.RELEASE]
at org.springframework.boot.autoconfigure.jdbc.DataSourceInitializer.init(DataSourceInitializer.java:77) [spring-boot-autoconfigure-1.4.0.RELEASE.jar:1.4.0.RELEASE]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_92]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_92]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_92]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_92]
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleElement.invoke(InitDestroyAnnotationBeanPostProcessor.java:365) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleMetadata.invokeInitMethods(InitDestroyAnnotationBeanPostProcessor.java:310) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:133) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:408) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1570) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:220) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:353) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:334) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.boot.autoconfigure.jdbc.DataSourceInitializerPostProcessor.postProcessAfterInitialization(DataSourceInitializerPostProcessor.java:62) [spring-boot-autoconfigure-1.4.0.RELEASE.jar:1.4.0.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization(AbstractAutowireCapableBeanFactory.java:422) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1583) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:207) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1214) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1054) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1019) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:835) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:741) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:189) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1143) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1046) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:372) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1123) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1018) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) [spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1076) [spring-context-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:851) [spring-context-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:541) [spring-context-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) [spring-boot-1.4.0.RELEASE.jar:1.4.0.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:759) [spring-boot-1.4.0.RELEASE.jar:1.4.0.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:369) [spring-boot-1.4.0.RELEASE.jar:1.4.0.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:313) [spring-boot-1.4.0.RELEASE.jar:1.4.0.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1185) [spring-boot-1.4.0.RELEASE.jar:1.4.0.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1174) [spring-boot-1.4.0.RELEASE.jar:1.4.0.RELEASE]
at edu.demo.SpringbootJdbcDemoApplication.main(SpringbootJdbcDemoApplication.java:9) [classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_92]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_92]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_92]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_92]
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147) [idea_rt.jar:na]

Is anyone familiar with this type of error? It's probably something pretty simple. The IDE I am using is IntelliJ. I have put my code below:

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>edu.demo</groupId>
    <artifactId>SpringbootJdbcDemoApplication</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

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

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

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

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

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

        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
        </dependency>

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

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

SpringbootJdbcDemoApplication.java

package edu.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringbootJdbcDemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringbootJdbcDemoApplication.class, args);
    }
}

User.java

    package edu.demo;

    public class User{
        private Integer id;
        private String name;
        private String email;

    public User(int number, String strName, String strEmail){
        id = number;
        name = strName;
        email = strEmail;
    }

    public User(){

    }
    public Integer getId() {
        return id;
    }

    public String getEmail() {
        return email;
    }

    public String getName() {
        return name;
    }

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

    public void setEmail(String email) {
        this.email = email;
    }

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

SpringbootJdbcDemoApplicationTests.java

package edu.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;

import org.junit.*;

@org.junit.runner.RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(SpringbootJdbcDemoApplication.class)
public class SpringbootJdbcDemoApplicationTests {
        @Autowired
        private UserRepository userRepository;

        @org.junit.Test
        public void findAllUsers() {
                List<User> users = userRepository.findAll();
                Assert.assertNotNull(users);
                Assert.assertTrue(!users.isEmpty());
        }

        @Test
        public void findUserById() {
                User user = userRepository.findUserById(1);
                Assert.assertNotNull(user);
        }

        @Test
        public void createUser() {
                User user = new User(0, "John", "john@gmail.com");
                User savedUser = userRepository.create(user);
                User newUser = userRepository.findUserById(savedUser.getId());
                Assert.assertNotNull(newUser);
                Assert.assertEquals("John", newUser.getName());
                Assert.assertEquals("john@gmail.com", newUser.getEmail());
        }
}

UserRepository.java

package edu.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;

import org.junit.*;

@org.junit.runner.RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(SpringbootJdbcDemoApplication.class)
public class SpringbootJdbcDemoApplicationTests {
        @Autowired
        private UserRepository userRepository;

        @org.junit.Test
        public void findAllUsers() {
                List<User> users = userRepository.findAll();
                Assert.assertNotNull(users);
                Assert.assertTrue(!users.isEmpty());
        }

        @Test
        public void findUserById() {
                User user = userRepository.findUserById(1);
                Assert.assertNotNull(user);
        }

        @Test
        public void createUser() {
                User user = new User(0, "John", "john@gmail.com");
                User savedUser = userRepository.create(user);
                User newUser = userRepository.findUserById(savedUser.getId());
                Assert.assertNotNull(newUser);
                Assert.assertEquals("John", newUser.getName());
                Assert.assertEquals("john@gmail.com", newUser.getEmail());
        }
}

Body:
For folks who are building a datasource manually, besides loading the mysql-connector-dependency, ensure that the driver class name is set correctly.

DataSourceFactory factory = new DataSourceFactory();
factory.setUrl("..");
factory.setUser("..");
factory.setDriverClass("com.mysql.jdbc.Driver"); //Important
...
DBI dbi = new DBI(factory.build(new MetricRegistry(), "mysql"));

Otherwise, DataSourceFactory.driverClass instance field gets set to "". When the application class loader tries to load a class with a name of "", it will throw a ClassNotFoundException


来源: stackexchange

问:
Git PullRequest job failed. Couldn't find any revision to build. Verify the repository and branch configuration for this job
Yesterday my pullrequest jobs failed with the following output:

```<code>11:07:41  > git rev-parse origin/${sha1}^{commit}
11:07:41  > git rev-parse ${sha1}^{commit}
11:07:41 ERROR: Couldn't find any revision to build. Verify the repository and branch configuration for this job.
</code>```

I have made an investigation and saw that in property ${sha1} there was nothing. When i paste an absolute path to pull request builder like pr/341/merge  instead of ${sha1} the build works. What it can be?

Git Client Plugin
1.9.0

GitHub API Plugin
1.44

答:
Whenever we don't specify a correct branch to pull, the git will look for all the branches that repository has and end up throwing an error saying "Couldn't find any revision to build. Verify the repository and branch configuration for this job."

I had faced the same issue with my git pull and i was using jenkins to specify the configuration.

If we leave it to blank, it would get the files from master branch, but if something is wrong or a typo is there, it would look for all branches and throw error saying branch not found.

ContentLicense: CC BY-SA 3.0

Body:
Yesterday my pullrequest jobs failed with the following output:

11:07:41  > git rev-parse origin/${sha1}^{commit}
11:07:41  > git rev-parse ${sha1}^{commit}
11:07:41 ERROR: Couldn't find any revision to build. Verify the repository and branch configuration for this job.

I have made an investigation and saw that in property ${sha1} there was nothing. When i paste an absolute path to pull request builder like pr/341/merge  instead of ${sha1} the build works. What it can be?

Git Client Plugin
1.9.0

GitHub API Plugin
1.44

ContentLicense: CC BY-SA 4.0


问:
How to delete all keys from redis cluster
I want to delete all keys from redis cluster by using fast process. I know how to delete the keys by using "redis-cli FLUSHALL". But this command can be slow when the data set is large. I heard that all keys can be cleared from redis cache by re-starting the redis service. I am testing this process on my local mac laptop. I am performing following steps:-

Setting many number of keys on my local redis server by using example command redis-cli SET mykey1 "Hello"

Then Re-starting the redis service "brew services restart redis" in the hope that all keys will be deleted when the service will be back up

Then getting the keys by giving "redis-cli KEYS '*'" command

I still see the keys after step-3

The keys are gone only when I give this command--> redis-cli FLUSHALL? How I can clear the keys by re-starting the redis service locally on my mac laptop first then I will try on QA servers?

答:
You see the keys after restart because there is either RDB or AOF persistence enabled. See https://redis.io/topics/persistence.

RDB is enabled by default. To disable persistence, you need to edit your redis.conf or start as redis-server --save "" --appendonly no

See Is there a way to flushall on a cluster so all keys from master and slaves are deleted from the db on how to use redis-cli to send the command to all cluster nodes.

As dizzyf indicates, use FLUSHALL ASYNC to have the deletion performed in the background. This will create fresh hash maps for each database, while the old ones are deleted (memory reclaimed) progressively by a background thread.


问:
why the following code does not return match object?
```<code>txt = 'is worth 12$'
pattern = re.compile('12$')
match = pattern.search(txt)
if match != None:
    print('ys')
else:
    print('no')
</code>```

It prints no. I want to know why the string '12$' is not being matched.

答:
If you want to use any of these characters as a literal in a regex,
  you need to escape them with a backslash. If you want to match 1+1=2,
  the correct regex is 1+1=2. Otherwise, the plus sign has a special
  meaning.

It should be:

```<code>pattern=re.compile('12\$')
</code>```

Body:
txt = 'is worth 12$'
pattern = re.compile('12$')
match = pattern.search(txt)
if match != None:
    print('ys')
else:
    print('no')

It prints no. I want to know why the string '12$' is not being matched.

Body:
If you want to use any of these characters as a literal in a regex,
  you need to escape them with a backslash. If you want to match 1+1=2,
  the correct regex is 1+1=2. Otherwise, the plus sign has a special
  meaning.

It should be:

pattern=re.compile('12\$')


问:
Errors in Access 2003 front end after switching DSN to sqlncli10
I have an Access 2003 front end linked (DSN) to a SQL 2008 back end. I had originally developed it using the older sqlsvr32 DSN driver, but were having performance issues. A new DSN was created to use the sqlncli10 (Server 2008r2 version) driver and the tables relinked. This increased performance, but now causes what looks like timeout errors at unpredicable intervals in the front end with everything from ADO recordset queries to simple dropdown box populations. The only thing which has changed is the driver, and I can't determine the cause of these timeouts. Any suggestions?</p>

答: The DSN was created using the OBDC manager (odbcad32.exe) using the Sql Server Native Client 10.0 (2009.100.1600.01). Tables were dropped and re-linked from the database (SQL Server 2008). This did not resolve the issue. Custom functions were re-written to use ADO, and tables were converted to a DSN-less connection with the same driver. Neither had an apparent effect on the issue. The issue was resolved after targeting different servers for testing to see if the server was the problem. Any server with 2008 R2 did not show any symptoms on this issue. The issue was resolved by uninstalling all SQL server instances, installing 2008 R2, and restoring the databases. I'm not sure of the exact cause, but this seems to fix the issue.</p>


问:
Finding row positions through datetime index in pandas dataframe
I have a dataframe that has a DateTimeIndex and an X 2d numpy array which is just the values of that dataframe. I want to select some rows through the index of the dataframe

```<code>dataset[from_d:to_d]
</code>```

Where from_d and to_d are Timestamps. The dataset is sliced just fine but I need to get the positions of those rows inside the dataset. I need them because then I want to select the same rows in the X numpy array. Something like

```<code>X[indexes]
</code>```

I have tried np.where(dataset[from_d:to_d])[0] but it gives me somehow a (23149590,) array when the dataset is of shape: (15075, 13117). Is there a better way to do this than with where?.

Body:
I have a dataframe that has a DateTimeIndex and an X 2d numpy array which is just the values of that dataframe. I want to select some rows through the index of the dataframe

dataset[from_d:to_d]

Where from_d and to_d are Timestamps. The dataset is sliced just fine but I need to get the positions of those rows inside the dataset. I need them because then I want to select the same rows in the X numpy array. Something like

X[indexes]

I have tried np.where(dataset[from_d:to_d])[0] but it gives me somehow a (23149590,) array when the dataset is of shape: (15075, 13117). Is there a better way to do this than with where?.

Body:
Use Index.get_indexer:

rng = pd.date_range('2017-04-03', periods=10)
dataset = pd.DataFrame({'a': range(10)}, index=rng)
print (dataset)
            a
2017-04-03  0
2017-04-04  1
2017-04-05  2
2017-04-06  3
2017-04-07  4
2017-04-08  5
2017-04-09  6
2017-04-10  7
2017-04-11  8
2017-04-12  9

from_d = '2017-04-05'
to_d = '2017-04-10'
print (dataset[from_d:to_d])
            a
2017-04-05  2
2017-04-06  3
2017-04-07  4
2017-04-08  5
2017-04-09  6
2017-04-10  7

indexes = dataset.index.get_indexer(dataset[from_d:to_d].index)
print (indexes)
[2 3 4 5 6 7]

Or Index.searchsorted:

indexes = dataset.index.searchsorted(dataset[from_d:to_d].index)
print (indexes)
[2 3 4 5 6 7]

EDIT:

For not unique DatetimeIndex is it possible with unique index and Index.get_indexer_for:

rng = pd.date_range('2017-04-03', periods=10)
dataset = pd.DataFrame({'a': range(20)}, index=rng.append(rng)).sort_index()
print (dataset)
             a
2017-04-03   0
2017-04-03  10
2017-04-04   1
2017-04-04  11
2017-04-05   2
2017-04-05  12
2017-04-06   3
2017-04-06  13
2017-04-07   4
2017-04-07  14
2017-04-08   5
2017-04-08  15
2017-04-09   6
2017-04-09  16
2017-04-10  17
2017-04-10   7
2017-04-11  18
2017-04-11   8
2017-04-12   9
2017-04-12  19

from_d = '2017-04-05'
to_d = '2017-04-10'

i = dataset[from_d:to_d].index.unique()
print (i)
DatetimeIndex(['2017-04-05', '2017-04-06', '2017-04-07', '2017-04-08',
               '2017-04-09', '2017-04-10'],
              dtype='datetime64[ns]', freq=None)

indexes = dataset.index.get_indexer_for(i)
print (indexes)
[ 4  5  6  7  8  9 10 11 12 13 14 15]

Verify indexes:

print (dataset.iloc[indexes])
             a
2017-04-05   2
2017-04-05  12
2017-04-06   3
2017-04-06  13
2017-04-07   4
2017-04-07  14
2017-04-08   5
2017-04-08  15
2017-04-09   6
2017-04-09  16
2017-04-10  17
2017-04-10   7


问:
Why is Postgres transaction block so much slower? And how to solve?
Hoping someone with deeper postgres/database knowledge can share some insight.

Background:

I have a postgres v11 database running with some data. Now there is about 200k operations that I want to run on it as a single transaction (they should either all succeed or no changes made). The transactions include a mix of INSERT and UPDATE statements that also involve some triggers in the database.

If I run the query in a transaction then it takes about 70 minutes

```<code>BEGIN;
// statement
// statement
// statement
// ...
COMMIT;
</code>```

If I remove the surrounding transaction block and simply run the queries then it will take 7 minutes.

```<code>// statement
// statement
// statement
// ...
</code>```

Now I suspect the performance difference is related to transaction keeping some temporary tables which run into buffer size or indexing issues resulting in the slowdown, but since I don't have deep understanding of Postgres internals I don't actually know. I have tried changing various WAL settings, but without any significant difference.

So I have 2 questions:

Why is the transaction so much slower?

How can I run the batch of operations with the possibility of rollback without sacrificing performance to this degree?

EDIT 1

Extra information about tables and queries

I will try to give as much information as I can without revealing specifics (which I am not allowed).

There are 5 main tables related to this transaction - accounts, currencies, transactions, transaction_logs, balance.

transactions table has 3 foreign keys - 2 to accounts and 1 to currencies.

balances table has 2 foreign keys - 1 to accounts and 1 to currencies.

transaction_logs table has 3 foreign keys - 1 to transactions, 1 to accounts, 1 to currencies.

The transaction batch starts by inserting all relevant accounts and currencies. (about 10k accounts and 2 currencies)

Next it is a mix of inserts and updates of the transactions table - inserts are in groups up to 300 rows in a single insert, while updates are based on PK so only 1 row at a time. In total there are about 140k inserts and 60k updates.

Both inserts and updates in turn execute triggers which update the balances table and insert 2 rows into transaction_log table.

A typical insert looks like

INSERT INTO transactions (from_account_id, to_account_id, currency_id, amount, metadata, status) VALUES (1, 1, 1, 10.00, '{"json":"blob"}', 'pending');

A typical update looks like

UPDATE transactions SET status = 'finished' WHERE id = 1;

The programming environment is node.js and driver is pg.

EDIT 2

Apologies to everyone for the delay in providing more information - I was trying to create a closed test environment reproducing the error. And while doing this I managed to get closer to the crux of the problem. The structure itself seems irrelevant. The slowdown is caused by updating the same row over and over again within the same transaction.

The simplest reproduction I managed was creating a table with 2 fields, adding a few rows and then repeatedly updating the first row. Without a transaction the operation time stays relatively constant. Within a transaction however it starts climbing - at around 100k updates it is around 3 times higher than in the beginning. On my machine the total runtime difference for 100k updates test was 2.5x between a transaction and non-transaction version.

If however your data is more varied - not updating the same row, but different rows, then the problem does not occur and with a nicely distributed data the transaction is actually faster.

PS. Tested this with v12 as well and performs roughly the same.

Does anyone have any ideas why this is happening?

EDIT 3

I have created a repository to demonstrate this issue https://github.com/DeadAlready/pg-test

答:
I took the question to postgres official mailinglist and this is the answer I got, which I will share here for future searchers.

TL;DR;

updating a single row multiple times inside a transaction is slow

this is expected

avoid doing that

Link to the thread:

https://www.postgresql.org/message-id/flat/7624.1581628574%40sss.pgh.pa.us

Full answer:

Yeah, that's unsurprising.  Each new update creates a new version of
  its row.  When you do them in separate transactions, then as soon as
  transaction N+1 commits the system can recognize that the row version
  created by transaction N is dead (no longer visible to anybody) and
  recycle it, allowing the number of row versions present on-disk to
  stay more or less constant.  However, there's not equivalently good
  housekeeping for row versions created by a transaction that's still
  running.  So when you do N updates in one transaction, there are going
  to be N doomed-but-not-yet-recyclable row versions on disk.

Aside from the disk-space bloat, this is bad because the later updates
  have to scan through all the row versions created by earlier updates,
  looking for the version they're supposed to update.  So you have an O(N^2)
  cost associated with that, which no doubt is what you're observing.

There isn't any really good fix for this, other than "don't do that".
  David's nearby suggestion of using a temp table won't help, because
  this behavior is the same whether the table is temp or regular.

In principle perhaps we could improve the granularity of dead-row
  detection, so that if a row version is both created and deleted by
  the current transaction, and we have no live snapshots that could
  see it, we could go ahead and mark the row dead.  But it's not clear
  that that'd be worth the extra cost to do.  Certainly no existing PG
  release tries to do it.

regards, tom lane

Body:
Hoping someone with deeper postgres/database knowledge can share some insight.

Background:

I have a postgres v11 database running with some data. Now there is about 200k operations that I want to run on it as a single transaction (they should either all succeed or no changes made). The transactions include a mix of INSERT and UPDATE statements that also involve some triggers in the database.

If I run the query in a transaction then it takes about 70 minutes

BEGIN;
// statement
// statement
// statement
// ...
COMMIT;

If I remove the surrounding transaction block and simply run the queries then it will take 7 minutes.

// statement
// statement
// statement
// ...

Now I suspect the performance difference is related to transaction keeping some temporary tables which run into buffer size or indexing issues resulting in the slowdown, but since I don't have deep understanding of Postgres internals I don't actually know. I have tried changing various WAL settings, but without any significant difference.

So I have 2 questions:

Why is the transaction so much slower?

How can I run the batch of operations with the possibility of rollback without sacrificing performance to this degree?

EDIT 1

Extra information about tables and queries

I will try to give as much information as I can without revealing specifics (which I am not allowed).

There are 5 main tables related to this transaction - accounts, currencies, transactions, transaction_logs, balance.

transactions table has 3 foreign keys - 2 to accounts and 1 to currencies.

balances table has 2 foreign keys - 1 to accounts and 1 to currencies.

transaction_logs table has 3 foreign keys - 1 to transactions, 1 to accounts, 1 to currencies.

The transaction batch starts by inserting all relevant accounts and currencies. (about 10k accounts and 2 currencies)

Next it is a mix of inserts and updates of the transactions table - inserts are in groups up to 300 rows in a single insert, while updates are based on PK so only 1 row at a time. In total there are about 140k inserts and 60k updates.

Both inserts and updates in turn execute triggers which update the balances table and insert 2 rows into transaction_log table.

A typical insert looks like

INSERT INTO transactions (from_account_id, to_account_id, currency_id, amount, metadata, status) VALUES (1, 1, 1, 10.00, '{"json":"blob"}', 'pending');

A typical update looks like

UPDATE transactions SET status = 'finished' WHERE id = 1;

The programming environment is node.js and driver is pg.

EDIT 2

Apologies to everyone for the delay in providing more information - I was trying to create a closed test environment reproducing the error. And while doing this I managed to get closer to the crux of the problem. The structure itself seems irrelevant. The slowdown is caused by updating the same row over and over again within the same transaction.

The simplest reproduction I managed was creating a table with 2 fields, adding a few rows and then repeatedly updating the first row. Without a transaction the operation time stays relatively constant. Within a transaction however it starts climbing - at around 100k updates it is around 3 times higher than in the beginning. On my machine the total runtime difference for 100k updates test was 2.5x between a transaction and non-transaction version.

If however your data is more varied - not updating the same row, but different rows, then the problem does not occur and with a nicely distributed data the transaction is actually faster.

PS. Tested this with v12 as well and performs roughly the same.

Does anyone have any ideas why this is happening?

EDIT 3

I have created a repository to demonstrate this issue https://github.com/DeadAlready/pg-test


问:
Flutter - How to get Rounded border when scrolling listview?
I'm having listview with chips in bottom of the Column.

In first image from starting in listview its in circular shape but in the end its shows as rectangle.

When scrolling the listview Chip 1 day is overflow.(Second Image).

I want both side bottom need to circular, How to achieve? Thanks in Advance.

My Code

```<code>Container(
                padding: EdgeInsets.only(
                  top: 16.0,
                ),
                width: MediaQuery.of(context).size.width,
                height: 100,
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(12.0),
                    color: Colors.white),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Text(""),
                    Container(
                      height: 35,
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.only(
                              bottomLeft: Radius.circular(12.0),
                              bottomRight: Radius.circular(12.0)),
                          color:
                              Theme.of(context).chipTheme.backgroundColor),
                      child: ListView(
                        scrollDirection: Axis.horizontal,
                        children: getChoiceChips(),
                      ),
                    )
                  ],
                ),
              )
</code>```

Chip Function

```<code>getChoiceChips() {
List<Widget> choiceChipList = [];
List<String> choiceString = [
  '1 Day',
  '1 Week',
  '1 Month',
  '3 Months',
  '1 Year'
];
for (String choice in choiceString) {
  choiceChipList.add(Padding(
    padding: const EdgeInsets.only(left: 2.0, right: 2.0),
    child: ChoiceChip(
      label: Text(choice),
      selected: choice == selectedChoice,
      onSelected: (newSelectedChoice) {
        setState(() {
          print(selectedChoice);
          print(newSelectedChoice);
          selectedChoice = choice;

          print(selectedChoice);
          print(choice);
        });
      },
    ),
  ));
}
return choiceChipList;
}
</code>```

答:
The BoxDecoration in the Container will only show the rounded corners as a visual feature. If you want to actually clip the contents to within those rounded corners with no overflow, you want to surround the container in a ClipRRect.

ClipRRect(
  borderRadius: BorderRadius.circular(12.0),
  child: Container(
    padding: EdgeInsets.only(top: 16.0),
    width: MediaQuery.of(context).size.width,
    height: 100,
    decoration: BoxDecoration(color: Colors.white),
    child: Column(
      ...
    ),
  ),
),
```

Body:
I'm having listview with chips in bottom of the Column.

In first image from starting in listview its in circular shape but in the end its shows as rectangle.

When scrolling the listview Chip 1 day is overflow.(Second Image).

I want both side bottom need to circular, How to achieve? Thanks in Advance.

My Code

Container(
                padding: EdgeInsets.only(
                  top: 16.0,
                ),
                width: MediaQuery.of(context).size.width,
                height: 100,
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(12.0),
                    color: Colors.white),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Text(""),
                    Container(
                      height: 35,
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.only(
                              bottomLeft: Radius.circular(12.0),
                              bottomRight: Radius.circular(12.0)),
                          color:
                              Theme.of(context).chipTheme.backgroundColor),
                      child: ListView(
                        scrollDirection: Axis.horizontal,
                        children: getChoiceChips(),
                      ),
                    )
                  ],
                ),
              )

Chip Function

getChoiceChips() {
List<Widget> choiceChipList = [];
List<String> choiceString = [
  '1 Day',
  '1 Week',
  '1 Month',
  '3 Months',
  '1 Year'
];
for (String choice in choiceString) {
  choiceChipList.add(Padding(
    padding: const EdgeInsets.only(left: 2.0, right: 2.0),
    child: ChoiceChip(
      label: Text(choice),
      selected: choice == selectedChoice,
      onSelected: (newSelectedChoice) {
        setState(() {
          print(selectedChoice);
          print(newSelectedChoice);
          selectedChoice = choice;

          print(selectedChoice);
          print(choice);
        });
      },
    ),
  ));
}
return choiceChipList;
}


答:
With plain Javascript, you could take cartesian product with a double nested reduce by mapping new objects.

This approach works for an arbirary count of arrays (sort of ...).

const
    l1 = [{ a: 1, a1: 2 }, { b: 3, b1: 4 }, { c: 5, c1: 6 }],
    l2 = [{ d: 2 }, { e: 2 }, { f: 2 }],
    result = [l1, l2].reduce((a, b) => a.reduce((r, v) => r.concat(b.map(w => ({ ...v, ...w }))), []));

console.log(result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Title: How to combine two array using ramda library?

Body:
I have two array as below

const l1 = [ {"a": 1, "a1": 2}, {"b": 3, "b1": 4}, {"c": 5, "c1": 6} ];
const l2 = [ {"d": 2}, {"e": 2}, {"f": 2} ];

How can I use ramda library to combine these two and get result like

[ {"a": 1, "a1": 2, "d": 2}, {"a": 1, "a1": 2, "e": 2}, {"a": 1, "a1": 2, "f": 2},
{"b": 3, "b1": 4, "d": 2}, {"b": 3, "b1": 4, "e": 2}, {"b": 3, "b1": 4, "f": 2},
{"c": 5, "c1": 6, "d": 2}, {"c": 5, "c1": 6, "e": 2}, {"c": 5, "c1": 6, "f": 2} ]

I used

R.map(R.xprod(__, l2, l1)

But not working since i got object inside array.

Thanks in advance.

Body:
With plain Javascript, you could take cartesian product with a double nested reduce by mapping new objects.

This approach works for an arbirary count of arrays (sort of ...).

const
    l1 = [{ a: 1, a1: 2 }, { b: 3, b1: 4 }, { c: 5, c1: 6 }],
    l2 = [{ d: 2 }, { e: 2 }, { f: 2 }],
    result = [l1, l2].reduce((a, b) => a.reduce((r, v) => r.concat(b.map(w => ({ ...v, ...w }))), []));

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
How to pass the props when set ref for a component
```<code>this.map[col1][row1] = <MemoizedItem key={item} x={row1} y={col1} />
this.setState({ map: this.map })
</code>```

This is my code, I'm put all the item in param map. and render by using:

```<code>renderItem() {

  return this.state.map.map((row) => {
    return row.map((item) => {
      return item;
    })
  })
}
</code>```

Now, i'm trying to pass the props color in the item by this.state.map[0][0].props.color ='#fff' but not working, get an error 'Cannot add property color, object is not extensible', so is there any way to do that?

答:
you should not store components in component state
You can just store the data in state like

```<code>let data = [{id:'row1', cols:[{id:'col1'}, {id:'col2'}]} , {...}, ...]
this.setState({
  map: data
})

</code>```

and render it using your memoized component

```<code>renderItem() {

  return this.state.map.map((row, rowIndex) => {
    return row.cols.map((item,index) => {
//you can pass whatever you want to pass to the component
      return <MemoizedComponent key={rowIndex+index} x={item} y={row} yourprops={condition ? color1: color2} />
    })
  })
}

</code>```

finally you can update data by setting state like

```<code>
  let final = this.state.data.map(r => {
    if (r === 'your condition') {
      return Object.assign({}, r, {
        cols: r.cols.map(c => {
          if (c === 'your col condition') {
            return Object.assign({}, c, {
              changedProp: 'changedPropvalue',
            });
          } else {
            return c;
          }
        }),
      });
    }else{
      return r
    }
  });

...

this.setState({data:final})
</code>```

so when the state updates the component rerendered

also make sure you use PureComponent as it will restrict rerenders to only changed items

Body:
this.map[col1][row1] = <MemoizedItem key={item} x={row1} y={col1} />
this.setState({ map: this.map })

This is my code, I'm put all the item in param map. and render by using:

renderItem() {

  return this.state.map.map((row) => {
    return row.map((item) => {
      return item;
    })
  })
}

Now, i'm trying to pass the props color in the item by this.state.map[0][0].props.color ='#fff' but not working, get an error 'Cannot add property color, object is not extensible', so is there any way to do that?

Body:
you should not store components in component state
You can just store the data in state like

let data = [{id:'row1', cols:[{id:'col1'}, {id:'col2'}]} , {...}, ...]
this.setState({
  map: data
})

and render it using your memoized component

renderItem() {

  return this.state.map.map((row, rowIndex) => {
    return row.cols.map((item,index) => {
//you can pass whatever you want to pass to the component
      return <MemoizedComponent key={rowIndex+index} x={item} y={row} yourprops={condition ? color1: color2} />
    })
  })
}

finally you can update data by setting state like

  let final = this.state.data.map(r => {
    if (r === 'your condition') {
      return Object.assign({}, r, {
        cols: r.cols.map(c => {
          if (c === 'your col condition') {
            return Object.assign({}, c, {
              changedProp: 'changedPropvalue',
            });
          } else {
            return c;
          }
        }),
      });
    }else{
      return r
    }
  });

...

this.setState({data:final})

so when the state updates the component rerendered

also make sure you use PureComponent as it will restrict rerenders to only changed items


问:
In R programming, what's the difference between & vs &&, and | vs ||
I know the part that && and || make for more efficient code because they do the least number of tests in a chain and break out as soon as we have enough information to know what the result of the chain is going to be.

As soon as && hits a FALSE in a chain it stops evaluating and returns FALSE for the whole chain.

As soon as || hits a TRUE in a chain it stops evaluating and returns TRUE for the chain

But I read in Garrett Grolemund's book that "...double operators are not appropriate everywhere. && and || are not vectorized, which means they can only handle a single logical test on each side of the operator..." Can somebody please explain to me what the emphasized part means?

Did some simple tests and while & is doing a element-wise comparison between the corresponding elements of the two logical vectors, && is comparing only the first elements and returning TRUE because the operator is not vecorized? Is that all the emphasized part above means, or is there more to it?

```<code>c(T, F, F, F, F) & c(T, T, F, T, F)
[1]  TRUE FALSE FALSE FALSE FALSE

c(T, F, F, F, F) && c(T, T, F, T, F)
[1] TRUE

c(F, F, F, F, F) && c(T, T, F, T, F)
[1] FALSE
</code>```

Collapsing vectors on either side of the operator to one boolean value using any and all.

```<code>any(T, T, F, F, T) && all(F, F, T, T, T)
[1] FALSE

any(T, T, F, F, T) && any(F, F, T, T, T)
[1] TRUE
</code>```

答:
they can only handle a single logical test on each side of the operator

```<code>a <- c(T, F, F, F)
b <- c(T, F, F, F)
a && b
</code>```

Returns
    [1] TRUE

Because only the first element of a and b are tested!

Edit:

Consider the following, where we 'rotate' a and b after each && test:

```<code>a <- c(T, F, T, F)
b <- c(T, F, F, T)
for (i in seq_along(a)){
  cat(paste0("'a' is: ", paste0(a, collapse=", "), " and\n'b' is: ", paste0(b, collapse=", "),"\n"))
  print(paste0("'a && b' is: ", a && b))
  a <- c(a[2:length(a)], a[1])
  b <- c(b[2:length(b)], b[i])
}
</code>```

Gives us:

```<code>'a' is: TRUE, FALSE, TRUE, FALSE and
'b' is: TRUE, FALSE, FALSE, TRUE
[1] "'a && b' is: TRUE"
'a' is: FALSE, TRUE, FALSE, TRUE and
'b' is: FALSE, FALSE, TRUE, TRUE
[1] "'a && b' is: FALSE"
'a' is: TRUE, FALSE, TRUE, FALSE and
'b' is: FALSE, TRUE, TRUE, FALSE
[1] "'a && b' is: FALSE"
'a' is: FALSE, TRUE, FALSE, TRUE and
'b' is: TRUE, TRUE, FALSE, TRUE
[1] "'a && b' is: FALSE"
</code>```

Additionally, &&, || stops as soon as the expression is clear:

```<code>FALSE & a_not_existing_object
TRUE | a_not_existing_object
</code>```

Returns:

```<code>Error: object 'a_not_existing_object' not found
Error: object 'a_not_existing_object' not found
</code>```

But:

```<code>FALSE && a_not_existing_object
TRUE || a_not_existing_object
</code>```

Returns:

[1] FALSE

[1] TRUE

Because anything after FALSE AND something (and TRUE OR something) becomes FALSE and TRUE respectively

This last behavior of && and || is especially useful if you want to check in your control-flow for an element that may not exist:

```<code>if (exists(a_not_existing_object) && a_not_existing_object > 42) {...}
</code>```

This way the evaluation stops after the first expression evaluates to FALSE and the a_not_existing_object > 42 part is not even atempted!

Body:
I know the part that && and || make for more efficient code because they do the least number of tests in a chain and break out as soon as we have enough information to know what the result of the chain is going to be.

As soon as && hits a FALSE in a chain it stops evaluating and returns FALSE for the whole chain.

As soon as || hits a TRUE in a chain it stops evaluating and returns TRUE for the chain

But I read in Garrett Grolemund's book that "...double operators are not appropriate everywhere. && and || are not vectorized, which means they can only handle a single logical test on each side of the operator..." Can somebody please explain to me what the emphasized part means?

Did some simple tests and while & is doing a element-wise comparison between the corresponding elements of the two logical vectors, && is comparing only the first elements and returning TRUE because the operator is not vecorized? Is that all the emphasized part above means, or is there more to it?

c(T, F, F, F, F) & c(T, T, F, T, F)
[1]  TRUE FALSE FALSE FALSE FALSE

c(T, F, F, F, F) && c(T, T, F, T, F)
[1] TRUE

c(F, F, F, F, F) && c(T, T, F, T, F)
[1] FALSE

Collapsing vectors on either side of the operator to one boolean value using any and all.

any(T, T, F, F, T) && all(F, F, T, T, T)
[1] FALSE

any(T, T, F, F, T) && any(F, F, T, T, T)
[1] TRUE

Body:
they can only handle a single logical test on each side of the operator

a <- c(T, F, F, F)
b <- c(T, F, F, F)
a && b

Returns
    [1] TRUE

Because only the first element of a and b are tested!

Edit:

Consider the following, where we 'rotate' a and b after each && test:

a <- c(T, F, T, F)
b <- c(T, F, F, T)
for (i in seq_along(a)){
  cat(paste0("'a' is: ", paste0(a, collapse=", "), " and\n'b' is: ", paste0(b, collapse=", "),"\n"))
  print(paste0("'a && b' is: ", a && b))
  a <- c(a[2:length(a)], a[1])
  b <- c(b[2:length(b)], b[i])
}

Gives us:

'a' is: TRUE, FALSE, TRUE, FALSE and
'b' is: TRUE, FALSE, FALSE, TRUE
[1] "'a && b' is: TRUE"
'a' is: FALSE, TRUE, FALSE, TRUE and
'b' is: FALSE, FALSE, TRUE, TRUE
[1] "'a && b' is: FALSE"
'a' is: TRUE, FALSE, TRUE, FALSE and
'b' is: FALSE, TRUE, TRUE, FALSE
[1] "'a && b' is: FALSE"
'a' is: FALSE, TRUE, FALSE, TRUE and
'b' is: TRUE, TRUE, FALSE, TRUE
[1] "'a && b' is: FALSE"

Additionally, &&, || stops as soon as the expression is clear:

FALSE & a_not_existing_object
TRUE | a_not_existing_object

Returns:

Error: object 'a_not_existing_object' not found
Error: object 'a_not_existing_object' not found

But:

FALSE && a_not_existing_object
TRUE || a_not_existing_object

Returns:

[1] FALSE

[1] TRUE

Because anything after FALSE AND something (and TRUE OR something) becomes FALSE and TRUE respectively

This last behavior of && and || is especially useful if you want to check in your control-flow for an element that may not exist:

if (exists(a_not_existing_object) && a_not_existing_object > 42) {...}

This way the evaluation stops after the first expression evaluates to FALSE and the a_not_existing_object > 42 part is not even atempted!


问:
iPhone OpenGL ES Texture Pipeline for JPEG
I am having trouble getting my texture pipeline working for JPEGs.  Everything works right for PNGs but converting over has been an issue.

I am loading by image data via UIImage and CGBitmapContextCreate

```<code>UIImage* tI = [UIImage imageWithContentsOfFile:fileName];
Image = tI.CGImage;

mWidth = CGImageGetWidth(Image);
mHeight = CGImageGetHeight(Image);

mData = new uint8[mWidth * mHeight * 4];

Context = CGBitmapContextCreate(mData, mWidth, mHeight, CGImageGetBitsPerComponent(Image), CGImageGetBytesPerRow(Image),
                                CGImageGetColorSpace(Image),
                                CGImageGetBitmapInfo(Image));

CGContextDrawImage(Context, CGRectMake(0.0, 0.0, float(mWidth), float(mHeight)), Image);
CGContextRelease(Context);
</code>```

Then I setup my GLTexture with the call...

```<code>glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, texture->Width(), texture->Height(), 0, GL_RGB, GL_UNSIGNED_BYTE, texture->Data());
</code>```

I suspect this glTexImage2D call is the issue.  I have been using different combinations to try and get things to work.  The BitmapInfo state for alpha is 'kCGImageAlphaNoneSkipLast' so I am not sure if I should be using RGBA and GL_UNSIGNED_SHORT_5_5_5_1 but no combination I have tried worked so far.  The closest I got was...

```<code>glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, texture->Width(), texture->Height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, texture->Data());
</code>```

which gave me very blown out texture (color edges were discernable but everything was too bright)

Any help would be great.  I am using JPEGs to try and save space over PNGs.

答: Your mData buffer is too big. JPEG images don't support alpha, so there are only three components per pixel (RGB), whereas you'd usually use four for PNGs (RGBA).</p>

Body:
I am having trouble getting my texture pipeline working for JPEGs.  Everything works right for PNGs but converting over has been an issue.

I am loading by image data via UIImage and CGBitmapContextCreate

UIImage* tI = [UIImage imageWithContentsOfFile:fileName];
Image = tI.CGImage;

mWidth = CGImageGetWidth(Image);
mHeight = CGImageGetHeight(Image);

mData = new uint8[mWidth * mHeight * 4];

Context = CGBitmapContextCreate(mData, mWidth, mHeight, CGImageGetBitsPerComponent(Image), CGImageGetBytesPerRow(Image),
                                CGImageGetColorSpace(Image),
                                CGImageGetBitmapInfo(Image));

CGContextDrawImage(Context, CGRectMake(0.0, 0.0, float(mWidth), float(mHeight)), Image);
CGContextRelease(Context);

Then I setup my GLTexture with the call...

glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, texture->Width(), texture->Height(), 0, GL_RGB, GL_UNSIGNED_BYTE, texture->Data());

I suspect this glTexImage2D call is the issue.  I have been using different combinations to try and get things to work.  The BitmapInfo state for alpha is 'kCGImageAlphaNoneSkipLast' so I am not sure if I should be using RGBA and GL_UNSIGNED_SHORT_5_5_5_1 but no combination I have tried worked so far.  The closest I got was...

glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, texture->Width(), texture->Height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, texture->Data());

which gave me very blown out texture (color edges were discernable but everything was too bright)

Any help would be great.  I am using JPEGs to try and save space over PNGs.


问:
pyodbc rowcount only returns -1
How does rowcount work.  I am using pyodbc and it's always returning -1.</p>

```<code> return_query = conn.query_db_param(query, q_params)
 print(return_query.rowcount)

 def query_db_param(self, query, params):
     self.cursor.execute(query,params)
     print(self.cursor.rowcount)
</code>```

答:
If you are using microsoft sql server, and you want to get the number of rows returned in the prior select statement, you can just execute select @@rowcount.

E.g.:

cursor.execute("select @@rowcount")
rowcount = cursor.fetchall()[0][0]
```

Title: pyodbc rowcount only returns -1

Body:
How does rowcount work.  I am using pyodbc and it's always returning -1.

 return_query = conn.query_db_param(query, q_params)
 print(return_query.rowcount)

 def query_db_param(self, query, params):
     self.cursor.execute(query,params)
     print(self.cursor.rowcount)


问:
Creating a new calculated column in a oracle exadata table with 3 billion rows
I have a table in Oracle exadata with 3.4 billion rows.
I need to create a new column in this table which is the sum of the other 2 columns in the table.
I tried the below.
- Create column using alter table add column.
- Update table set column C = Column A + column B.
But update threw the below error after a while.
ORA-30036: unable to extend segment by 8 in undo tablespace 'UNDOTBS1'

I read the online documentation for this error and checked with the DBA and he said its not a space issue and that I should try an alternative to the update statement in this case.
Please let me know what other ways I can do this operation. Can I do this using insert?

Thanks,
Sawan

答:
To get an additional column that is calculated from other column of the row you can use a virtual column.

The great benefit is that you store no data, it can't be inconstistent and it is installed immediately.

```<code>alter table TEST add
(columnC NUMBER GENERATED ALWAYS AS (columnA + columnB) VIRTUAL)
;

select * from TEST;

   COLUMNA    COLUMNB    COLUMNC
---------- ---------- ----------
         1          1          2
         2          2          4
         3          3          6
</code>```

Body:
To get an additional column that is calculated from other column of the row you can use a virtual column.

The great benefit is that you store no data, it can't be inconstistent and it is installed immediately.

alter table TEST add
(columnC NUMBER GENERATED ALWAYS AS (columnA + columnB) VIRTUAL)
;

select * from TEST;

   COLUMNA    COLUMNB    COLUMNC
---------- ---------- ----------
         1          1          2
         2          2          4
         3          3          6


问:
Spring Data Jpa Repository findBy Part of Data not by doing all cases
I cannot find similar question, so I post this question.
I'm pleased to be linked similar question I have.

My Spring server get some parts of 3 Data from UI client and will give appropriate data to UI client found in DB.
I have to identify and execute respectively findby~ function for it.

In ProjectService

```<code>public List<Project> getProjectsByPartialData(ProjectDto projectDto) {
    if (projectDto.getYearCodeName()!= null && projectDto.getCustomerCoName() != null && projectDto.getSeasonCodeName()!=null) {
        return projectRepository.findByYearCodeNameAndCustomerCoNameAndSeasonCodeName(projectDto.getYearCodeName(),projectDto.getCustomerCoName(),projectDto.getSeasonCodeName());
    } else if (projectDto.getYearCodeName() == null && projectDto.getCustomerCoName() != null && projectDto.getSeasonCodeName()!=null) {
        return projectRepository.findByCustomerCoNameAndSeasonCodeName(projectDto.getCustomerCoName(),projectDto.getSeasonCodeName());
    } else if (projectDto.getYearCodeName()!= null && projectDto.getCustomerCoName() == null && projectDto.getSeasonCodeName()!=null) {
        return projectRepository.findByYearCodeNameAndSeasonCodeName(projectDto.getYearCodeName(),projectDto.getSeasonCodeName());
    } else if (projectDto.getYearCodeName()!= null && projectDto.getCustomerCoName() != null && projectDto.getSeasonCodeName()==null) {
        return projectRepository.findByYearCodeNameAndCustomerCoName(projectDto.getYearCodeName(),projectDto.getCustomerCoName());
    } ...3 more to go
}
</code>```

Is there any simple way to do this??

extra

In Project

```<code>@Entity
@Getter
@NoArgsConstructor
@ToString
@EqualsAndHashCode
public class Project {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @ManyToOne
    @JoinColumn(name = "YEAR_CODE", referencedColumnName = "CODE")
    private YearCode yearCode;

    @ManyToOne
    @JoinColumn(name = "CUSTOMER_CO_CODE", referencedColumnName = "CODE")
    private CustomerCo customerCo;

    @ManyToOne
    @JoinColumn(name = "SEASON_CODE", referencedColumnName = "CODE")
    private SeasonCode seasonCode;

    ... other properties
}
</code>```

In ProjectDto

```<code>@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
@ToString
public class ProjectDto {

    private String yearCodeName;

    @JsonProperty(value = "customerNameCode")
    private String customerCoName;

    private String seasonCodeName;
    ... other properties
}
</code>```

答:
You don't have to use findBy... method for each case. Spring Data has special Specification interface to define reusable predicate. Just implement toPredicate(..) method from this interface and use your implementation as a parameter in repository method:

```<code>List<Project> findAll(Specification spec);
</code>```

See more:

Spring Data Specifications and Querydsl

REST Query Language with Spring Data JPA Specifications

Body:
I cannot find similar question, so I post this question.
I'm pleased to be linked similar question I have.

My Spring server get some parts of 3 Data from UI client and will give appropriate data to UI client found in DB.
I have to identify and execute respectively findby~ function for it.

In ProjectService

public List<Project> getProjectsByPartialData(ProjectDto projectDto) {
    if (projectDto.getYearCodeName()!= null && projectDto.getCustomerCoName() != null && projectDto.getSeasonCodeName()!=null) {
        return projectRepository.findByYearCodeNameAndCustomerCoNameAndSeasonCodeName(projectDto.getYearCodeName(),projectDto.getCustomerCoName(),projectDto.getSeasonCodeName());
    } else if (projectDto.getYearCodeName() == null && projectDto.getCustomerCoName() != null && projectDto.getSeasonCodeName()!=null) {
        return projectRepository.findByCustomerCoNameAndSeasonCodeName(projectDto.getCustomerCoName(),projectDto.getSeasonCodeName());
    } else if (projectDto.getYearCodeName()!= null && projectDto.getCustomerCoName() == null && projectDto.getSeasonCodeName()!=null) {
        return projectRepository.findByYearCodeNameAndSeasonCodeName(projectDto.getYearCodeName(),projectDto.getSeasonCodeName());
    } else if (projectDto.getYearCodeName()!= null && projectDto.getCustomerCoName() != null && projectDto.getSeasonCodeName()==null) {
        return projectRepository.findByYearCodeNameAndCustomerCoName(projectDto.getYearCodeName(),projectDto.getCustomerCoName());
    } ...3 more to go
}

Is there any simple way to do this??

extra

In Project

@Entity
@Getter
@NoArgsConstructor
@ToString
@EqualsAndHashCode
public class Project {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @ManyToOne
    @JoinColumn(name = "YEAR_CODE", referencedColumnName = "CODE")
    private YearCode yearCode;

    @ManyToOne
    @JoinColumn(name = "CUSTOMER_CO_CODE", referencedColumnName = "CODE")
    private CustomerCo customerCo;

    @ManyToOne
    @JoinColumn(name = "SEASON_CODE", referencedColumnName = "CODE")
    private SeasonCode seasonCode;

    ... other properties
}

In ProjectDto

@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
@ToString
public class ProjectDto {

    private String yearCodeName;

    @JsonProperty(value = "customerNameCode")
    private String customerCoName;

    private String seasonCodeName;
    ... other properties
}

Body:
You don't have to use findBy... method for each case. Spring Data has special Specification interface to define reusable predicate. Just implement toPredicate(..) method from this interface and use your implementation as a parameter in repository method:

List<Project> findAll(Specification spec);

See more:

Spring Data Specifications and Querydsl

REST Query Language with Spring Data JPA Specifications


问:
Display data based on the value of the key
I have one column(Date) in the table which has some icons and text coming from a dictionary. the table looks like as shown in the below picture. the key 'date' has values of font awesome icon class and normal date string. so i am struggling to get a way to implement date column. here the advantage is i can modify dictionary however i want like i can add, delete or changing the key value pairs to achieve the goal. Thanks in advance.

stackblitz link

 data = [
    {
    'date':'fa-refresh',
    'name':"Bengaluru",
    'entities': 14,
    'details':'Lorem Ipsum , Lorem Ipsum',
    'actions':'fa fa-envelope-o',
    'color':'text-primary'
},
{
  'date':'fa-refresh',
  'name':"Hyderabad",
  'entities': 17,
  'details':'Lorem Ipsum,Lorem Ipsum, Ipsum',
  'actions':'fa fa-envelope-o',
  'color':'text-primary'

},
{
  'date':'Nov 4',
  'name':"Mumbai",
  'entities': 20,
  'details':'Lorem Ipsum,Lorem ,Lorem Ipsum',
  'actions':'fa fa-envelope-o,fa fa-share-alt,fa fa-trash-o,fa fa-pencil'

},
{
  'date':'Nov 5',
  'name':"Kerala",
  'entities': 10,
  'details':'Lorem ,Lorem Ipsum,Lorem Ipsum',
  'actions':'fa fa-envelope-o,fa fa-share-alt,fa fa-trash-o,fa fa-pencil'

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>      <table class="table table-hover">
        <tr>
          <th class="text">Date</th>
          <th class="text">List Name</th>
          <th class="text">No. of Entities</th>
          <th class="text">Actions</th>
          <th class="text"></th>

        </tr>
        <tbody>
          <tr *ngFor="let items of data | filter: search">
            <td class="text-dark font-weight-bold"> {{items.date}}</td>
            <td  class=" font-weight-bold tablename {{items.color}}">{{ items.name }}</td>
            <td  class="text-dark font-weight-bold">{{ items.entities }}</td>

            <td>
              <span *ngFor="let x of items.actions.split(',')">
                  <i class="{{x}} tableicons"></i>
              </span>
          </td>            <td>
              <button type="button" class="btn btn-outline-secondary" (click)="getdetails(items)">
                Details
              </button>
            </td>
          </tr>
        </tbody>
      </table></code>```

答:
You shouldn't reuse properties in your model like this. You should keep your date separate from whatever icons you also want to show. You should also use date instances.

data

```<code>data = [
{
  date: null,
  /* other properties omitted for brevity */
},
{
  date: null
},
{
  date: new Date('2019-11-04'),
}
]
</code>```

html

```<code><tr *ngFor="let items of data | filter: search">
  <td class="text-dark font-weight-bold">
    <span *ngIf="items.date">{{items.date | date:'MMM dd' }}</span>
    <span *ngIf="!items.date"><i class="fas fa-refresh"></i></span>
  </td>
  <!-- other cells omitted for brevity -->
</tr>
</code>```

A simpler model will then let you choose how to display it in the HTML. I have assumed you want to show either a formatted date (read up on how to format dates using the Angular date pipe), or a font awesome fas fa-refresh icon. Obviously change these to suit your needs.

NB The data model I have shown is for a simple case where you either have a date or need to show an icon. If you potentially need to show different icons, then you would need to build that into your model.

Body:
I have one column(Date) in the table which has some icons and text coming from a dictionary. the table looks like as shown in the below picture. the key 'date' has values of font awesome icon class and normal date string. so i am struggling to get a way to implement date column. here the advantage is i can modify dictionary however i want like i can add, delete or changing the key value pairs to achieve the goal. Thanks in advance.

stackblitz link

 data = [
    {
    'date':'fa-refresh',
    'name':"Bengaluru",
    'entities': 14,
    'details':'Lorem Ipsum , Lorem Ipsum',
    'actions':'fa fa-envelope-o',
    'color':'text-primary'
},
{
  'date':'fa-refresh',
  'name':"Hyderabad",
  'entities': 17,
  'details':'Lorem Ipsum,Lorem Ipsum, Ipsum',
  'actions':'fa fa-envelope-o',
  'color':'text-primary'

},
{
  'date':'Nov 4',
  'name':"Mumbai",
  'entities': 20,
  'details':'Lorem Ipsum,Lorem ,Lorem Ipsum',
  'actions':'fa fa-envelope-o,fa fa-share-alt,fa fa-trash-o,fa fa-pencil'

},
{
  'date':'Nov 5',
  'name':"Kerala",
  'entities': 10,
  'details':'Lorem ,Lorem Ipsum,Lorem Ipsum',
  'actions':'fa fa-envelope-o,fa fa-share-alt,fa fa-trash-o,fa fa-pencil'

}

          Date
          List Name
          No. of Entities
          Actions

             {{items.date}}
            {{ items.name }}
            {{ items.entities }}

              <button type="button" class="btn btn-outline-secondary" (click)="getdetails(items)">
                Details
              </button>

Body:
You shouldn't reuse properties in your model like this. You should keep your date separate from whatever icons you also want to show. You should also use date instances.

data

data = [
{
  date: null,
  /* other properties omitted for brevity */
},
{
  date: null
},
{
  date: new Date('2019-11-04'),
}
]

html

<tr *ngFor="let items of data | filter: search">
  <td class="text-dark font-weight-bold">
    <span *ngIf="items.date">{{items.date | date:'MMM dd' }}</span>
    <span *ngIf="!items.date"><i class="fas fa-refresh"></i></span>
  </td>
  <!-- other cells omitted for brevity -->
</tr>

A simpler model will then let you choose how to display it in the HTML. I have assumed you want to show either a formatted date (read up on how to format dates using the Angular date pipe), or a font awesome fas fa-refresh icon. Obviously change these to suit your needs.

NB The data model I have shown is for a simple case where you either have a date or need to show an icon. If you potentially need to show different icons, then you would need to build that into your model.


问:
Debugging a DLL in VS2005 (C++)
I have a dll project in a solution that I want to debug.  The calling application is in a different path and the DLL must be placed inside that path. When I build the debug version and copy+paste the produced DLL into the calling application's path, I get an error message that there are no symbols and that the binary wasn't built by the project. It asks me if I want to continue. This method used to work in visual c++ 6.0 but now it never hits any breakpoints.. How do I do this in VS2005?

Thanks.

答:
Make sure the pdb file for the dll is also in the application's path.

Or alternatively compile your dll with the /Z7 compiler option, that will trigger the old-style debug info as it was used in MSVC 6.0. If you compile like this, you will be able to copy just the dll.

Or alternatively in the 'Modules' window, right-click your dll and select 'Load Symbols', then point the dialog to the original location of your dll.

OwnerDisplayName: krebstar

ContentLicense: CC BY-SA 2.5

Title: Debugging a DLL in VS2005 (C++)

LastEditorDisplayName: krebstar


问:
ERROR in Cannot assign to a reference or variable
If I set full template type check

```<code>    {
        "compileOnSave": false,
        "compilerOptions": {
            ///...
            "target": "es6",
            "typeRoots": ["node_modules/@types"],
            "lib": ["es2018", "dom"],
        },
        "angularCompilerOptions": {
            "fullTemplateTypeCheck": true,
            "enableIvy": false
        }
    }
</code>```

I get this error:

ERROR in Cannot assign to a reference or variable

So how can I figure out where exactly the problem is?

i have a big project.

答:
please set:

```<code> "fullTemplateTypeCheck": false,
</code>```

should be ok

Body:
If I set full template type check

    {
        "compileOnSave": false,
        "compilerOptions": {
            ///...
            "target": "es6",
            "typeRoots": ["node_modules/@types"],
            "lib": ["es2018", "dom"],
        },
        "angularCompilerOptions": {
            "fullTemplateTypeCheck": true,
            "enableIvy": false
        }
    }

I get this error:

ERROR in Cannot assign to a reference or variable

So how can I figure out where exactly the problem is?

i have a big project.

Body:
please set:

 "fullTemplateTypeCheck": false,

should be ok


问:
Conditionally Assign const value in js
I'm trying to assign a different value to sequelize based on whether the app is running locally or on the server. This is my code:

```<code>    const sequelize = production
  ? sequelizeHeroku.connect(Sequelize)
  : new Sequelize(database, user, password, {
      host,
      dialect: "mysql",
      pool: {
        max: 10,
        min: 0,
        acquire: 30000,
        idle: 10000
      }
    });
</code>```

This doesn't work locally, as when I log the value of sequelize it is false. However, if I try to assign the variable like this:

```<code>const sequelize = new Sequelize(database, user, password, {
  host,
  dialect: "mysql",
  pool: {
    max: 10,
    min: 0,
    acquire: 30000,
    idle: 10000
  }
});
</code>```

it works just fine. I also checked that console.log(production == true) prints out false. What am I doing wrong?

答:
It's better to use NODE_ENV environment variable. E.g.

index.ts:

import { Sequelize } from 'sequelize';
import assert from 'assert';

const database = 'sample';
const user = 'testuser';
const password = 'testpass';
const host = '127.0.0.1';

const sequelize =
  process.env.NODE_ENV === 'production'
    ? 'sequelize heroku'
    : new Sequelize(database, user, password, {
        host,
        dialect: 'mysql',
        pool: {
          max: 10,
          min: 0,
          acquire: 30000,
          idle: 10000,
        },
      });

assert(process.env.NODE_ENV === 'production', 'NODE_ENV should be "production"');
assert(sequelize === 'sequelize heroku', 'Should use heroku sequelize in production environment');
```

<p>Execute code in <code>production</code> environment:</p>

<pre class="lang-js prettyprint-override"><code>NODE_ENV=production npx ts-node ./index.ts
</code>```

No assertion failed. It works as expected.

Title: Conditionally Assign const value in js

Body:
I'm trying to assign a different value to sequelize based on whether the app is running locally or on the server. This is my code:

    const sequelize = production
  ? sequelizeHeroku.connect(Sequelize)
  : new Sequelize(database, user, password, {
      host,
      dialect: "mysql",
      pool: {
        max: 10,
        min: 0,
        acquire: 30000,
        idle: 10000
      }
    });

This doesn't work locally, as when I log the value of sequelize it is false. However, if I try to assign the variable like this:

const sequelize = new Sequelize(database, user, password, {
  host,
  dialect: "mysql",
  pool: {
    max: 10,
    min: 0,
    acquire: 30000,
    idle: 10000
  }
});

it works just fine. I also checked that console.log(production == true) prints out false. What am I doing wrong?

Body:
It's better to use NODE_ENV environment variable. E.g.

index.ts:

import { Sequelize } from 'sequelize';
import assert from 'assert';

const database = 'sample';
const user = 'testuser';
const password = 'testpass';
const host = '127.0.0.1';

const sequelize =
  process.env.NODE_ENV === 'production'
    ? 'sequelize heroku'
    : new Sequelize(database, user, password, {
        host,
        dialect: 'mysql',
        pool: {
          max: 10,
          min: 0,
          acquire: 30000,
          idle: 10000,
        },
      });

assert(process.env.NODE_ENV === 'production', 'NODE_ENV should be "production"');
assert(sequelize === 'sequelize heroku', 'Should use heroku sequelize in production environment');

Execute code in production environment:

NODE_ENV=production npx ts-node ./index.ts

No assertion failed. It works as expected.


问:
DynamoDB and computed columns: Run Lambda on GetItem / Query request but before data is returned to caller
Is it possible to run a Lambda function as part of a GetItem / Query request? I plan to use some kind of computed colum that I would like to update before the value is returned to the caller. The current idea is to do this with a Lambda function and DynamoDB Streams. Up to know, I kind of missed the part in the docs where I can specify the exact moment when the Lambda is executed (before, after fetching data). Of course, I am open for better ideas!

答:
No. It is not possible. Dynamodb is designed to response items in distributed systems within milliseconds. There is no way to execute Lambdas synchronous with Put or Get Requets. DynamodDB Streams are more like asynchronous Table Trigger and only executed on new Data. </p>

<p>One Idea is to call an Lambda to collect and compute your data instead request Dynamodb. </p>

Body:
No. It is not possible. Dynamodb is designed to response items in distributed systems within milliseconds. There is no way to execute Lambdas synchronous with Put or Get Requets. DynamodDB Streams are more like asynchronous Table Trigger and only executed on new Data.

One Idea is to call an Lambda to collect and compute your data instead request Dynamodb.