问:
How do resolve this exception in my Spring Application?
Here is my configuration file

```<code>import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@Configuration
//activates spring MVC
@EnableWebMvc
//scans for our classes in the package
@ComponentScan("in.nit")
//loads properties file into Spring Container
@PropertySource("classpath:app.properties")

public class AppConfig {
@Autowired
Environment env;

//1.DataSource
@Bean
public DataSource ds() {
    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName(env.getProperty("db.driver"));
    ds.setUrl("db.url");
    ds.setUsername("db.user");
    ds.setPassword("db.password");
    return ds;
}
//session factory
@Bean
public LocalSessionFactoryBean sf() {
    LocalSessionFactoryBean sf = new LocalSessionFactoryBean();
    sf.setDataSource(ds());
    sf.setHibernateProperties(props());
//  sf.setAnnotatedClasses(annotatedClasses);
    sf.setPackagesToScan("in.nit.model");
    return  sf;
}
//Hibernate properties

public Properties props() {
    Properties props = new Properties();
    props.put("hibernate.dialect", env.getProperty("orm.dialect"));
    props.put("hibernate.format_sql",env.getProperty("orm.format_sql"));
    props.put("hibernate.show_sql",env.getProperty("orm.show_sql"));
    props.put("hibernate.hbm2ddl.auto", env.getProperty("orm.hb2ddl.auto"));
    return props;

}
//Tx Manager

@Bean
public HibernateTransactionManager tm() {
    HibernateTransactionManager tm = new HibernateTransactionManager();
    tm.setSessionFactory(sf().getObject());
    return tm;
}
//HibernateTemplate
@Bean
public HibernateTemplate ht() {
    HibernateTemplate ht = new HibernateTemplate();
    ht.setSessionFactory(sf().getObject());
    return ht;
}

//view resolver
@Bean
public InternalResourceViewResolver vr() {
    InternalResourceViewResolver vr = new InternalResourceViewResolver();
    vr.setSuffix(env.getProperty("mvc.suffix"));
    vr.setPrefix(env.getProperty("mvc.prefix"));
    return vr;
}
}
</code>```

And this is my Prperties file from which The config would read values

```<code>##Connection Properties##
db.driver = oracle.jdbc.driver.OracleDriver
db.url = jdbc:oracle:thin:@localhost:1521:ORCL.168.0.29
db.user = prem
db.password = rempe

##ORM PROPERTIES ##
orm.dialect = org.hibernate.dialect.OracleDialect
orm.show_sql = true
orm.format_sql = true
orm.hbm2ddl.auto = create

##MVC properties##
mvc.prefix = /WEB-INF/views/
mvc.suffix = .jsp
</code>```

and below is my WebApplicationInitializer file

```<code>import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class AppInit extends AbstractAnnotationConfigDispatcherServletInitializer {

    //provivde root configuration classes to FrontController something like providing web.xml to ServletContainer
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[] {AppConfig.class};
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        // TODO Auto-generated method stub
        return null;
    }

    //URL pattern
    @Override
    protected String[] getServletMappings() {
        return new String[] {"/"};
    }

}

</code>```

and on running the application in tomcat 9.0 webserver ,I get the following exception

```<code>WARNING: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sf' defined in AppConfig: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.hibernate5.LocalSessionFactoryBean]: Factory method 'sf' threw exception; nested exception is java.lang.NullPointerException
Feb 15, 2020 7:09:54 PM org.springframework.web.context.ContextLoader initWebApplicationContext
SEVERE: Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sf' defined in AppConfig: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.hibernate5.LocalSessionFactoryBean]: Factory method 'sf' threw exception; nested exception is java.lang.NullPointerException
    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:656)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:484)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1338)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1177)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:557)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:860)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:878)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:401)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:292)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:103)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4680)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5150)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1377)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1367)
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
    at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
    at java.base/java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:140)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:902)
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:841)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1377)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1367)
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
    at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
    at java.base/java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:140)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:902)
    at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:262)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.StandardService.startInternal(StandardService.java:421)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:932)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:633)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:344)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:475)
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.hibernate5.LocalSessionFactoryBean]: Factory method 'sf' threw exception; nested exception is java.lang.NullPointerException
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:651)
    ... 45 more
Caused by: java.lang.NullPointerException
    at java.base/java.util.concurrent.ConcurrentHashMap.putVal(ConcurrentHashMap.java:1011)
    at java.base/java.util.concurrent.ConcurrentHashMap.put(ConcurrentHashMap.java:1006)
    at java.base/java.util.Properties.put(Properties.java:1331)
    at AppConfig.props(AppConfig.java:57)
    at AppConfig.sf(AppConfig.java:45)
    at AppConfig$$EnhancerBySpringCGLIB$$dbf03bd2.CGLIB$sf$4(<generated>)
    at AppConfig$$EnhancerBySpringCGLIB$$dbf03bd2$$FastClassBySpringCGLIB$$69575c9b.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244)
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:363)
    at AppConfig$$EnhancerBySpringCGLIB$$dbf03bd2.sf(<generated>)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154)
    ... 46 more

Feb 15, 2020 7:09:54 PM org.apache.catalina.core.StandardContext listenerStart
SEVERE: Exception sending context initialized event to listener instance of class [org.springframework.web.context.ContextLoaderListener]
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sf' defined in AppConfig: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.hibernate5.LocalSessionFactoryBean]: Factory method 'sf' threw exception; nested exception is java.lang.NullPointerException
    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:656)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:484)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1338)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1177)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:557)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:860)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:878)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:401)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:292)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:103)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4680)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5150)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1377)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1367)
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
    at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
    at java.base/java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:140)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:902)
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:841)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1377)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1367)
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
    at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
    at java.base/java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:140)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:902)
    at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:262)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.StandardService.startInternal(StandardService.java:421)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:932)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:633)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:344)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:475)
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.hibernate5.LocalSessionFactoryBean]: Factory method 'sf' threw exception; nested exception is java.lang.NullPointerException
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:651)
    ... 45 more
Caused by: java.lang.NullPointerException
    at java.base/java.util.concurrent.ConcurrentHashMap.putVal(ConcurrentHashMap.java:1011)
    at java.base/java.util.concurrent.ConcurrentHashMap.put(ConcurrentHashMap.java:1006)
    at java.base/java.util.Properties.put(Properties.java:1331)
    at AppConfig.props(AppConfig.java:57)
    at AppConfig.sf(AppConfig.java:45)
    at AppConfig$$EnhancerBySpringCGLIB$$dbf03bd2.CGLIB$sf$4(<generated>)
    at AppConfig$$EnhancerBySpringCGLIB$$dbf03bd2$$FastClassBySpringCGLIB$$69575c9b.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244)
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:363)
    at AppConfig$$EnhancerBySpringCGLIB$$dbf03bd2.sf(<generated>)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154)
    ... 46 more
</code>```

Please Guide me how to resolve this issue and explain why is it occuring?

答:
You are trying to inject property which is not found in your property file

```<code> props.put("hibernate.hbm2ddl.auto", env.getProperty("orm.hb2ddl.auto"));
</code>```

But your property file contains

```<code>  orm.hbm2ddl.auto = create
</code>```

Body:
Here is my configuration file

import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@Configuration
//activates spring MVC
@EnableWebMvc
//scans for our classes in the package
@ComponentScan("in.nit")
//loads properties file into Spring Container
@PropertySource("classpath:app.properties")

public class AppConfig {
@Autowired
Environment env;

//1.DataSource
@Bean
public DataSource ds() {
    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName(env.getProperty("db.driver"));
    ds.setUrl("db.url");
    ds.setUsername("db.user");
    ds.setPassword("db.password");
    return ds;
}
//session factory
@Bean
public LocalSessionFactoryBean sf() {
    LocalSessionFactoryBean sf = new LocalSessionFactoryBean();
    sf.setDataSource(ds());
    sf.setHibernateProperties(props());
//  sf.setAnnotatedClasses(annotatedClasses);
    sf.setPackagesToScan("in.nit.model");
    return  sf;
}
//Hibernate properties

public Properties props() {
    Properties props = new Properties();
    props.put("hibernate.dialect", env.getProperty("orm.dialect"));
    props.put("hibernate.format_sql",env.getProperty("orm.format_sql"));
    props.put("hibernate.show_sql",env.getProperty("orm.show_sql"));
    props.put("hibernate.hbm2ddl.auto", env.getProperty("orm.hb2ddl.auto"));
    return props;

}
//Tx Manager

@Bean
public HibernateTransactionManager tm() {
    HibernateTransactionManager tm = new HibernateTransactionManager();
    tm.setSessionFactory(sf().getObject());
    return tm;
}
//HibernateTemplate
@Bean
public HibernateTemplate ht() {
    HibernateTemplate ht = new HibernateTemplate();
    ht.setSessionFactory(sf().getObject());
    return ht;
}

//view resolver
@Bean
public InternalResourceViewResolver vr() {
    InternalResourceViewResolver vr = new InternalResourceViewResolver();
    vr.setSuffix(env.getProperty("mvc.suffix"));
    vr.setPrefix(env.getProperty("mvc.prefix"));
    return vr;
}
}

And this is my Prperties file from which The config would read values

##Connection Properties##
db.driver = oracle.jdbc.driver.OracleDriver
db.url = jdbc:oracle:thin:@localhost:1521:ORCL.168.0.29
db.user = prem
db.password = rempe

##ORM PROPERTIES ##
orm.dialect = org.hibernate.dialect.OracleDialect
orm.show_sql = true
orm.format_sql = true
orm.hbm2ddl.auto = create

##MVC properties##
mvc.prefix = /WEB-INF/views/
mvc.suffix = .jsp

and below is my WebApplicationInitializer file

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class AppInit extends AbstractAnnotationConfigDispatcherServletInitializer {

    //provivde root configuration classes to FrontController something like providing web.xml to ServletContainer
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[] {AppConfig.class};
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        // TODO Auto-generated method stub
        return null;
    }

    //URL pattern
    @Override
    protected String[] getServletMappings() {
        return new String[] {"/"};
    }

}

and on running the application in tomcat 9.0 webserver ,I get the following exception

WARNING: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sf' defined in AppConfig: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.hibernate5.LocalSessionFactoryBean]: Factory method 'sf' threw exception; nested exception is java.lang.NullPointerException
Feb 15, 2020 7:09:54 PM org.springframework.web.context.ContextLoader initWebApplicationContext
SEVERE: Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sf' defined in AppConfig: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.hibernate5.LocalSessionFactoryBean]: Factory method 'sf' threw exception; nested exception is java.lang.NullPointerException
    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:656)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:484)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1338)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1177)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:557)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:860)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:878)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:401)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:292)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:103)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4680)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5150)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1377)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1367)
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
    at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
    at java.base/java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:140)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:902)
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:841)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1377)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1367)
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
    at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
    at java.base/java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:140)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:902)
    at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:262)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.StandardService.startInternal(StandardService.java:421)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:932)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:633)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:344)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:475)
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.hibernate5.LocalSessionFactoryBean]: Factory method 'sf' threw exception; nested exception is java.lang.NullPointerException
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:651)
    ... 45 more
Caused by: java.lang.NullPointerException
    at java.base/java.util.concurrent.ConcurrentHashMap.putVal(ConcurrentHashMap.java:1011)
    at java.base/java.util.concurrent.ConcurrentHashMap.put(ConcurrentHashMap.java:1006)
    at java.base/java.util.Properties.put(Properties.java:1331)
    at AppConfig.props(AppConfig.java:57)
    at AppConfig.sf(AppConfig.java:45)
    at AppConfig$$EnhancerBySpringCGLIB$$dbf03bd2.CGLIB$sf$4(<generated>)
    at AppConfig$$EnhancerBySpringCGLIB$$dbf03bd2$$FastClassBySpringCGLIB$$69575c9b.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244)
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:363)
    at AppConfig$$EnhancerBySpringCGLIB$$dbf03bd2.sf(<generated>)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154)
    ... 46 more

Feb 15, 2020 7:09:54 PM org.apache.catalina.core.StandardContext listenerStart
SEVERE: Exception sending context initialized event to listener instance of class [org.springframework.web.context.ContextLoaderListener]
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sf' defined in AppConfig: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.hibernate5.LocalSessionFactoryBean]: Factory method 'sf' threw exception; nested exception is java.lang.NullPointerException
    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:656)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:484)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1338)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1177)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:557)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:860)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:878)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:401)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:292)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:103)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4680)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5150)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1377)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1367)
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
    at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
    at java.base/java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:140)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:902)
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:841)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1377)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1367)
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
    at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
    at java.base/java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:140)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:902)
    at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:262)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.StandardService.startInternal(StandardService.java:421)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:932)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:633)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:344)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:475)
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.hibernate5.LocalSessionFactoryBean]: Factory method 'sf' threw exception; nested exception is java.lang.NullPointerException
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:651)
    ... 45 more
Caused by: java.lang.NullPointerException
    at java.base/java.util.concurrent.ConcurrentHashMap.putVal(ConcurrentHashMap.java:1011)
    at java.base/java.util.concurrent.ConcurrentHashMap.put(ConcurrentHashMap.java:1006)
    at java.base/java.util.Properties.put(Properties.java:1331)
    at AppConfig.props(AppConfig.java:57)
    at AppConfig.sf(AppConfig.java:45)
    at AppConfig$$EnhancerBySpringCGLIB$$dbf03bd2.CGLIB$sf$4(<generated>)
    at AppConfig$$EnhancerBySpringCGLIB$$dbf03bd2$$FastClassBySpringCGLIB$$69575c9b.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244)
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:363)
    at AppConfig$$EnhancerBySpringCGLIB$$dbf03bd2.sf(<generated>)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154)
    ... 46 more

Please Guide me how to resolve this issue and explain why is it occuring?

Body:
You are trying to inject property which is not found in your property file

 props.put("hibernate.hbm2ddl.auto", env.getProperty("orm.hb2ddl.auto"));

But your property file contains

  orm.hbm2ddl.auto = create


来源: stackexchange

问:
Generic interface problem
So here is my problem:

I have the interface:

```<code>public interface ICell<Feature>
where Feature: struct, IComparable<ICell<Feature>>
{
    List<ICell<Feature>> Window { get; set; }
    Feature              GenusFeature { get; set; }
    Double               VitalityRatio { get; set; }
    String               PopulationMarker { get; set; }
    Boolean              Captured { get; set; }
}
</code>```

And wanted to implement ISubstratum interface in this way:

```<code>public interface ISubstratum<K,T> : IDisposable
where K : IDisposable
where T : struct
{
    ICell<T> this[Int32 i, Int32 j] { get; set; }
}
</code>```

But compiler says that:

The type 'T' cannot be used as type parameter 'Feature' in the generic type or method 'Colorizer.Core.ICell<Feature>'. There is no boxing conversion or type parameter conversion from 'T' to 'System.IComparable<Colorizer.Core.ICell<T>>'.

In some possible ISubstratum implementation I planned to pass a Bitmap as K && ICell (extented pixel info) as T.

How to resolve this?

Thanks!

答: You need to require T to implement IComparable<ICell<T>> as defined by the ICell type definition.

ContentLicense: CC BY-SA 3.0

Title: Generic interface problem

Body:
So here is my problem:

I have the interface:

public interface ICell<Feature>
where Feature: struct, IComparable<ICell<Feature>>
{
    List<ICell<Feature>> Window { get; set; }
    Feature              GenusFeature { get; set; }
    Double               VitalityRatio { get; set; }
    String               PopulationMarker { get; set; }
    Boolean              Captured { get; set; }
}

And wanted to implement ISubstratum interface in this way:

public interface ISubstratum<K,T> : IDisposable
where K : IDisposable
where T : struct
{
    ICell<T> this[Int32 i, Int32 j] { get; set; }
}

But compiler says that:

The type 'T' cannot be used as type parameter 'Feature' in the generic type or method 'Colorizer.Core.ICell<Feature>'. There is no boxing conversion or type parameter conversion from 'T' to 'System.IComparable<Colorizer.Core.ICell<T>>'.

In some possible ISubstratum implementation I planned to pass a Bitmap as K && ICell (extented pixel info) as T.

How to resolve this?

Thanks!


问:
Why do tutorials that dockerize Node.js require you to also install Node.js on the host?
What's the point of having Node.js and Vue.js installed on my host and then also getting a Node/Vue image for Docker? Every Vue.js tutorial says to install Node and Vue to the host first and then get the Docker image, is this not redundant?

Examples:

https://morioh.com/p/3021edac7ef1

https://jonathanmh.com/deploying-a-vue-js-single-page-app-including-router-with-docker/

https://mherman.org/blog/dockerizing-a-vue-app/

I'm using a Windows 10 host and was trying to avoid installing Node and Vue to Windows if possible, unless there are particular advantages to doing so, which hopefully someone can enumerate. Otherwise, maybe someone can confirm that it's redundant to also install Node/Vue on the host and state why it's silly and redundant.

答:
Like you say, it is redundant but easier. A container is a running instance of an image, an image that was created (probably) using a Dockerfile with the instructions, so how would you go about doing everything from the container?

Would you add the creation of the app to the Dockerfile or would you connect to the container using bash and run the commands from there? If you connect with bash you'll lost everything once you remove the container. Once your app is created inside your container how would you get it out? I mean you need to write your app's code. You could store you data using docker volumes but that gets complicated depending were you are running Docker. For example on Mac a virtual machine is created for Docker, so to find that data you'll need to connect to the virtual machine...

It is just easier to do all of that from your local machine and use docker to host your app.

ContentLicense: CC BY-SA 4.0


问:
How to ensure Java threads run in a particular order
Given three threads, 1-3, that print a letter, A-C, how can I guarantee the output order?

I would like the output of the threads to be "ABCABCABC"

答:
```<code>public class RunningThreadSequentially {
    //Runnable task for each thread
    private static class Task implements Runnable {
        public static int counter=0;

        @Override
        public void run() {
            try {
                synchronized(this) {
                    Thread.sleep(500);
                    System.out.println(Thread.currentThread().getName() + " is completed--" + counter ++);
                }
            } catch (Exception ex) {
            }
        }
    }

    public static void main(String args[]) throws InterruptedException {
        while(true) {
            Thread t1 = new Thread(new Task(), "Thread 1");
            Thread t2 = new Thread(new Task(), "Thread 2");
            Thread t3 = new Thread(new Task(), "Thread 3");
            Thread t4 = new Thread(new Task(), "Thread 4");
            Thread t5 = new Thread(new Task(), "Thread 5");
            Thread t6 = new Thread(new Task(), "Thread 6");

            t1.start();
            t1.join();
            t2.start();
            t2.join();
            t3.start();
            t3.join();
            t4.start();
            t4.join();
            t5.start();
            t5.join();
            t6.start();
            t6.join();
        }
    }
}
</code>```


问:
EF Core FromSql with IN Clause
How to pass a dynamic list of int to FromSql method?
i tried the following code but it not works.

Conversion failed when converting the nvarchar value '1,2,3' to data type int.

```<code>var result = dataContext.Customers.FromSql($"SELECT * FROM Customer WHERE Id IN ({string.Join(",", listOfInt)})")
</code>```

答:
This works for me:

```<code>var result = dataContext.Customers.FromSql(string.Format("SELECT * FROM Customer WHERE Id IN ({0})", string.Join(",", listOfInt)));
</code>```

It does complain about injection vulnerability however but easy to sanitise a list of int at least.

Title: EF Core FromSql with IN Clause

Body:
How to pass a dynamic list of int to FromSql method?
i tried the following code but it not works.

Conversion failed when converting the nvarchar value '1,2,3' to data type int.

var result = dataContext.Customers.FromSql($"SELECT * FROM Customer WHERE Id IN ({string.Join(",", listOfInt)})")

Body:
This works for me:

var result = dataContext.Customers.FromSql(string.Format("SELECT * FROM Customer WHERE Id IN ({0})", string.Join(",", listOfInt)));

It does complain about injection vulnerability however but easy to sanitise a list of int at least.


问:
How to scrape the next page in ruby
I am trying to scrape the next page of the website called https://www.jobsatosu.com/postings/search. Because there are many jobs, there are many pages. Our team successfully scraped the first page like this:

```<code>def initialize
        @agent_menu = Mechanize.new
        @page = @agent_menu.get(PAGE_URL)
        @form = @page.forms[0]
</code>```

I am working on trying to scrape the next page. Also, we were told to use Nokogiri and Mechanize in Ruby. I just have to scrape the next page and do not have to parse it.

This is what I did:

```<code>def next_page
        @page_num += 1
        new_url = "https://www.jobsatosu.com/postings/search?page=#{@page_num}"
        @new_page = @agent_menu.get(new_url)
        @new_form = @new_page.forms[0]
    end
</code>```

I made one page_num for all to share. If someone calls the method, then it gets iterated by 1 and it gets the new URL, puts it in @new_page.
I haven't tested this out, but any thoughts on this code?

答:
You need to initialize @page_num = 0 before use

In the first time @page_num is nil so @page_num += 1 raises execption

NoMethodError: undefined method '+' for nil:NilClass

Actually you don't describe variable before using but in this case, you need to do

Title: How to scrape the next page in ruby

Body:
I am trying to scrape the next page of the website called https://www.jobsatosu.com/postings/search. Because there are many jobs, there are many pages. Our team successfully scraped the first page like this:

def initialize
        @agent_menu = Mechanize.new
        @page = @agent_menu.get(PAGE_URL)
        @form = @page.forms[0]

I am working on trying to scrape the next page. Also, we were told to use Nokogiri and Mechanize in Ruby. I just have to scrape the next page and do not have to parse it.

This is what I did:

def next_page
        @page_num += 1
        new_url = "https://www.jobsatosu.com/postings/search?page=#{@page_num}"
        @new_page = @agent_menu.get(new_url)
        @new_form = @new_page.forms[0]
    end

I made one page_num for all to share. If someone calls the method, then it gets iterated by 1 and it gets the new URL, puts it in @new_page.
I haven't tested this out, but any thoughts on this code?


问:
Angular PWA error Site cannot be installed: no matching service worker detected
I have a website (Angular 9.0.1), I added the @angular/pwa package to turn it into a PWA and it's not working.

The website is on production site but with test data right now on https://new.indomablestore.com

I have checked that the required files (manifest.webmanifest, ngsw.json, ngsw-worker.js) are on the root folder.
I have checked that the index.html file points correctly to the manifest, and it is shown on Chrome Devtools Application tab.

But on the Installability section it says: No matching service worker detected. You may need to reload the page, or check that the service worker for the current page also controls the start URL from the manifest.

I have also checked that the app.module.ts file has this line:

ServiceWorkerModule.register('ngsw-worker.js', { enabled: environment.production })

And I haven't modified any of the PWA files, I let Angular CLI build them.

Any help would be appreciated as the site is going to go live soon and this is the last thing on my list :)

Thanks!

UPDATE: The manifest looks like this:

```<code>  "name": "Indomable",
  "short_name": "Indomable",
  "theme_color": "#1976d2",
  "background_color": "#fafafa",
  "display": "standalone",
  "scope": "/",
  "start_url": "/",
  "icons": [
    ...
  ]
}
</code>```

And the Service Worker is registered on the app.module like this:

```<code>@NgModule({
  declarations: [
    AppComponent,
    ...PAGES,
    ...COMPONENTS,
    ...PIPES
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    FormsModule,
    routing,
    NgxPayPalModule,
    ServiceWorkerModule.register('./ngsw-worker.js', { enabled: environment.production, scope: './' })
  ],
  ...
</code>```

Thanks for the quick answers anyway :)

答:
I found the answer. Angular waits until the application is "stable" before it registers the service worker. The app has an AJAX call on startup that checks against the server if there are new products, photos... and apparently this makes Angular think it isn't stable so it does not even call the service worker registration.

As pointed out in this Stack Overflow answer the registration has an option named "registrationStrategy" and I can set it to "registerImmediately".

```<code>ServiceWorkerModule.register('ngsw-worker.js',
    {
       enabled: environment.production,
       registrationStrategy: 'registerImmediately'
    }
)
</code>```

And it just started working :)

Anyway, thanks for the help and the quick answers.

Body:
I have a website (Angular 9.0.1), I added the @angular/pwa package to turn it into a PWA and it's not working.

The website is on production site but with test data right now on https://new.indomablestore.com

I have checked that the required files (manifest.webmanifest, ngsw.json, ngsw-worker.js) are on the root folder.
I have checked that the index.html file points correctly to the manifest, and it is shown on Chrome Devtools Application tab.

But on the Installability section it says: No matching service worker detected. You may need to reload the page, or check that the service worker for the current page also controls the start URL from the manifest.

I have also checked that the app.module.ts file has this line:

ServiceWorkerModule.register('ngsw-worker.js', { enabled: environment.production })

And I haven't modified any of the PWA files, I let Angular CLI build them.

Any help would be appreciated as the site is going to go live soon and this is the last thing on my list :)

Thanks!

UPDATE: The manifest looks like this:

  "name": "Indomable",
  "short_name": "Indomable",
  "theme_color": "#1976d2",
  "background_color": "#fafafa",
  "display": "standalone",
  "scope": "/",
  "start_url": "/",
  "icons": [
    ...
  ]
}

And the Service Worker is registered on the app.module like this:

@NgModule({
  declarations: [
    AppComponent,
    ...PAGES,
    ...COMPONENTS,
    ...PIPES
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    FormsModule,
    routing,
    NgxPayPalModule,
    ServiceWorkerModule.register('./ngsw-worker.js', { enabled: environment.production, scope: './' })
  ],
  ...

Thanks for the quick answers anyway :)

Body:
I found the answer. Angular waits until the application is "stable" before it registers the service worker. The app has an AJAX call on startup that checks against the server if there are new products, photos... and apparently this makes Angular think it isn't stable so it does not even call the service worker registration.

As pointed out in this Stack Overflow answer the registration has an option named "registrationStrategy" and I can set it to "registerImmediately".

ServiceWorkerModule.register('ngsw-worker.js',
    {
       enabled: environment.production,
       registrationStrategy: 'registerImmediately'
    }
)

And it just started working :)

Anyway, thanks for the help and the quick answers.


问:
selenium find specific argument python
Hei there

I'm trying to automatically push a button, but I don't seem to find the right location with Selenium selectors. It's the one nested and called 'submit'. What do I do?

```<code><button class="pull-right" type="submit"><span>Resultate anzeigen</span></button>
</code>```

Thanks!

答:
Can you try this xpath.
//button[@class='pull-right']//span[contains(text(), 'Resultate')]</p>

Title: selenium find specific argument python

Body:
Hei there

I'm trying to automatically push a button, but I don't seem to find the right location with Selenium selectors. It's the one nested and called 'submit'. What do I do?

<button class="pull-right" type="submit">Resultate anzeigen</button>

Thanks!


问:
Correct method for setKeepScreenOn / FLAG_KEEP_SCREEN_ON
I am using the method setKeepScreenOn(true) and haven't been able to figure out how to call this in relation to the current Activity (which has a content view set).  I've been able to get it to work by calling it on one of my buttons which is always present in the view, but this feels wrong - and I'm sure there must be a way to get around this.  I tried referencing the current focus like this:

```<code>getCurrentFocus().setKeepScreenOn(true);
</code>```

but that threw a NullPointerException.  Maybe there was no current focus.
So, can anyone tell me how I can reference the view class which I am working inside?  Thanks :)

答: Set android:keepScreenOn in XML

ContentLicense: CC BY-SA 2.5

Body:
I am using the method setKeepScreenOn(true) and haven't been able to figure out how to call this in relation to the current Activity (which has a content view set).  I've been able to get it to work by calling it on one of my buttons which is always present in the view, but this feels wrong - and I'm sure there must be a way to get around this.  I tried referencing the current focus like this:

getCurrentFocus().setKeepScreenOn(true);

but that threw a NullPointerException.  Maybe there was no current focus.
So, can anyone tell me how I can reference the view class which I am working inside?  Thanks :)

Body: Set android:keepScreenOn in XML


问:
Unity fresh Scene is too dark
When creating a new scene with the HDR Template,
the scene is completely dark compared to the sample scene.

Sample Scene:

New Scene:

even when adding the example assets to the new scene the scene is too dark:

Game View and Scene View look almost the same in this case aswell.

答:
After copying every single lighting setting from the sample scene into the new scene i still saw no changes.

So i tried a couple of things until i found the solution:

I needed to include the post processing volume into the new scene with following settings:

So i guess before dealing with any more hdr lighting stuff i should look into volumes, reflector probes and light probe groups.

Hope i could help you with that future unity game developer who stumbled upon the same issue.

Title: Unity fresh Scene is too dark


问:
Pass a set of Array to a new function for computing
It generates error.

```<code>  int main(void)
  {
     int Numbers[9]={1,2,3,4,5,6,7,8,9};
     printf("%i\n", SUM(Numbers[9]));
  }

  int SUM(int array[int n])
  {
     int sum = array[1]*2 + array[2]*3 + array[3]*4 + array[4]*6 + array[5]*6;
     return sum;
   }
</code>```

It says i have passed too many arguments to the function.

答:
You passing one int by Numbers[9]. You need to pass the array by passing the pointer to it. But actually a 1D array name is practically the pointer to the first element of the array. This will fix it:

```<code>  int main(void)
  {
     int Numbers[9]={1,2,3,4,5,6,7,8,9};
     printf("%i\n", SUM(Numbers)); // passing the pointer to the array
  }

  int SUM(int array[]) // int SUM(int *array) would also work
  {
     int sum = array[1]*2 + array[2]*3 + array[3]*4 + array[4]*6 + array[5]*6;
     return sum;
  }
</code>```

Note that usually you want to pass the size too so you can check bounds and thus avoiding over indexing the array.

Body:
It generates error.

  int main(void)
  {
     int Numbers[9]={1,2,3,4,5,6,7,8,9};
     printf("%i\n", SUM(Numbers[9]));
  }

  int SUM(int array[int n])
  {
     int sum = array[1]*2 + array[2]*3 + array[3]*4 + array[4]*6 + array[5]*6;
     return sum;
   }

It says i have passed too many arguments to the function.

Body:
You passing one int by Numbers[9]. You need to pass the array by passing the pointer to it. But actually a 1D array name is practically the pointer to the first element of the array. This will fix it:

  int main(void)
  {
     int Numbers[9]={1,2,3,4,5,6,7,8,9};
     printf("%i\n", SUM(Numbers)); // passing the pointer to the array
  }

  int SUM(int array[]) // int SUM(int *array) would also work
  {
     int sum = array[1]*2 + array[2]*3 + array[3]*4 + array[4]*6 + array[5]*6;
     return sum;
  }

Note that usually you want to pass the size too so you can check bounds and thus avoiding over indexing the array.


问:
Should I check the types of constructor arguments (and at other places too)?
Python discourages checking the types. But in many cases this may be useful:

Checking constructor arguments. e.g. checking foe Boolean, string, dict etc. If I don't and set the object's members to the arguments it will cause problems later.

Checking functions arguments.

In properties. If someone sets a wrong value or different type, I should respond quickly.

答:
It is often a good thing to do. Checking for explicit types is probably not so useful in Python (as others have said), but checking for legal values can be a good idea. The reason it's a good idea is that the software will fail closer to the source of the bug (it follows the Fail Fast Principle). Also, the checks act as documentation to other programmers and yourself. Even better, it is "executable documentation", which is good because it's documentation that can't lie.

A quick and dirty but reasonable way to check your arguments is to use assert:

```<code>def my_sqrt(x):
    assert x >= 0, "must be greater or equal to zero"
    # ...
</code>```

Asserting your arguments is a kind of poor man's Design by Contract. (You might like to look up Design by Contract; it is interesting.)

OwnerDisplayName: Xolve

Body:
It is often a good thing to do. Checking for explicit types is probably not so useful in Python (as others have said), but checking for legal values can be a good idea. The reason it's a good idea is that the software will fail closer to the source of the bug (it follows the Fail Fast Principle). Also, the checks act as documentation to other programmers and yourself. Even better, it is "executable documentation", which is good because it's documentation that can't lie.

A quick and dirty but reasonable way to check your arguments is to use assert:

def my_sqrt(x):
    assert x >= 0, "must be greater or equal to zero"
    # ...

Asserting your arguments is a kind of poor man's Design by Contract. (You might like to look up Design by Contract; it is interesting.)

OwnerDisplayName: dangph

LastEditorDisplayName: dangph


问:
"Insufficient priveleges to complete the operation", inspite of granting all necessary permissions
```<code>{"odata.error":{"code":"Authorization_RequestDenied",
"message":
{"lang":"en","value":"Insufficient privileges to complete the operation."},
"requestId":"b205e5d0-f929-418e-9153-f1994e2c0893",
"date":"2020-02-15T06:53:57"}
}
</code>```

I am able to retrieve the authentication token from the server and have granted all the permissions through the AAD but still I'm facing the same issue.
Would be great if someone could help me out.
I am using the Microsoft Graph API.

Below is the code that I am using

```<code>private const string clientID = "XXXX";
        private const string addInstance = "https://login.microsoftonline.com/{0}";
        private const string tenant = "XYZ";
        private const string resource = "https://graph.windows.net";
        private const string appKey = "appkey";
        static string authority = String.Format(CultureInfo.InvariantCulture, addInstance, tenant);

        private static HttpClient httpclient = new HttpClient();
        private static AuthenticationContext context = null;
        private static ClientCredential credential = null;

        static void Main(string[] args)
        {
            context = new AuthenticationContext(authority);
            credential = new ClientCredential(clientID,appKey);

            Task<string> token = GetToken();
            token.Wait();
            Console.WriteLine(token.Result);

            Task<string> users = GetUsers(token.Result);
            users.Wait();
            Console.WriteLine(users.Result);
            //Console.ReadLine();
        }

        private static async Task<string> GetUsers(string result)
        {
            string users = null;
            string queryString = "api-version=1.6";
            var uri = "https://graph.windows.net/ *The Microsoft 365 account assosciated with the tenant* /users?"+ queryString;
            httpclient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result);
            var getResult = await httpclient.GetAsync(uri);
            if (getResult != null)
            {
                users = await getResult.Content.ReadAsStringAsync();
            }
            return users;
        }

        private static async Task<string> GetToken()
        {
            AuthenticationResult result = null;
            string token = null;
            result = await context.AcquireTokenAsync(resource, credential);
            token = result.AccessToken;
            return token;
        }
    }
</code>```

答:
I have tried following way and perfectly worked for me.

```<code>       //Token Request End Point
        string tokenUrl = $"https://login.microsoftonline.com/yourTenant.onmicrosoft.com/oauth2/token";
        var tokenRequest = new HttpRequestMessage(HttpMethod.Post, tokenUrl);

        //I am Using client_credentials as It is mostly recommended
        tokenRequest.Content = new FormUrlEncodedContent(new Dictionary<string, string>
        {
            ["grant_type"] = "client_credentials",
            ["client_id"] = "b603c7be-a956_Your_Client_Id_a45996-e6921e61f36955",
            ["client_secret"] = "Vxf1SluKbgu4PF0loj_Your_Client_Secret_okjh8wL/yujh45lojhgg=",
            ["resource"] = "https://graph.windows.net"
        });

        dynamic json;
        AccessTokenClass results = new AccessTokenClass();
        HttpClient client = new HttpClient();

        var tokenResponse = await client.SendAsync(tokenRequest);

        json = await tokenResponse.Content.ReadAsStringAsync();
        results = JsonConvert.DeserializeObject<AccessTokenClass>(json);

        //New Block For Accessing Data from Microsoft Graph Rest API
        HttpClient _client = new HttpClient();

        HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, string.Format("https://graph.windows.net/YourTenant.onmicrosoft.com/users?api-version=1.6"));

        //Passing Token For this Request
        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", results.access_token);

        //Check The Response and extract response data
        HttpResponseMessage response = await _client.SendAsync(request);
        dynamic objGpraphUserList = JsonConvert.DeserializeObject<dynamic>(await response.Content.ReadAsStringAsync());

        return objGpraphUserList
</code>```

Class Used:

 public class AccessTokenClass
    {
        public string token_type { get; set; }
        public string expires_in { get; set; }
        public string resource { get; set; }
        public string access_token { get; set; }
    }
```

I got the User List as expected. See the screen shot.

Validate Your Token :

Check your token on https://jwt.io/ which should have User.ReadWrite.All or User.Read.All Application permission

Note:
  You should have following permission on Azure Active Directory Graph

For more information please refer to this official document

Hope this would help.

Body:
{"odata.error":{"code":"Authorization_RequestDenied",
"message":
{"lang":"en","value":"Insufficient privileges to complete the operation."},
"requestId":"b205e5d0-f929-418e-9153-f1994e2c0893",
"date":"2020-02-15T06:53:57"}
}

I am able to retrieve the authentication token from the server and have granted all the permissions through the AAD but still I'm facing the same issue.
Would be great if someone could help me out.
I am using the Microsoft Graph API.

Below is the code that I am using

private const string clientID = "XXXX";
        private const string addInstance = "https://login.microsoftonline.com/{0}";
        private const string tenant = "XYZ";
        private const string resource = "https://graph.windows.net";
        private const string appKey = "appkey";
        static string authority = String.Format(CultureInfo.InvariantCulture, addInstance, tenant);

        private static HttpClient httpclient = new HttpClient();
        private static AuthenticationContext context = null;
        private static ClientCredential credential = null;

        static void Main(string[] args)
        {
            context = new AuthenticationContext(authority);
            credential = new ClientCredential(clientID,appKey);

            Task<string> token = GetToken();
            token.Wait();
            Console.WriteLine(token.Result);

            Task<string> users = GetUsers(token.Result);
            users.Wait();
            Console.WriteLine(users.Result);
            //Console.ReadLine();
        }

        private static async Task<string> GetUsers(string result)
        {
            string users = null;
            string queryString = "api-version=1.6";
            var uri = "https://graph.windows.net/ *The Microsoft 365 account assosciated with the tenant* /users?"+ queryString;
            httpclient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result);
            var getResult = await httpclient.GetAsync(uri);
            if (getResult != null)
            {
                users = await getResult.Content.ReadAsStringAsync();
            }
            return users;
        }

        private static async Task<string> GetToken()
        {
            AuthenticationResult result = null;
            string token = null;
            result = await context.AcquireTokenAsync(resource, credential);
            token = result.AccessToken;
            return token;
        }
    }

Body:
I have tried following way and perfectly worked for me.

       //Token Request End Point
        string tokenUrl = $"https://login.microsoftonline.com/yourTenant.onmicrosoft.com/oauth2/token";
        var tokenRequest = new HttpRequestMessage(HttpMethod.Post, tokenUrl);

        //I am Using client_credentials as It is mostly recommended
        tokenRequest.Content = new FormUrlEncodedContent(new Dictionary<string, string>
        {
            ["grant_type"] = "client_credentials",
            ["client_id"] = "b603c7be-a956_Your_Client_Id_a45996-e6921e61f36955",
            ["client_secret"] = "Vxf1SluKbgu4PF0loj_Your_Client_Secret_okjh8wL/yujh45lojhgg=",
            ["resource"] = "https://graph.windows.net"
        });

        dynamic json;
        AccessTokenClass results = new AccessTokenClass();
        HttpClient client = new HttpClient();

        var tokenResponse = await client.SendAsync(tokenRequest);

        json = await tokenResponse.Content.ReadAsStringAsync();
        results = JsonConvert.DeserializeObject<AccessTokenClass>(json);

        //New Block For Accessing Data from Microsoft Graph Rest API
        HttpClient _client = new HttpClient();

        HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, string.Format("https://graph.windows.net/YourTenant.onmicrosoft.com/users?api-version=1.6"));

        //Passing Token For this Request
        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", results.access_token);

        //Check The Response and extract response data
        HttpResponseMessage response = await _client.SendAsync(request);
        dynamic objGpraphUserList = JsonConvert.DeserializeObject<dynamic>(await response.Content.ReadAsStringAsync());

        return objGpraphUserList

Class Used:

 public class AccessTokenClass
    {
        public string token_type { get; set; }
        public string expires_in { get; set; }
        public string resource { get; set; }
        public string access_token { get; set; }
    }

I got the User List as expected. See the screen shot.

Validate Your Token :

Check your token on https://jwt.io/ which should have User.ReadWrite.All or User.Read.All Application permission

Note:
  You should have following permission on Azure Active Directory Graph

For more information please refer to this official document

Hope this would help.


问:
Where to get JSON sample with data that repeats across objects
Where I can find a JSON sample, preferably an array of objects, in which the data repeats itself? Like an object with that has categories, cities, or information that repeats across other objects.

Something like

```<code>[
{name: 'jon', age: 33, city: 'Paris', job: 'teacher'},
{name: 'ana', age: 67, city: 'Boston', job: 'retired'},
{name: 'Eva', age: 33, city: 'Shangai', job: 'manager'},
{name: 'Lii', age: 25, city: 'Moscou', job: 'teacher'},
{name: 'Peter', age: 40, city: 'Paris', job: 'developer'},
]
</code>```

As you can see, some information there repeats itself, which enables the sorting of multiple keys. If the information doesn't repeat, I can sort only by one key.

I'm building an data table plugin that enables multiple sorting (sorting multiple columns). To perform the tests, I need a sample (at least 400 objects) that I can sort by multiple columns.

I have some JSON samples, but all values of each key in the objects are different, so I cannot know if my sorting is actually working.

答:
You could search for "JSON open data" and will get a list of sites that offer interesting JSON data that should meet your requirement.

https://catalog.data.gov/dataset?res_format=JSON

https://data.gov.ie/dataset?res_format=JSON

https://healthdata.gov/dataset/project-open-data-datajson-file-0

https://opendata.swiss/en/dataset?res_format=JSON

etc.

Body:
Where I can find a JSON sample, preferably an array of objects, in which the data repeats itself? Like an object with that has categories, cities, or information that repeats across other objects.

Something like

[
{name: 'jon', age: 33, city: 'Paris', job: 'teacher'},
{name: 'ana', age: 67, city: 'Boston', job: 'retired'},
{name: 'Eva', age: 33, city: 'Shangai', job: 'manager'},
{name: 'Lii', age: 25, city: 'Moscou', job: 'teacher'},
{name: 'Peter', age: 40, city: 'Paris', job: 'developer'},
]

As you can see, some information there repeats itself, which enables the sorting of multiple keys. If the information doesn't repeat, I can sort only by one key.

I'm building an data table plugin that enables multiple sorting (sorting multiple columns). To perform the tests, I need a sample (at least 400 objects) that I can sort by multiple columns.

I have some JSON samples, but all values of each key in the objects are different, so I cannot know if my sorting is actually working.


问:
R convert time (xx:xx:xx) to min. as.POSIXct returns error "character string is not in a standard unambiguous format"
I have some data about focus times in xx:xx:xx format that I would like to add together over several sessions. So I am trying to convert each of them to minutes or any format that can be summed and understood. I've tried as.POSIX.ct but I get the error in the title. I've also tried lubidate hms(day1)/60 and I get another error. Here's a shortened reproducible example.

```<code>day1 <- c("01:05:38", "00:56:54", "00:48:17")
day2 <- c("00:37:57", "00:21:09", "00:43:34")
day1convert <- as.numeric(as.POSIXct(day1), units = "mins")
</code>```

This returns the error: "Error in as.POSIXlt.character(x, tz, ...) :
  character string is not in a standard unambiguous format"

```<code>library(lubridate)
convert<-hms(day1)/60
</code>```

This returns the error:"Error in validObject(.Object) :
  invalid class “Period” object: periods must have integer values

Any help would be appreciated.

答:
1) chron::times Use chron times class. They can be added and if we convert them to numeric they are given in fractions of a day.

```<code>library(chron)

times(day1) + times(day2)
## [1] 01:43:35 01:18:03 01:31:51

as.numeric(times(day1) + times(day2))
## [1] 0.07193287 0.05420139 0.06378472
</code>```

2) data.table::as.ITime  Another possibility is data.table's ITime.   They can be added or converting to numeric gives seconds.

```<code>library(data.table)

as.ITime(day1) + as.ITime(day2)
## [1] "01:43:35" "01:18:03" "01:31:51"

as.numeric(as.ITime(day1) + as.ITime(day2))
## [1] 6215 4683 5511
</code>```

Body:
I have some data about focus times in xx:xx:xx format that I would like to add together over several sessions. So I am trying to convert each of them to minutes or any format that can be summed and understood. I've tried as.POSIX.ct but I get the error in the title. I've also tried lubidate hms(day1)/60 and I get another error. Here's a shortened reproducible example.

day1 <- c("01:05:38", "00:56:54", "00:48:17")
day2 <- c("00:37:57", "00:21:09", "00:43:34")
day1convert <- as.numeric(as.POSIXct(day1), units = "mins")

This returns the error: "Error in as.POSIXlt.character(x, tz, ...) :
  character string is not in a standard unambiguous format"

library(lubridate)
convert<-hms(day1)/60

This returns the error:"Error in validObject(.Object) :
  invalid class “Period” object: periods must have integer values

Any help would be appreciated.

Body:
1) chron::times Use chron times class. They can be added and if we convert them to numeric they are given in fractions of a day.

library(chron)

times(day1) + times(day2)
## [1] 01:43:35 01:18:03 01:31:51

as.numeric(times(day1) + times(day2))
## [1] 0.07193287 0.05420139 0.06378472

2) data.table::as.ITime  Another possibility is data.table's ITime.   They can be added or converting to numeric gives seconds.

library(data.table)

as.ITime(day1) + as.ITime(day2)
## [1] "01:43:35" "01:18:03" "01:31:51"

as.numeric(as.ITime(day1) + as.ITime(day2))
## [1] 6215 4683 5511


问:
What is the difference between Sessions and Cookies in PHP?
What is the distinction between Sessions and Cookies in PHP?

答:
Cookie

is a small amount of data saved in the browser (client-side)

can be set from PHP with setcookie and then will be sent to the client's browser (HTTP response header Set-cookie)

can be set directly client-side in Javascript: document.cookie = 'foo=bar';

if no expiration date is set, by default, it will expire when the browser is closed.

 Example: go on http://example.com, open the Console, do document.cookie = 'foo=bar';. Close the tab, reopen the same website, open the Console, do document.cookie: you will see foo=bar is still there. Now close the browser and reopen it, re-visit the same website, open the Console ; you will see document.cookie is empty.

you can also set a precise expiration date other than "deleted when browser is closed".

the cookies that are stored in the browser are sent to the server in the headers of every request of the same website (see Cookie). You can see this for example with Chrome by opening Developer tools > Network, click on the request, see Headers:

can be read client-side with document.cookie

can be read server-side with $_COOKIE['foo']

Bonus: it can also be set/get with another language than PHP. Example in Python with "bottle" micro-framework (see also here):

```<code>from bottle import get, run, request, response
@get('/')
def index():
    if request.get_cookie("visited"):
        return "Welcome back! Nice to see you again"
    else:
        response.set_cookie("visited", "yes")
        return "Hello there! Nice to meet you"
run(host='localhost', port=8080, debug=True, reloader=True)
</code>```

Session

is some data relative to a browser session saved server-side

each server-side language may implement it in a different way

in PHP, when session_start(); is called:

a random ID is generated by the server, e.g. jo96fme9ko0f85cdglb3hl6ah6

a file is saved on the server, containing the data: e.g. /var/lib/php5/sess_jo96fme9ko0f85cdglb3hl6ah6

the session ID is sent to the client in the HTTP response headers, using the traditional cookie mechanism detailed above: Set-Cookie: PHPSESSID=jo96fme9ko0f85cdglb3hl6ah6; path=/:

(it can also be be sent via the URL instead of cookie but not the default behaviour)

you can see the session ID on client-side with document.cookie:

the PHPSESSID cookie is set with no expiration date, thus it will expire when the browser is closed. Thus "sessions" are not valid anymore when the browser is closed / reopened.

can be set/read in PHP with $_SESSION

the client-side does not see the session data but only the ID: do this in index.php:

```<code><?php
session_start();
$_SESSION["abc"]="def";
?>
</code>```

The only thing that is seen on client-side is (as mentioned above) the session ID:

because of this, session is useful to store data that you don't want to be seen or modified by the client

you can totally avoid using sessions if you want to use your own database + IDs and send an ID/token to the client with a traditional Cookie

Body:
Cookie

is a small amount of data saved in the browser (client-side)

can be set from PHP with setcookie and then will be sent to the client's browser (HTTP response header Set-cookie)

can be set directly client-side in Javascript: document.cookie = 'foo=bar';

if no expiration date is set, by default, it will expire when the browser is closed.

 Example: go on http://example.com, open the Console, do document.cookie = 'foo=bar';. Close the tab, reopen the same website, open the Console, do document.cookie: you will see foo=bar is still there. Now close the browser and reopen it, re-visit the same website, open the Console ; you will see document.cookie is empty.

you can also set a precise expiration date other than "deleted when browser is closed".

the cookies that are stored in the browser are sent to the server in the headers of every request of the same website (see Cookie). You can see this for example with Chrome by opening Developer tools > Network, click on the request, see Headers:

can be read client-side with document.cookie

can be read server-side with $_COOKIE['foo']

Bonus: it can also be set/get with another language than PHP. Example in Python with "bottle" micro-framework (see also here):

from bottle import get, run, request, response
@get('/')
def index():
    if request.get_cookie("visited"):
        return "Welcome back! Nice to see you again"
    else:
        response.set_cookie("visited", "yes")
        return "Hello there! Nice to meet you"
run(host='localhost', port=8080, debug=True, reloader=True)

Session

is some data relative to a browser session saved server-side

each server-side language may implement it in a different way

in PHP, when session_start(); is called:

a random ID is generated by the server, e.g. jo96fme9ko0f85cdglb3hl6ah6

a file is saved on the server, containing the data: e.g. /var/lib/php5/sess_jo96fme9ko0f85cdglb3hl6ah6

the session ID is sent to the client in the HTTP response headers, using the traditional cookie mechanism detailed above: Set-Cookie: PHPSESSID=jo96fme9ko0f85cdglb3hl6ah6; path=/:

(it can also be be sent via the URL instead of cookie but not the default behaviour)

you can see the session ID on client-side with document.cookie:

the PHPSESSID cookie is set with no expiration date, thus it will expire when the browser is closed. Thus "sessions" are not valid anymore when the browser is closed / reopened.

can be set/read in PHP with $_SESSION

the client-side does not see the session data but only the ID: do this in index.php:

<?php
session_start();
$_SESSION["abc"]="def";
?>

The only thing that is seen on client-side is (as mentioned above) the session ID:

because of this, session is useful to store data that you don't want to be seen or modified by the client

you can totally avoid using sessions if you want to use your own database + IDs and send an ID/token to the client with a traditional Cookie


问:
Replace words in a string using reference from a dictionary
I have 2 dictionaries and want to replace values in the SQL query using as reference the other dictionary:

```<code>params_to_replace = {'tvchview': [{'source': 'table', 'channel': ['abc', 'abcd']}],
                     'tvtot_du': [{'source': 'table1', 'channel': ['ab']}]}

queries = {'tvchview': 'SELECT DISTINCT id, channel AS value FROM ${source} WHERE channel IN (${channel});',
           'tvtot_du': "SELECT id, SUM(duration) AS value FROM ${source} WHERE channel IN ('${channel}') GROUP BY id;"}
</code>```

The desired output is:

```<code>{'tvchview': 'SELECT DISTINCT id, channel AS value FROM table WHERE channel IN ('abc', 'abcd');',
 'tvtot_du': "SELECT id, SUM(duration) AS value FROM table1 WHERE channel IN ('ab') GROUP BY id;"}
</code>```

This is where I got, but don't know to to proceed. I am not sure if the last two lines are needed. I wanted to split the string and to replace the words, but not sure if this is the best way. Also there can be a case the references may be other words not only source and channel, basically anything from the dictionary should be replaced:

```<code>for k, v in queries.items():
    if k in params_to_replace:
        for v1 in params_to_replace.values():
            res = {k: v for d in v1 for k, v in d.items()}
            a = [el.split() for el in list(queries.values())]
</code>```

答:
Try this -

params_to_replace = {
        'tvchview': [{'source': 'table', 'channel': ['abc', 'abcd']}],
        'tvtot_du': [{'source': 'table1', 'channel': ['ab']}]
    }

queries = {
        'tvchview': 'SELECT DISTINCT id, channel AS value FROM ${source} WHERE channel IN (${channel});',
        'tvtot_du': "SELECT id, SUM(duration) AS value FROM ${source} WHERE channel IN ('${channel}') GROUP BY id;"
    }

expected_output = {
        'tvchview': "SELECT DISTINCT id, channel AS value FROM table WHERE channel IN ('abc', 'abcd');",
        'tvtot_du': "SELECT id, SUM(duration) AS value FROM table1 WHERE channel IN ('ab') GROUP BY id;"
    }

for k, v in params_to_replace.items():

    # Because the tvchview has => (${channel}) and
    # The tvtot_du has => ('${channel}') in the queries dictionary
    if k == 'tvtot_du':
        queries[k] = queries[k].replace("${source}", v[0]['source']) \
                    .replace("${channel}", ", ".join(item for item in v[0]['channel']))
    else:
        queries[k] = queries[k].replace("${source}", v[0]['source']) \
                    .replace("${channel}", ", ".join("'" + item + "'" for item in v[0]['channel']))

print(queries == expected_output)
```

Body:
I have 2 dictionaries and want to replace values in the SQL query using as reference the other dictionary:

params_to_replace = {'tvchview': [{'source': 'table', 'channel': ['abc', 'abcd']}],
                     'tvtot_du': [{'source': 'table1', 'channel': ['ab']}]}

queries = {'tvchview': 'SELECT DISTINCT id, channel AS value FROM ${source} WHERE channel IN (${channel});',
           'tvtot_du': "SELECT id, SUM(duration) AS value FROM ${source} WHERE channel IN ('${channel}') GROUP BY id;"}

The desired output is:

{'tvchview': 'SELECT DISTINCT id, channel AS value FROM table WHERE channel IN ('abc', 'abcd');',
 'tvtot_du': "SELECT id, SUM(duration) AS value FROM table1 WHERE channel IN ('ab') GROUP BY id;"}

This is where I got, but don't know to to proceed. I am not sure if the last two lines are needed. I wanted to split the string and to replace the words, but not sure if this is the best way. Also there can be a case the references may be other words not only source and channel, basically anything from the dictionary should be replaced:

for k, v in queries.items():
    if k in params_to_replace:
        for v1 in params_to_replace.values():
            res = {k: v for d in v1 for k, v in d.items()}
            a = [el.split() for el in list(queries.values())]


问:
Pass string class variable by reference in C++
Look at the following code:

```<code>#include <iostream>
#include <string>
using namespace std;
void reverseStr(string arr, int start, int end)
{
    while (start < end)
    {
        swap(arr[start], arr[end]);
        ++start;
        --end;
    }
}
int main()
{
    string str = "CPP";
    reverseStr(str, 0, 3);
    cout << str;
    return 0;
}
</code>```

The output is CPP, while PCC is expected.

Question: How to pass string by reference in C++? Are strings a normal array? If yes then the reference must be passed automatically, while it just creates a copy in the formal parameters.

My question is that why I have to use my function like void reverseStr(string &arr, int start, int end) instead of just void reverseStr(string arr, int start, int end). Why I have to use extra & informal parameters? Aren't string variables just other arrays?

答:
The syntax for references in C++ is

```<code>void reverseStr(string &arr, int start, int end);
</code>```

You can think about arr as a pointer, which is automatically dereferenced.

More information about references here.

Body:
Look at the following code:

#include <iostream>
#include <string>
using namespace std;
void reverseStr(string arr, int start, int end)
{
    while (start < end)
    {
        swap(arr[start], arr[end]);
        ++start;
        --end;
    }
}
int main()
{
    string str = "CPP";
    reverseStr(str, 0, 3);
    cout << str;
    return 0;
}

The output is CPP, while PCC is expected.

Question: How to pass string by reference in C++? Are strings a normal array? If yes then the reference must be passed automatically, while it just creates a copy in the formal parameters.

My question is that why I have to use my function like void reverseStr(string &arr, int start, int end) instead of just void reverseStr(string arr, int start, int end). Why I have to use extra & informal parameters? Aren't string variables just other arrays?

Body:
The syntax for references in C++ is

void reverseStr(string &arr, int start, int end);

You can think about arr as a pointer, which is automatically dereferenced.

More information about references here.


问:
round to higher multiple of 5
i am trying to round values to it's higher multiple of 5
For example:</p>

```<code>df
values    rounded_values (expected column)
    10                10
    11                15
    13                15
    22                25
    21                25
    34                35
    35                35
</code>```

答:
This can be done simply, by first dividing by 5, then calling math.ceil, then multiplying by 5:

```<code>>>>import math
>>>round5 = lambda n: math.ceil(n / 5) * 5
>>> round5(22)
25
>>> round5(21)
25
>>> round5(35)
35
>>> round5(10)
10
>>> round5(11)
15
>>> round5(15)
15

</code>```

Title: round to higher multiple of 5

Body:
i am trying to round values to it's higher multiple of 5
For example:

df
values    rounded_values (expected column)
    10                10
    11                15
    13                15
    22                25
    21                25
    34                35
    35                35

Body:
This can be done simply, by first dividing by 5, then calling math.ceil, then multiplying by 5:

>>>import math
>>>round5 = lambda n: math.ceil(n / 5) * 5
>>> round5(22)
25
>>> round5(21)
25
>>> round5(35)
35
>>> round5(10)
10
>>> round5(11)
15
>>> round5(15)
15


问:
Is DI the only solution to Singleton and/or static objects?
I have been told that Singletons are hard to test.

http://misko.hevery.com/2008/08/17/singletons-are-pathological-liars/

http://misko.hevery.com/code-reviewers-guide/flaw-brittle-global-state-singletons/

I have been told that Static methods/objects are no good either.

http://misko.hevery.com/2008/12/15/static-methods-are-death-to-testability/

So basically the only solution appears to be dependency injection.

But ... I really can't get used to DI, take this example:

In my framework I have a class that manages SQL. This class (and many other of my framework) uses a singleton Logger to logs message (and many other helpers).

With DI my code would turn to:

```<code>global $logger; //> consider i have been instanciated it at the start of my fw

$query = new PreparedQuery($logger);
$query->prepare() etc.
</code>```

Now that doesn't seem too bad. But consider a page that needs many queries I believe it's pretty redundant to have to write everytime $logger in the constructor, especially if you consider if PreparedQuery needed many other dependencies in the constructor.

The only solution to avoid singleton that I have found is to use a method (or just a simple function) in the main application that stores every references to this helper objects (Service Locator/Container) but this doens't solve the problem of hiding the dependencies

So in your experience other than DI what is a good pattern to use?

Solution:

For everyone interesetd the creator of PHPunit explains how to solve the Singleton problem (and how to solve static methods testing problem with PHP 5.3)

(singleton) http://sebastian-bergmann.de/archives/882-Testing-Code-That-Uses-Singletons.html

(static) http://sebastian-bergmann.de/archives/883-Stubbing-and-Mocking-Static-Methods.html

Pretty interesting read if you ask me.

答:
Well, in this case, I would build a builder (or factory) instead. So your factory would inject the dependency for you.  That way you can also avoid your globals:

```<code>class PreparedQueryFactory {
    protected $logger = null;
    public function __construct($loggger) {
        $this->logger = $logger;
    }
    public function create() {
        return new PreparedQuery($this->logger);
    }
}
</code>```

That way, you do once:

```<code>$factory = new PreparedQueryFactory($logger);
</code>```

Then any time you need a new query, just call:

```<code>$query = $factory->create();
</code>```

Now, this is a very simple example.  But you could add all sorts of complex logic if you need.  But the point is, by avoiding new in your code, you also avoid managing the dependencies.  So instead, you can pass the factory(ies) around as needed.

The benefit, is that all of this is 100% testable, since everything is injected everywhere (as opposed to using globals).

You can also use a registry (otherwise known as Service Container, or DI Container), but be sure you're injecting the registry in.

Body:
I have been told that Singletons are hard to test.

http://misko.hevery.com/2008/08/17/singletons-are-pathological-liars/

http://misko.hevery.com/code-reviewers-guide/flaw-brittle-global-state-singletons/

I have been told that Static methods/objects are no good either.

http://misko.hevery.com/2008/12/15/static-methods-are-death-to-testability/

So basically the only solution appears to be dependency injection.

But ... I really can't get used to DI, take this example:

In my framework I have a class that manages SQL. This class (and many other of my framework) uses a singleton Logger to logs message (and many other helpers).

With DI my code would turn to:

global $logger; //> consider i have been instanciated it at the start of my fw

$query = new PreparedQuery($logger);
$query->prepare() etc.

Now that doesn't seem too bad. But consider a page that needs many queries I believe it's pretty redundant to have to write everytime $logger in the constructor, especially if you consider if PreparedQuery needed many other dependencies in the constructor.

The only solution to avoid singleton that I have found is to use a method (or just a simple function) in the main application that stores every references to this helper objects (Service Locator/Container) but this doens't solve the problem of hiding the dependencies

So in your experience other than DI what is a good pattern to use?

Solution:

For everyone interesetd the creator of PHPunit explains how to solve the Singleton problem (and how to solve static methods testing problem with PHP 5.3)

(singleton) http://sebastian-bergmann.de/archives/882-Testing-Code-That-Uses-Singletons.html

(static) http://sebastian-bergmann.de/archives/883-Stubbing-and-Mocking-Static-Methods.html

Pretty interesting read if you ask me.

Body:
Well, in this case, I would build a builder (or factory) instead. So your factory would inject the dependency for you.  That way you can also avoid your globals:

class PreparedQueryFactory {
    protected $logger = null;
    public function __construct($loggger) {
        $this->logger = $logger;
    }
    public function create() {
        return new PreparedQuery($this->logger);
    }
}

That way, you do once:

$factory = new PreparedQueryFactory($logger);

Then any time you need a new query, just call:

$query = $factory->create();

Now, this is a very simple example.  But you could add all sorts of complex logic if you need.  But the point is, by avoiding new in your code, you also avoid managing the dependencies.  So instead, you can pass the factory(ies) around as needed.

The benefit, is that all of this is 100% testable, since everything is injected everywhere (as opposed to using globals).

You can also use a registry (otherwise known as Service Container, or DI Container), but be sure you're injecting the registry in.


问:
error in build.gradle.kts script using extra property
below is a small (build.gradle.kts) script which gives at line 9 (the classpath line) the error : Cannot get property 'kotlinVersion' on extra properties extension as it does not exist

```<code>buildscript {
    extra["kotlinVersion"] = "1.2.70"

    repositories {
        jcenter()
    }

    dependencies {
      classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:${extra["kotlinVersion"]}")
    }
}
</code>```

I do not understand why this error occur.

答:
This works for me: </p>

```<code>buildscript {
    extra["kotlin_version"] = "1.3.61"

    repositories {
        google()
        jcenter()

    }
    dependencies {
        classpath("com.android.tools.build:gradle:3.5.3")
        classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:${extra["kotlin_version"]}")
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()

    }
}
</code>```

Body:
below is a small (build.gradle.kts) script which gives at line 9 (the classpath line) the error : Cannot get property 'kotlinVersion' on extra properties extension as it does not exist

buildscript {
    extra["kotlinVersion"] = "1.2.70"

    repositories {
        jcenter()
    }

    dependencies {
      classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:${extra["kotlinVersion"]}")
    }
}

I do not understand why this error occur.

Body:
This works for me:

buildscript {
    extra["kotlin_version"] = "1.3.61"

    repositories {
        google()
        jcenter()

    }
    dependencies {
        classpath("com.android.tools.build:gradle:3.5.3")
        classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:${extra["kotlin_version"]}")
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()

    }
}


答:
Not exactly sure what is your expected output but you can try the following to get time in minutes.

```<code>library(lubridate)
period_to_seconds(hms(day1))/60
#[1] 65.63333 56.90000 48.28333
</code>```

If you want to convert time to POSIXct format

```<code>as.POSIXct(day1, format = "%T", tz = "UTC")
#[1] "2020-02-15 01:05:38 UTC" "2020-02-15 00:56:54 UTC" "2020-02-15 00:48:17 UTC"
</code>```

Title: R convert time (xx:xx:xx) to min. as.POSIXct returns error "character string is not in a standard unambiguous format"

Body:
Not exactly sure what is your expected output but you can try the following to get time in minutes.

library(lubridate)
period_to_seconds(hms(day1))/60
#[1] 65.63333 56.90000 48.28333

If you want to convert time to POSIXct format

as.POSIXct(day1, format = "%T", tz = "UTC")
#[1] "2020-02-15 01:05:38 UTC" "2020-02-15 00:56:54 UTC" "2020-02-15 00:48:17 UTC"


问:
How does ArrayList work?
What data structure does an ArrayList use internally?</p>

答:
as i understand is that

ArrayList class implements List interface and
  (as interface only extends other interface)
  List interface extends Collection interface.
  while talking about arraylist when we initialize in memory it reserve by default space 10 > and create array of Integer which you normally use. when this this array is full then the another array of interger is created which is greater then default size.

```<code>List<Integer> list = new ArrayList<>();
</code>```

now in memory as => Integer[] list = new Integer[10];

now suppose that you enter 1,2,3,4,5,6,7,8,9,10 array is full now and what happen when you enter 11 in the memory another array of Integer is created which is greater then by default and all element in old array is copied in new array. Internally arraylist user Object[] array.

thats how arrayList work

Title: How does ArrayList work?

Body:
as i understand is that

ArrayList class implements List interface and
  (as interface only extends other interface)
  List interface extends Collection interface.
  while talking about arraylist when we initialize in memory it reserve by default space 10 > and create array of Integer which you normally use. when this this array is full then the another array of interger is created which is greater then default size.

List<Integer> list = new ArrayList<>();

now in memory as => Integer[] list = new Integer[10];

now suppose that you enter 1,2,3,4,5,6,7,8,9,10 array is full now and what happen when you enter 11 in the memory another array of Integer is created which is greater then by default and all element in old array is copied in new array. Internally arraylist user Object[] array.

thats how arrayList work