问:
Sequential list with pairs of the same prefix
I have the simplest possible code for creating string with integer:

```<code>x = []
for i in range(6):
    x.append('a' + str(i))
</code>```

,witch creating that output:

```<code>['a0', 'a1', 'a2', 'a3', 'a4', 'a5']
</code>```

But how could the condition to create a list in this form look like:

```<code> ['a0', 'a0', 'a1', 'a1', 'a2', 'a2']
</code>```

I tried this way:

```<code>x = []
for i in range(6):
   if i%2==0:
       x.append('a' + str(i))
   else:
       x.append('a' + str(i-1))
</code>```

But this ['a0', 'a0', 'a2', 'a2', 'a4', 'a4'] is far from what I need.

Body:
I have the simplest possible code for creating string with integer:

x = []
for i in range(6):
    x.append('a' + str(i))

,witch creating that output:

['a0', 'a1', 'a2', 'a3', 'a4', 'a5']

But how could the condition to create a list in this form look like:

 ['a0', 'a0', 'a1', 'a1', 'a2', 'a2']

I tried this way:

x = []
for i in range(6):
   if i%2==0:
       x.append('a' + str(i))
   else:
       x.append('a' + str(i-1))

But this ['a0', 'a0', 'a2', 'a2', 'a4', 'a4'] is far from what I need.

Body:
x = []
for i in range(3):
    x.append('a' + str(i))
    x.append('a' + str(i))

Output

['a0', 'a0', 'a1', 'a1', 'a2', 'a2']


来源: stackexchange

问:
Android Studio 3.0 Canary 1 annotation processor error
Just upgraded to Android Studio 3.0, a project which was compiling before is throwing following error

Error:java.lang.RuntimeException: Annotation processors must now be
  declared explicitly.  The following dependencies in the compile
  classpath are found to contain annotation processors.  Please add them
  to the annotationProcessor configuration.

However, this following is not defined. here is how compile statements in my build.gradle looks like

```<code>compile('com.crashlytics.sdk.android:crashlytics:2.6.7@aar') {
    transitive = true;
}

compile 'com.android.support:support-v4:25.3.1'
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support:design:25.3.1'
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.2.0'
compile 'com.jakewharton.timber:timber:4.4.0'
compile 'io.reactivex:rxandroid:1.0.1'
compile 'io.reactivex:rxjava:1.0.14'
compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
compile 'com.jpardogo.googleprogressbar:library:1.2.0'
compile 'com.wang.avi:library:2.1.3'
compile 'link.fls:swipestack:0.3.0'
compile 'com.jakewharton:butterknife:8.4.0'
compile 'com.codemybrainsout.rating:ratingdialog:1.0.7'
compile 'org.greenrobot:greendao:3.2.0'
compile 'com.android.support.constraint:constraint-layout:1.0.0-beta5'
testCompile 'junit:junit:4.12'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.4.0'
provided 'org.projectlombok:lombok:1.12.6'
</code>```

答:
I have same problem with MPchart library, in build.gradle of MPchart project add this:

```<code>defaultConfig {
        ...
        javaCompileOptions {
            annotationProcessorOptions {
                includeCompileClasspath true
            }
        }
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Just upgraded to Android Studio 3.0, a project which was compiling before is throwing following error

Error:java.lang.RuntimeException: Annotation processors must now be
  declared explicitly.  The following dependencies in the compile
  classpath are found to contain annotation processors.  Please add them
  to the annotationProcessor configuration.

However, this following is not defined. here is how compile statements in my build.gradle looks like

compile('com.crashlytics.sdk.android:crashlytics:2.6.7@aar') {
    transitive = true;
}

compile 'com.android.support:support-v4:25.3.1'
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support:design:25.3.1'
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.2.0'
compile 'com.jakewharton.timber:timber:4.4.0'
compile 'io.reactivex:rxandroid:1.0.1'
compile 'io.reactivex:rxjava:1.0.14'
compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
compile 'com.jpardogo.googleprogressbar:library:1.2.0'
compile 'com.wang.avi:library:2.1.3'
compile 'link.fls:swipestack:0.3.0'
compile 'com.jakewharton:butterknife:8.4.0'
compile 'com.codemybrainsout.rating:ratingdialog:1.0.7'
compile 'org.greenrobot:greendao:3.2.0'
compile 'com.android.support.constraint:constraint-layout:1.0.0-beta5'
testCompile 'junit:junit:4.12'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.4.0'
provided 'org.projectlombok:lombok:1.12.6'

Body:
I have same problem with MPchart library, in build.gradle of MPchart project add this:

defaultConfig {
        ...
        javaCompileOptions {
            annotationProcessorOptions {
                includeCompileClasspath true
            }
        }
    }


答:
You're looking for zip, something like this:

```<code>>>> dict(zip(b, filter(None, a)))
{'43': 'test1', '17': 'test'}
</code>```

Take in mind this will give different results when run, as sets are unordered.

Title: Combine dictionary according to index

Body:
Let us Assume, I have a key value pair in python, such as the following.

a = ['', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', 'test1', 'test', '', '', '', '', '', '', '', '', '', '']

now I want to combine these values with:

b = {"18", "17", "16", "15", "14", "13", "12", "11", "21", "22", "23", "24", "25", "26", "27", "28","48", "47", "46", "45", "44", "43", "42", "41", "31", "32", "33", "34", "35", "36", "37", "38"}

Is there any way where I can combine the values from variable a against the \ b like result shown below:

c = {'44': ['test1'], '43': ['test2']}

thank you.

Body:
You're looking for zip, something like this:

>>> dict(zip(b, filter(None, a)))
{'43': 'test1', '17': 'test'}

Take in mind this will give different results when run, as sets are unordered.


问:
Java generics - Map of (typed) maps
I'm working on a (simple) caching solution of sorts, where a service can request a Cache object from a Map of caches. A Cache object works essentially just like a Map, too, with a key and a value and methods to access and store objects.

I came up with the following solution, but as you can see, it contains a cast (because get() can't know what the types of the nested object are supposed to be).

```<code>private final  Map<String, Cache<?, ?>> caches = new HashMap<String, Cache<?, ?>>();

public <K, V> Cache<K, V> getOrCreateCache(String identifier) {
    if (caches.containsKey(identifier)) {
        return (Cache<K, V>) caches.get(identifier);
    } else {
        Cache<K, V> cache = new CacheImpl<K, V>();
        caches.put(identifier, cache);
        return cache;
    }
}

private void test() {
    Cache<String, String> strCache = getOrCreateCache("string cache");
    strCache.set("key", "value");
}
</code>```

Now, my questions:

Is this a 'safe' approach, as long as classcastexceptions are handled properly? (probably going to catch those and pack them into a custom exception class)

Is there a 'safe' alternative? One with generics, if at all possible, because I like them and dislike casts.

(not directly related) Is this threadsafe? I assume not, but then, I'm no threading expert. Is it enough to just make the whole method synchronized, or would that (with half a dozen clients) cause too much overhead / locking? Is there a neat solution for that?

Edit: Woo, lots of answers, thanks! Editing here to describe an oddity I found while actually testing this:

```<code>    Cache<String, String> someCache = service.getOrCreateCache(cacheIdentifier);
    someCache.set("asdf", "sdfa");
    Cache<String, Integer> someCacheRetrievedAgain = service.getOrCreateCache(cacheIdentifier);
    System.out.println(someCacheRetrievedAgain.get("asdf")); // prints "sdfa". No errors whatsoever. Odd.
</code>```

答: There was a similar question yesterday. Your solution is not safe as there is nothing about the key that implies the type of the value. In other question the key was Callable<T> and the value was T. Thus a custom map could be made which insured type safety, and prevent the underlying map from being corrupted.

ContentLicense: CC BY-SA 2.5

Title: Java generics - Map of (typed) maps

Body:
I'm working on a (simple) caching solution of sorts, where a service can request a Cache object from a Map of caches. A Cache object works essentially just like a Map, too, with a key and a value and methods to access and store objects.

I came up with the following solution, but as you can see, it contains a cast (because get() can't know what the types of the nested object are supposed to be).

private final  Map<String, Cache<?, ?>> caches = new HashMap<String, Cache<?, ?>>();

public <K, V> Cache<K, V> getOrCreateCache(String identifier) {
    if (caches.containsKey(identifier)) {
        return (Cache<K, V>) caches.get(identifier);
    } else {
        Cache<K, V> cache = new CacheImpl<K, V>();
        caches.put(identifier, cache);
        return cache;
    }
}

private void test() {
    Cache<String, String> strCache = getOrCreateCache("string cache");
    strCache.set("key", "value");
}

Now, my questions:

Is this a 'safe' approach, as long as classcastexceptions are handled properly? (probably going to catch those and pack them into a custom exception class)

Is there a 'safe' alternative? One with generics, if at all possible, because I like them and dislike casts.

(not directly related) Is this threadsafe? I assume not, but then, I'm no threading expert. Is it enough to just make the whole method synchronized, or would that (with half a dozen clients) cause too much overhead / locking? Is there a neat solution for that?

Edit: Woo, lots of answers, thanks! Editing here to describe an oddity I found while actually testing this:

    Cache<String, String> someCache = service.getOrCreateCache(cacheIdentifier);
    someCache.set("asdf", "sdfa");
    Cache<String, Integer> someCacheRetrievedAgain = service.getOrCreateCache(cacheIdentifier);
    System.out.println(someCacheRetrievedAgain.get("asdf")); // prints "sdfa". No errors whatsoever. Odd.


问:
Failed to validate a newly established connection. happened on as400
I use the spring-boot first time.A sample page was working on db2 of windows.
I want use the db2 for as400,but a connection error happened when query.

console log

```<code>java.sql.SQLException: Failed to validate a newly established connection.
    at org.apache.tomcat.jdbc.pool.ConnectionPool.borrowConnection(ConnectionPool.java:837) ~[tomcat-jdbc-8.5.11.jar:na]
    at org.apache.tomcat.jdbc.pool.ConnectionPool.borrowConnection(ConnectionPool.java:648) ~[tomcat-jdbc-8.5.11.jar:na]
    at org.apache.tomcat.jdbc.pool.ConnectionPool.getConnection(ConnectionPool.java:198) ~[tomcat-jdbc-8.5.11.jar:na]
    at org.apache.tomcat.jdbc.pool.DataSourceProxy.getConnection(DataSourceProxy.java:132) ~[tomcat-jdbc-8.5.11.jar:na]
    at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.internal.AbstractSessionImpl$NonContextualJdbcConnectionAccess.obtainConnection(AbstractSessionImpl.java:386) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.acquireConnectionIfNeeded(LogicalConnectionManagedImpl.java:87) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.getPhysicalConnection(LogicalConnectionManagedImpl.java:112) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.internal.SessionImpl.connection(SessionImpl.java:489) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_131]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_131]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_131]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_131]
    at org.springframework.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:216) ~[spring-core-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:201) ~[spring-core-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect$HibernateConnectionHandle.doGetConnection(HibernateJpaDialect.java:414) ~[spring-orm-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.beginTransaction(HibernateJpaDialect.java:177) ~[spring-orm-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.orm.jpa.JpaTransactionManager.doBegin(JpaTransactionManager.java:380) ~[spring-orm-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:373) ~[spring-tx-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:447) ~[spring-tx-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:277) ~[spring-tx-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) ~[spring-tx-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136) ~[spring-tx-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:133) ~[spring-data-jpa-1.11.1.RELEASE.jar:na]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92) ~[spring-aop-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:57) ~[spring-data-commons-1.13.1.RELEASE.jar:na]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213) ~[spring-aop-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at com.sun.proxy.$Proxy72.findAll(Unknown Source) ~[na:na]
    at com.test.services.ProductServiceImpl.listAll(ProductServiceImpl.java:33) ~[classes/:na]
    at com.test.controllers.ProductController.listProducts(ProductController.java:44) ~[classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_131]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_131]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_131]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_131]
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205) ~[spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133) ~[spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:116) ~[spring-webmvc-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827) ~[spring-webmvc-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738) ~[spring-webmvc-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) ~[spring-webmvc-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963) ~[spring-webmvc-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897) ~[spring-webmvc-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) ~[spring-webmvc-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861) ~[spring-webmvc-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:622) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) ~[spring-webmvc-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) ~[tomcat-embed-websocket-8.5.11.jar:8.5.11]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:105) ~[spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81) ~[spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197) ~[spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:474) [tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79) [tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349) [tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:783) [tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:798) [tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1434) [tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.11.jar:8.5.11]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_131]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_131]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.11.jar:8.5.11]
    at java.lang.Thread.run(Thread.java:748) [na:1.8.0_131]
</code>```

application.properties

```<code>spring.datasource.driver-class-name=com.ibm.as400.access.AS400JDBCDriver
spring.datasource.url=jdbc:as400://192.168.11.123;naming=system;libraries=mylibs
spring.datasource.username=user
spring.datasource.password=123
spring.datasource.testWhileIdle=true
spring.datasource.validationQuery=select 1 from sysibm.sysdummy1
</code>```

Same error when using spring.datasource.validationQuery=select 1.
And the sql [select 1 from sysibm/sysdummy1] were successful excuted on pcom's strsql.

application.properties for db2 on windows.

```<code>spring.datasource.driver-class-name=com.ibm.db2.jcc.DB2Driver
spring.datasource.url=jdbc:db2://localhost:50000/testdb
spring.datasource.username=db2admin
spring.datasource.password=db2admin
spring.datasource.validationQuery=select 1
</code>```

答:
Since you are on tomcat, can you try with spring.datasource.tomcat.validationQuery
instead of  spring.datasource.validationQuery ?

see https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-1.4-Release-Notes#datasource-binding

Body:
I use the spring-boot first time.A sample page was working on db2 of windows.
I want use the db2 for as400,but a connection error happened when query.

console log

java.sql.SQLException: Failed to validate a newly established connection.
    at org.apache.tomcat.jdbc.pool.ConnectionPool.borrowConnection(ConnectionPool.java:837) ~[tomcat-jdbc-8.5.11.jar:na]
    at org.apache.tomcat.jdbc.pool.ConnectionPool.borrowConnection(ConnectionPool.java:648) ~[tomcat-jdbc-8.5.11.jar:na]
    at org.apache.tomcat.jdbc.pool.ConnectionPool.getConnection(ConnectionPool.java:198) ~[tomcat-jdbc-8.5.11.jar:na]
    at org.apache.tomcat.jdbc.pool.DataSourceProxy.getConnection(DataSourceProxy.java:132) ~[tomcat-jdbc-8.5.11.jar:na]
    at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.internal.AbstractSessionImpl$NonContextualJdbcConnectionAccess.obtainConnection(AbstractSessionImpl.java:386) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.acquireConnectionIfNeeded(LogicalConnectionManagedImpl.java:87) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.getPhysicalConnection(LogicalConnectionManagedImpl.java:112) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.internal.SessionImpl.connection(SessionImpl.java:489) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_131]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_131]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_131]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_131]
    at org.springframework.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:216) ~[spring-core-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:201) ~[spring-core-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect$HibernateConnectionHandle.doGetConnection(HibernateJpaDialect.java:414) ~[spring-orm-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.beginTransaction(HibernateJpaDialect.java:177) ~[spring-orm-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.orm.jpa.JpaTransactionManager.doBegin(JpaTransactionManager.java:380) ~[spring-orm-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:373) ~[spring-tx-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:447) ~[spring-tx-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:277) ~[spring-tx-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) ~[spring-tx-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136) ~[spring-tx-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:133) ~[spring-data-jpa-1.11.1.RELEASE.jar:na]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92) ~[spring-aop-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:57) ~[spring-data-commons-1.13.1.RELEASE.jar:na]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213) ~[spring-aop-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at com.sun.proxy.$Proxy72.findAll(Unknown Source) ~[na:na]
    at com.test.services.ProductServiceImpl.listAll(ProductServiceImpl.java:33) ~[classes/:na]
    at com.test.controllers.ProductController.listProducts(ProductController.java:44) ~[classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_131]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_131]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_131]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_131]
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205) ~[spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133) ~[spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:116) ~[spring-webmvc-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827) ~[spring-webmvc-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738) ~[spring-webmvc-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) ~[spring-webmvc-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963) ~[spring-webmvc-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897) ~[spring-webmvc-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) ~[spring-webmvc-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861) ~[spring-webmvc-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:622) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) ~[spring-webmvc-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) ~[tomcat-embed-websocket-8.5.11.jar:8.5.11]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:105) ~[spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81) ~[spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197) ~[spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:474) [tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79) [tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349) [tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:783) [tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:798) [tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1434) [tomcat-embed-core-8.5.11.jar:8.5.11]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.11.jar:8.5.11]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_131]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_131]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.11.jar:8.5.11]
    at java.lang.Thread.run(Thread.java:748) [na:1.8.0_131]

application.properties

spring.datasource.driver-class-name=com.ibm.as400.access.AS400JDBCDriver
spring.datasource.url=jdbc:as400://192.168.11.123;naming=system;libraries=mylibs
spring.datasource.username=user
spring.datasource.password=123
spring.datasource.testWhileIdle=true
spring.datasource.validationQuery=select 1 from sysibm.sysdummy1

Same error when using spring.datasource.validationQuery=select 1.
And the sql [select 1 from sysibm/sysdummy1] were successful excuted on pcom's strsql.

application.properties for db2 on windows.

spring.datasource.driver-class-name=com.ibm.db2.jcc.DB2Driver
spring.datasource.url=jdbc:db2://localhost:50000/testdb
spring.datasource.username=db2admin
spring.datasource.password=db2admin
spring.datasource.validationQuery=select 1


问:
Why and how the new keyword is being used with the already existing object of a class?
I'm using PHP 7.1.11

Consider below code :

```<code><?php
  class Test {
    static public function getNew() {
      return new static;
    }
  }

  class Child extends Test {}

  $obj1 = new Test();
  $obj2 = new $obj1;
?>
</code>```

Above code snippet has been taken from the PHP Manual.

From the above code I'm not able to understand why and how the new keyword is being used with the existing object of a class Test?

What's the intention behind doing like this?

Is this kind of usage of new keyword recommended?

If you really want to assign an already existing object of a class to some variable then can't it be done by simply writing the statement $obj2 = $obj1;?

What's the difference between below two statements? Which one is better and should be preferred?

```<code>$obj2 = new $obj1;
$obj2 = $obj1;
</code>```

答:
$obj2 = new $obj1; (creates a new instance of an object of the same class as $obj1) !== $obj2 = $obj1; (which creates $obj2 a reference to $obj1) !== $obj2 = clone $obj1; (which creates a new $obj2 with all the same property values as the original but as a new object instance)

For the 3 different cases that I cited in my comments above, let's create a simple class and instantiate it:

```<code>class User {
    public $firstname;
    public $lastname;

    public function __construct($firstname = 'TEST', $lastname = 'USER') {
        $this->firstname = $firstname;
        $this->lastname = $lastname;
    }

    public function getName() {
        return implode(' ', [$this->firstname, $this->lastname]);
    }
}

// original instance of a User
$obj1 = new User('Mark', 'Baker');
var_dump($obj1->getName());    // Mark Baker
</code>```

Now if we simply assign a new variable to the original, we're setting a pointer to the original (because it's an object), similar to a reference

```<code>// Simply set reference to our original User
$obj2 = $obj1;
var_dump($obj2->getName());    // Mark Baker

// And if we change properties of the instance, it changes for both because it's a reference
$obj2->firstname = 'David Mark';
var_dump($obj2->getName());    // David Mark Baker
var_dump($obj1->getName());    // David Mark Baker
</code>```

Any changes to either will be reflected in the other, because they are pointing to the same object instance

If we use clone, then we're creating a brand new object instance, but already populated with the property values from the original

```<code>// Clone the original object, this will create a new instance but will inherit property values of the original
$obj3 = clone $obj1;
var_dump($obj3->getName());    // David Mark Baker

// But changing properties of the clone won't affect the original in any way
$obj3->firstname = 'Mark';
var_dump($obj3->getName());    // Mark Baker
var_dump($obj1->getName());    // David Mark Baker
</code>```

Now if we change properties of the original, it won't affect the clone (or vice versa) because they are unique instances.

The we have the third case, where we're using new with an instance rather than  class name.

```<code>// Now create a new instance of the same type of object as your original User
// If we had mandatory constructor arguments, then we'd have to provide them $obj4 = new $obj1('a', 'b');
// But because they're optional, we  can get away with allowing the defaults

$obj4 = new $obj1;
var_dump($obj4->getName());    // TEST USER
</code>```

If we didn't know what class type $obj1 was, then it doesn't matter (though it would have been easy enough to find out). This creates a brand new instance of whatever class $obj1 was, without the property inheritance that clone gives, nor is it  reference like $obj2 = $obj1 gave..... it still calls the constructor, so we have to pass any mandatory constructor arguments (or get an error).

Body:
I'm using PHP 7.1.11

Consider below code :

<?php
  class Test {
    static public function getNew() {
      return new static;
    }
  }

  class Child extends Test {}

  $obj1 = new Test();
  $obj2 = new $obj1;
?>

Above code snippet has been taken from the PHP Manual.

From the above code I'm not able to understand why and how the new keyword is being used with the existing object of a class Test?

What's the intention behind doing like this?

Is this kind of usage of new keyword recommended?

If you really want to assign an already existing object of a class to some variable then can't it be done by simply writing the statement $obj2 = $obj1;?

What's the difference between below two statements? Which one is better and should be preferred?

$obj2 = new $obj1;
$obj2 = $obj1;

Body:
$obj2 = new $obj1; (creates a new instance of an object of the same class as $obj1) !== $obj2 = $obj1; (which creates $obj2 a reference to $obj1) !== $obj2 = clone $obj1; (which creates a new $obj2 with all the same property values as the original but as a new object instance)

For the 3 different cases that I cited in my comments above, let's create a simple class and instantiate it:

class User {
    public $firstname;
    public $lastname;

    public function __construct($firstname = 'TEST', $lastname = 'USER') {
        $this->firstname = $firstname;
        $this->lastname = $lastname;
    }

    public function getName() {
        return implode(' ', [$this->firstname, $this->lastname]);
    }
}

// original instance of a User
$obj1 = new User('Mark', 'Baker');
var_dump($obj1->getName());    // Mark Baker

Now if we simply assign a new variable to the original, we're setting a pointer to the original (because it's an object), similar to a reference

// Simply set reference to our original User
$obj2 = $obj1;
var_dump($obj2->getName());    // Mark Baker

// And if we change properties of the instance, it changes for both because it's a reference
$obj2->firstname = 'David Mark';
var_dump($obj2->getName());    // David Mark Baker
var_dump($obj1->getName());    // David Mark Baker

Any changes to either will be reflected in the other, because they are pointing to the same object instance

If we use clone, then we're creating a brand new object instance, but already populated with the property values from the original

// Clone the original object, this will create a new instance but will inherit property values of the original
$obj3 = clone $obj1;
var_dump($obj3->getName());    // David Mark Baker

// But changing properties of the clone won't affect the original in any way
$obj3->firstname = 'Mark';
var_dump($obj3->getName());    // Mark Baker
var_dump($obj1->getName());    // David Mark Baker

Now if we change properties of the original, it won't affect the clone (or vice versa) because they are unique instances.

The we have the third case, where we're using new with an instance rather than  class name.

// Now create a new instance of the same type of object as your original User
// If we had mandatory constructor arguments, then we'd have to provide them $obj4 = new $obj1('a', 'b');
// But because they're optional, we  can get away with allowing the defaults

$obj4 = new $obj1;
var_dump($obj4->getName());    // TEST USER

If we didn't know what class type $obj1 was, then it doesn't matter (though it would have been easy enough to find out). This creates a brand new instance of whatever class $obj1 was, without the property inheritance that clone gives, nor is it  reference like $obj2 = $obj1 gave..... it still calls the constructor, so we have to pass any mandatory constructor arguments (or get an error).


问:
How many levels of inheritance
Are there any best practices regarding the maximum depth of the inheritance hierarchy for a framework and guidelines when to use multiple levels of inheritance or join them in a single class?

Some references to established practices/examples that worked well in the Java world would be nice in the answers as this is from the perspective of the community and frameworks surrounding Java.

答:
You should think first about the clarity of the code you are writing.  Will having more level of depth make the code easier to read and maintain or will it make it harder.  Alot depending on the problem you are trying to solve.

As other posters suggest, you can make the depth either too shallow or too deep.  This is a goldilocks problem IMHO.

Title: How many levels of inheritance


问:
How to take CPU memory(UCHAR Buffer) in to GPU memory(ID3D11Texture2D Resource)
The code here will run in GPU and capture windows screen, it give us ID3D11Texture2D Resource. Using ID3D11DeviceContext::Map I taking GPU resource in to BYTE buffer from BYTEbuffer in to CPU Memory g_iMageBuffer its a UCHAR.

Now I want to do reverse engineering, I want to take g_iMageBufferbuffer(CPU Memory) in to ID3D11Texture2D(GPU memory). Please someone help me how to do this reverse engineering I am new to graphical part.

```<code>//Variable Declaration
IDXGIOutputDuplication* IDeskDupl;
IDXGIResource*          lDesktopResource = nullptr;
DXGI_OUTDUPL_FRAME_INFO IFrameInfo;
ID3D11Texture2D*        IAcquiredDesktopImage;
ID3D11Texture2D*        lDestImage;
ID3D11DeviceContext*    lImmediateContext;
UCHAR*                  g_iMageBuffer=nullptr;

//Screen capture start here
hr = lDeskDupl->AcquireNextFrame(20, &lFrameInfo, &lDesktopResource);

// >QueryInterface for ID3D11Texture2D
hr = lDesktopResource->QueryInterface(IID_PPV_ARGS(&lAcquiredDesktopImage));
lDesktopResource.Release();

// Copy image into GDI drawing texture
lImmediateContext->CopyResource(lDestImage,lAcquiredDesktopImage);
lAcquiredDesktopImage.Release();
lDeskDupl->ReleaseFrame();

// Copy GPU Resource to CPU
D3D11_TEXTURE2D_DESC desc;
lDestImage->GetDesc(&desc);
D3D11_MAPPED_SUBRESOURCE resource;
UINT subresource = D3D11CalcSubresource(0, 0, 0);
lImmediateContext->Map(lDestImage, subresource, D3D11_MAP_READ_WRITE, 0, &resource);

std::unique_ptr<BYTE> pBuf(new BYTE[resource.RowPitch*desc.Height]);
UINT lBmpRowPitch = lOutputDuplDesc.ModeDesc.Width * 4;
BYTE* sptr = reinterpret_cast<BYTE*>(resource.pData);
BYTE* dptr = pBuf.get() + resource.RowPitch*desc.Height - lBmpRowPitch;
UINT lRowPitch = std::min<UINT>(lBmpRowPitch, resource.RowPitch);

for (size_t h = 0; h < lOutputDuplDesc.ModeDesc.Height; ++h)
{
    memcpy_s(dptr, lBmpRowPitch, sptr, lRowPitch);
    sptr += resource.RowPitch;
    dptr -= lBmpRowPitch;
}

lImmediateContext->Unmap(lDestImage, subresource);
long g_captureSize=lRowPitch*desc.Height;
g_iMageBuffer= new UCHAR[g_captureSize];
g_iMageBuffer = (UCHAR*)malloc(g_captureSize);

//Copying to UCHAR buffer
memcpy(g_iMageBuffer,pBuf,g_captureSize);
</code>```

答:
You don't need reverse engineering. What you describe is called "loading a texture".

How to: Initialize a Texture Programmatically

How to: Initialize a Texture From a File

As you appear to be new to DirectX programming, consider working through the DirectX Tool Kit for DX11 tutorials. In particular, make sure you read the section on ComPtr and ThrowIfFailed.

Body:
The code here will run in GPU and capture windows screen, it give us ID3D11Texture2D Resource. Using ID3D11DeviceContext::Map I taking GPU resource in to BYTE buffer from BYTEbuffer in to CPU Memory g_iMageBuffer its a UCHAR.

Now I want to do reverse engineering, I want to take g_iMageBufferbuffer(CPU Memory) in to ID3D11Texture2D(GPU memory). Please someone help me how to do this reverse engineering I am new to graphical part.

//Variable Declaration
IDXGIOutputDuplication* IDeskDupl;
IDXGIResource*          lDesktopResource = nullptr;
DXGI_OUTDUPL_FRAME_INFO IFrameInfo;
ID3D11Texture2D*        IAcquiredDesktopImage;
ID3D11Texture2D*        lDestImage;
ID3D11DeviceContext*    lImmediateContext;
UCHAR*                  g_iMageBuffer=nullptr;

//Screen capture start here
hr = lDeskDupl->AcquireNextFrame(20, &lFrameInfo, &lDesktopResource);

// >QueryInterface for ID3D11Texture2D
hr = lDesktopResource->QueryInterface(IID_PPV_ARGS(&lAcquiredDesktopImage));
lDesktopResource.Release();

// Copy image into GDI drawing texture
lImmediateContext->CopyResource(lDestImage,lAcquiredDesktopImage);
lAcquiredDesktopImage.Release();
lDeskDupl->ReleaseFrame();

// Copy GPU Resource to CPU
D3D11_TEXTURE2D_DESC desc;
lDestImage->GetDesc(&desc);
D3D11_MAPPED_SUBRESOURCE resource;
UINT subresource = D3D11CalcSubresource(0, 0, 0);
lImmediateContext->Map(lDestImage, subresource, D3D11_MAP_READ_WRITE, 0, &resource);

std::unique_ptr<BYTE> pBuf(new BYTE[resource.RowPitch*desc.Height]);
UINT lBmpRowPitch = lOutputDuplDesc.ModeDesc.Width * 4;
BYTE* sptr = reinterpret_cast<BYTE*>(resource.pData);
BYTE* dptr = pBuf.get() + resource.RowPitch*desc.Height - lBmpRowPitch;
UINT lRowPitch = std::min<UINT>(lBmpRowPitch, resource.RowPitch);

for (size_t h = 0; h < lOutputDuplDesc.ModeDesc.Height; ++h)
{
    memcpy_s(dptr, lBmpRowPitch, sptr, lRowPitch);
    sptr += resource.RowPitch;
    dptr -= lBmpRowPitch;
}

lImmediateContext->Unmap(lDestImage, subresource);
long g_captureSize=lRowPitch*desc.Height;
g_iMageBuffer= new UCHAR[g_captureSize];
g_iMageBuffer = (UCHAR*)malloc(g_captureSize);

//Copying to UCHAR buffer
memcpy(g_iMageBuffer,pBuf,g_captureSize);


问:
Using separate components in a linear mat-horizontal-stepper
In Angular, is it possible to have a linear stepper where the individual steps are separate components? For example:

<mat-horizontal-stepper [linear]="isLinear">
    <mat-step [stepControl]="firstFormGroup" label="Some Form">
        <first-component></first-component>
    </mat-step>
    <mat-step [stepControl]="secondFormGroup" label="Another Form">
        <second-component></second-component>
    </mat-step>
    <mat-step [stepControl]="thirdFormGroup" label="Review">
        <third-component></third-component>
    </mat-step>
</mat-horizontal-stepper>
```

When I try this, I receive the following error upon hitting the matStepperNext button:

TypeError: Cannot read property 'invalid' of undefined.

答:
Ok, I think I see a few issues:

```<code><mat-horizontal-stepper [linear]="isLinear">
  <mat-step [stepControl]="foodFormGroup">
    <food-selection></food-selection>
  </mat-step>
  <mat-step [stepControl]="pieFormGroup">
    <pie-selection></pie-selection>
  </mat-step>
</mat-horizontal-stepper>
</code>```

foodFormGroup and pieFormGroup need to be defined in your tough-choice.component.ts file (Which, btw is misspelled in your example code)

Here's an example (from the docs) of how this might look:

```<code>import {Component} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';

/**
 * @title Stepper overview
 */
@Component({
  selector: 'stepper-overview-example',
  templateUrl: 'stepper-overview-example.html',
  styleUrls: ['stepper-overview-example.css']
})
export class StepperOverviewExample {
  isLinear = false;
  firstFormGroup: FormGroup;
  secondFormGroup: FormGroup;

  constructor(private _formBuilder: FormBuilder) { }

  ngOnInit() {
    this.firstFormGroup = this._formBuilder.group({
      firstCtrl: ['', Validators.required]
    });
    this.secondFormGroup = this._formBuilder.group({
      secondCtrl: ['', Validators.required]
    });
  }
}
</code>```

Also, I don't see a module.ts file in your example. That's where you would want to import your @angular/material modules, not in the component files.

I'd suggest just giving the Angular Material documentation a once-over.
https://material.angular.io/components/stepper/overview

Body:
In Angular, is it possible to have a linear stepper where the individual steps are separate components? For example:

<mat-horizontal-stepper [linear]="isLinear">
    <mat-step [stepControl]="firstFormGroup" label="Some Form">
        <first-component></first-component>
    </mat-step>
    <mat-step [stepControl]="secondFormGroup" label="Another Form">
        <second-component></second-component>
    </mat-step>
    <mat-step [stepControl]="thirdFormGroup" label="Review">
        <third-component></third-component>
    </mat-step>
</mat-horizontal-stepper>

When I try this, I receive the following error upon hitting the matStepperNext button:

TypeError: Cannot read property 'invalid' of undefined.

Body:
Ok, I think I see a few issues:

<mat-horizontal-stepper [linear]="isLinear">
  <mat-step [stepControl]="foodFormGroup">
    <food-selection></food-selection>
  </mat-step>
  <mat-step [stepControl]="pieFormGroup">
    <pie-selection></pie-selection>
  </mat-step>
</mat-horizontal-stepper>

foodFormGroup and pieFormGroup need to be defined in your tough-choice.component.ts file (Which, btw is misspelled in your example code)

Here's an example (from the docs) of how this might look:

import {Component} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';

/**
 * @title Stepper overview
 */
@Component({
  selector: 'stepper-overview-example',
  templateUrl: 'stepper-overview-example.html',
  styleUrls: ['stepper-overview-example.css']
})
export class StepperOverviewExample {
  isLinear = false;
  firstFormGroup: FormGroup;
  secondFormGroup: FormGroup;

  constructor(private _formBuilder: FormBuilder) { }

  ngOnInit() {
    this.firstFormGroup = this._formBuilder.group({
      firstCtrl: ['', Validators.required]
    });
    this.secondFormGroup = this._formBuilder.group({
      secondCtrl: ['', Validators.required]
    });
  }
}

Also, I don't see a module.ts file in your example. That's where you would want to import your @angular/material modules, not in the component files.

I'd suggest just giving the Angular Material documentation a once-over.
https://material.angular.io/components/stepper/overview


问:
What am i missing in this java regex for netbeans replace
I want to alter thousands of lines in a project, the line is always one of these formats and is always in the middle of a line.

link() accepts upto 3 parameters and can look like these:

```<code>$this->url->link('this/path')
$this->url->link('this/path', '', true)
$this->url->link('this/path', 'something=' . $something, true)
$this->url->link('this/path', 'something=' . $something . '&other=' . $other, true)
</code>```

I have a put together the following regex which correctly finds the lines I want as set out above with no problem.

```<code>// regex
\$this->url->link.*(, true)
</code>```

I want to be able to remove empty parameters from the line so basically this means:

If parameters two and three match '', true remove them, otherwise remove just paramter three: , true

I tried these:

```<code>\$this->url->link.*(.*)
\$this->url->link.*($1)
</code>```

答:
If I've understood your question, I'd use 2 different replacement operations, one to remove '',true and another to remove ,true.

deleting '', true

Search: \$this->url->link\((.+), '', true\)

Replace: \$this->url->link($1)

This should replace

= $this->url->link('some/thing', '', true)

with

= $this->url->link('some/thing')

deleting , true

Search: \$this->url->link\((.+),(.+), true\)

Replace: \$this->url->link($1,$2)

This should replace

=> $this->url->link('some/thing', 'variable data or empty', true)

with

=> $this->url->link('some/thing', 'variable data or empty')

and also works for

$this->url->link('some/thingthing', 'variable data', true)

replacing it with

$this->url->link('some/thingthing', 'variable data')

Body:
I want to alter thousands of lines in a project, the line is always one of these formats and is always in the middle of a line.

link() accepts upto 3 parameters and can look like these:

$this->url->link('this/path')
$this->url->link('this/path', '', true)
$this->url->link('this/path', 'something=' . $something, true)
$this->url->link('this/path', 'something=' . $something . '&other=' . $other, true)

I have a put together the following regex which correctly finds the lines I want as set out above with no problem.

// regex
\$this->url->link.*(, true)

I want to be able to remove empty parameters from the line so basically this means:

If parameters two and three match '', true remove them, otherwise remove just paramter three: , true

I tried these:

\$this->url->link.*(.*)
\$this->url->link.*($1)


问:
Sorting an array of structs (Cards)
I am making a blackjack game and have created an array to act as the hand the user is dealt. I want to be able to sort it so that the hand is sorted in numerical order so it will be simpler to determine what type of hand the user has. Here is my sturct for the cards:

```<code>struct ACard{
    int num;
    const char *pic;
};
</code>```

I want to sort the array by int num. I have tried to just use a simple insertion sort to complete the sort but I believe I need overload the operator to do so but I'm having trouble doing so as I've never overloaded a struct like this before. Here is what I have for the sort so far:

```<code>        int i,j;
        ACard key;
        for(int i = 1; i < 5; i++){
            key = userHand[i].num;
            j = i - 1;

            while(j >= 0 && userHand[j].num > key){
                userHand[j + 1] = userHand[j];
                j = j - 1;
            }
            userHand[j + 1] = key;
        }
</code>```

*Note userHand is the array of ACard's that I wish to sort.

答:
With STL containers you can use std::sort function. First two arguments define the range of elements to be sorted. Third argument defines a LessThan function used for your custom elements comparison (you can use lambda expression for that).

```<code>std::vector<ACard> userHand; // or another stl container

// initialize userHand somehow

std::sort(userHand.begin(), userHand.end(),
    [](const ACard& left, const ACard& right)
    {
        return left.num < right.num;
    });
</code>```

Title: Sorting an array of structs (Cards)

Body:
I am making a blackjack game and have created an array to act as the hand the user is dealt. I want to be able to sort it so that the hand is sorted in numerical order so it will be simpler to determine what type of hand the user has. Here is my sturct for the cards:

struct ACard{
    int num;
    const char *pic;
};

I want to sort the array by int num. I have tried to just use a simple insertion sort to complete the sort but I believe I need overload the operator to do so but I'm having trouble doing so as I've never overloaded a struct like this before. Here is what I have for the sort so far:

        int i,j;
        ACard key;
        for(int i = 1; i < 5; i++){
            key = userHand[i].num;
            j = i - 1;

            while(j >= 0 && userHand[j].num > key){
                userHand[j + 1] = userHand[j];
                j = j - 1;
            }
            userHand[j + 1] = key;
        }

*Note userHand is the array of ACard's that I wish to sort.

Body:
With STL containers you can use std::sort function. First two arguments define the range of elements to be sorted. Third argument defines a LessThan function used for your custom elements comparison (you can use lambda expression for that).

std::vector<ACard> userHand; // or another stl container

// initialize userHand somehow

std::sort(userHand.begin(), userHand.end(),
    [](const ACard& left, const ACard& right)
    {
        return left.num < right.num;
    });


问:
How to combine values of objects with common key in JavaScript?
I'm trying to merge some items in a JSON array, based on one of the keys. I want to group by the 'metric', and then I need to look at all the time/value data in 'rounded_counts', and if the times are the same, the values need to be added together. Here is the source data:

```<code>let sourceData = [
  {
    "metric": "Approved",
    "rounded_counts": [
      { "2017-11-16 15:10:00": 3 },
      { "2017-11-16 15:11:00": 5 }
    ]
  },
  {
    "metric": "Approved",
    "rounded_counts": [
      { "2017-11-16 15:10:00": 28 },
      { "2017-11-16 15:11:00": 28 }
    ]
  },
  {
    "metric": "Quarantine",
    "rounded_counts": [
      { "2017-11-16 15:10:00": 1 },
      { "2017-11-16 15:11:00": 2 }
    ]
  }
];
</code>```

and here is the desired output required for the Highcharts graphing library - notice how the 2 metrics called 'Approved' have had their values merged

Underscore, and/or ES6 can be used - Thanks in advance!

```<code>let chartData = [
  {
    "name": "Approved",
    "data": [
      [ "2017-11-16 15:10:00", 30 ],
      [ "2017-11-16 15:11:00", 33 ]
    ]
  },
  {
    "name": "Quarantine",
    "data": [
      [ "2017-11-16 15:10:00", 1 ],
      [ "2017-11-16 15:11:00", 2 ]
    ]
  }
]
</code>```

答:
Because of the structure of your data, it looks like you are going to need to use some nested loops and comparisons. I don't think you can do this with the built in array functions in javascript. Try this:

```<code>    let sourceData = [{
      "metric": "Approved",
      "rounded_counts": [{
        "2017-11-16 15:10:00": 3
      }, {
        "2017-11-16 15:11:00": 5
      }]
    }, {
      "metric": "Approved",
      "rounded_counts": [{
        "2017-11-16 15:10:00": 28
      }, {
        "2017-11-16 15:11:00": 28
      }]
    }, {
      "metric": "Quarantine",
      "rounded_counts": [{
        "2017-11-16 15:10:00": 1
      }, {
        "2017-11-16 15:11:00": 2
      }]
    }];
    let chartData = [];

    function isSame(obj1, obj2) {
      if (obj1.metric && obj1.metric == obj2.metric &&
         obj1.rounded_counts && obj2.rounded_counts &&
         obj1.rounded_counts.length == obj2.rounded_counts.length) {
        var roundedCountsDifferent = false;
        for (var i in obj1.rounded_counts) {
          var count = 0;
          var key1;
          var key2;
          for (var j in obj1.rounded_counts[i]) {
            key1 = j;
            break;
          }
          for (var j in obj2.rounded_counts[i]) {
            key2 = j;
            break;
          }
          roundedCountsDifferent = key1 != key2;
          return !roundedCountsDifferent;
        }
      }
      return false;
    }
    for (var i in sourceData) {
      var source = sourceData[i];
      var existingChart = null;
      for (var j in chartData) {
        if (isSame(source, chartData[j])) {
          existingChart = chartData[j];
          for (var k in source.rounded_counts) {
            var key;
            var val;
            for (var kv in source.rounded_counts[k]) {
              val = source.rounded_counts[k][kv];
              break;
            }
            for (var kv in existingChart.rounded_counts[k]) {
              existingChart.rounded_counts[k][kv] += val;
              break;
            }
          }
        }
      }
      if (!existingChart) {
        chartData.push(source);
      }
    }
    console.log(chartData);
</code>```

Working fiddle:
https://jsfiddle.net/h1n70m7s/1/

Body:
I'm trying to merge some items in a JSON array, based on one of the keys. I want to group by the 'metric', and then I need to look at all the time/value data in 'rounded_counts', and if the times are the same, the values need to be added together. Here is the source data:

let sourceData = [
  {
    "metric": "Approved",
    "rounded_counts": [
      { "2017-11-16 15:10:00": 3 },
      { "2017-11-16 15:11:00": 5 }
    ]
  },
  {
    "metric": "Approved",
    "rounded_counts": [
      { "2017-11-16 15:10:00": 28 },
      { "2017-11-16 15:11:00": 28 }
    ]
  },
  {
    "metric": "Quarantine",
    "rounded_counts": [
      { "2017-11-16 15:10:00": 1 },
      { "2017-11-16 15:11:00": 2 }
    ]
  }
];

and here is the desired output required for the Highcharts graphing library - notice how the 2 metrics called 'Approved' have had their values merged

Underscore, and/or ES6 can be used - Thanks in advance!

let chartData = [
  {
    "name": "Approved",
    "data": [
      [ "2017-11-16 15:10:00", 30 ],
      [ "2017-11-16 15:11:00", 33 ]
    ]
  },
  {
    "name": "Quarantine",
    "data": [
      [ "2017-11-16 15:10:00", 1 ],
      [ "2017-11-16 15:11:00", 2 ]
    ]
  }
]

Body:
Because of the structure of your data, it looks like you are going to need to use some nested loops and comparisons. I don't think you can do this with the built in array functions in javascript. Try this:

    let sourceData = [{
      "metric": "Approved",
      "rounded_counts": [{
        "2017-11-16 15:10:00": 3
      }, {
        "2017-11-16 15:11:00": 5
      }]
    }, {
      "metric": "Approved",
      "rounded_counts": [{
        "2017-11-16 15:10:00": 28
      }, {
        "2017-11-16 15:11:00": 28
      }]
    }, {
      "metric": "Quarantine",
      "rounded_counts": [{
        "2017-11-16 15:10:00": 1
      }, {
        "2017-11-16 15:11:00": 2
      }]
    }];
    let chartData = [];

    function isSame(obj1, obj2) {
      if (obj1.metric && obj1.metric == obj2.metric &&
         obj1.rounded_counts && obj2.rounded_counts &&
         obj1.rounded_counts.length == obj2.rounded_counts.length) {
        var roundedCountsDifferent = false;
        for (var i in obj1.rounded_counts) {
          var count = 0;
          var key1;
          var key2;
          for (var j in obj1.rounded_counts[i]) {
            key1 = j;
            break;
          }
          for (var j in obj2.rounded_counts[i]) {
            key2 = j;
            break;
          }
          roundedCountsDifferent = key1 != key2;
          return !roundedCountsDifferent;
        }
      }
      return false;
    }
    for (var i in sourceData) {
      var source = sourceData[i];
      var existingChart = null;
      for (var j in chartData) {
        if (isSame(source, chartData[j])) {
          existingChart = chartData[j];
          for (var k in source.rounded_counts) {
            var key;
            var val;
            for (var kv in source.rounded_counts[k]) {
              val = source.rounded_counts[k][kv];
              break;
            }
            for (var kv in existingChart.rounded_counts[k]) {
              existingChart.rounded_counts[k][kv] += val;
              break;
            }
          }
        }
      }
      if (!existingChart) {
        chartData.push(source);
      }
    }
    console.log(chartData);

Working fiddle:
https://jsfiddle.net/h1n70m7s/1/


问:
Error During File upload in Express.js using Multer
I am learning Node.js from a book "Web Development with Nodejs and MongoDB" and is Stuck at a point where I have to upload a Image using Multer.
The Code goes like this :-

Below is My Configure.js file :

```<code>var path = require('path'),
routes = require('./routes'),
exphbs = require('express-handlebars'),
express = require('express'),
bodyParser = require('body-parser'),
cookieParser = require('cookie-parser'),
morgan = require('morgan'),
methodOverride = require('method-override'),
errorHandler = require('errorhandler');
multer = require('multer');
moment = require('moment');
var upload = multer({ dest: './public/upload/temp' });
module.exports = function(app) {
app.use(morgan('dev'));
app.use(methodOverride());
app.use(cookieParser('some-secret-value-here'));
routes(app);

app.post('/public/upload/temp', upload.single('img'), function(req, res) {
    //var form_description = req.body.description;
    console.log(req.file.name);
    //  insert operations into database get placed here
    res.redirect('/');
});

app.use('/public/', express.static(path.join(__dirname,
    '../public')));

if ('development' === app.get('env')) {
    app.use(errorHandler());
}

app.engine('handlebars', exphbs.create({
    defaultLayout: 'main',
    layoutsDir: app.get('views') + '/layouts',
    partialsDir: app.get('views') + '/partials',
    helpers: {
        timeago: function(timestamp) {
            return moment(timestamp).startOf('minute').fromNow();
        }
    }
}).engine);
return app;
};
</code>```

Below is the Handlebar file or (HTML) file :-

```<code><div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">
Upload an Image
</h3>
</div>
<form method="post" action="/images" enctype="multipart/formdata">
<div class="panel-body form-horizontal">
<div class="form-group col-md-12">
<label class="col-sm-2 control-label" for="file">Browse:</label>
<div class="col-md-10">
<input class="form-control" type="file" name="file" id="file">
</div>
</div>
<div class="form-group col-md-12">
<label class="col-md-2 control-label" for="title">Title:</label>
<div class="col-md-10">
<input class="form-control" type="text" name="title">
</div>
</div>
<div class="form-group col-md-12">
<label class="col-md-2 control-label" for="description">Description
</label>
<div class="col-md-10">
<textarea class="form-control" name="description" rows="2"></textarea>
</div>
</div>
<div class="form-group col-md-12">
<div class="col-md-12 text-right">
<button type="submit" id="login-btn"
class="btn btn-success" type="button">
<i class="fa fa-cloud-upload ">
</i> Upload Image</button>
</div>
</div>
</div>
</form>
</div>
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">
</h3>
</div>
<div class="panel-body">
{{#each images}}
<div class="col-md-4 text-center" style="padding-bottom:1em;">
<a href="/images/{{ uniqueId }}">
<img src="/public/upload/{{filename}}" alt="{{title}}" style="width:
175px; height: 175px;" class="imgthumbnail">
</a></div>
{{/each}}
</div>
</div>
</code>```

Below is the image.js Controller File :-

```<code>var fs = require('fs');
var path = require('path');
module.exports = {
index: function(req, res) {
    var viewModel = {
        image: {
            uniqueId: 1,
            title: 'Sample Image 1',
            description: 'This is a sample.',
            filename: 'sample1.jpg',
            views: 0,
            likes: 0,
            timestamp: Date.now
        },
        comments: [{
            image_id: 1,
            email: 'test@testing.com',
            name: 'Test Tester',
            gravatar: 'http://lorempixel.com/75/75/animals/1',
            comment: 'This is a test comment...',
            timestamp: Date.now
        }, {
            image_id: 1,
            email: 'test@testing.com',
            name: 'Test Tester',
            gravatar: 'http://lorempixel.com/75/75/animals/2',
            comment: 'Another followup comment!',
            timestamp: Date.now
        }]
    };
    res.render('image.handlebars', viewModel);
},
create: function(req, res) {
    var possible = 'abcdefghijklmnopqrstuvwxyz0123456789',
        imgUrl = '';
    for (var i = 0; i < 6; i += 1) {
        imgUrl += possible.charAt(Math.floor(Math.random() *
            possible.length));
    }
    var tempPath = req.file.path,
        ext = path.extname(req.file.name).toLowerCase(),
        targetPath = path.resolve('./public/upload/' + imgUrl + ext);
    if (ext === '.png' || ext === '.jpg' || ext === '.jpeg' || ext ===
        '.gif') {
        fs.rename(tempPath, targetPath, function(err) {
            if (err) throw err;
            res.redirect('/images/' + imgUrl);
        });
    } else {
        fs.unlink(tempPath, function() {
            if (err) throw err;
            res.json(500, { error: 'Only image files are allowed.' });
        });
    }
},
like: function(req, res) {
    res.send('The image:like POST controller');
},
comment: function(req, res) {
    res.send('The image:comment POST controller');
}
};
</code>```

When run the server and visit the website on localhost and try to upload a image by clicking on Upload Image button this error comes :-

Cannot read property 'path' of undefined

```<code>at create (G:\Docs\Node.js\Project\imgploader.io\controllers\image.js:40:32)
at Layer.handle [as handle_request] (G:\Docs\Node.js\Project\imgploader.io\node_modules\express\lib\router\layer.js:95:5)
at next (G:\Docs\Node.js\Project\imgploader.io\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (G:\Docs\Node.js\Project\imgploader.io\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (G:\Docs\Node.js\Project\imgploader.io\node_modules\express\lib\router\layer.js:95:5)
at G:\Docs\Node.js\Project\imgploader.io\node_modules\express\lib\router\index.js:281:22
at Function.process_params (G:\Docs\Node.js\Project\imgploader.io\node_modules\express\lib\router\index.js:335:12)
at next (G:\Docs\Node.js\Project\imgploader.io\node_modules\express\lib\router\index.js:275:10)
at Function.handle (G:\Docs\Node.js\Project\imgploader.io\node_modules\express\lib\router\index.js:174:3)
at router (G:\Docs\Node.js\Project\imgploader.io\node_modules\express\lib\router\index.js:47:12)
</code>```

What is the Problem ? I have tried everything available on the Internet but still the same !
Please Help

答:
Maybe because you have used ( ; ) at the end of error handler declaration

```<code>errorHandler = require('errorhandler');
</code>```

also in your HTML name attribute should be img as you have used it multer.

Body:
I am learning Node.js from a book "Web Development with Nodejs and MongoDB" and is Stuck at a point where I have to upload a Image using Multer.
The Code goes like this :-

Below is My Configure.js file :

var path = require('path'),
routes = require('./routes'),
exphbs = require('express-handlebars'),
express = require('express'),
bodyParser = require('body-parser'),
cookieParser = require('cookie-parser'),
morgan = require('morgan'),
methodOverride = require('method-override'),
errorHandler = require('errorhandler');
multer = require('multer');
moment = require('moment');
var upload = multer({ dest: './public/upload/temp' });
module.exports = function(app) {
app.use(morgan('dev'));
app.use(methodOverride());
app.use(cookieParser('some-secret-value-here'));
routes(app);

app.post('/public/upload/temp', upload.single('img'), function(req, res) {
    //var form_description = req.body.description;
    console.log(req.file.name);
    //  insert operations into database get placed here
    res.redirect('/');
});

app.use('/public/', express.static(path.join(__dirname,
    '../public')));

if ('development' === app.get('env')) {
    app.use(errorHandler());
}

app.engine('handlebars', exphbs.create({
    defaultLayout: 'main',
    layoutsDir: app.get('views') + '/layouts',
    partialsDir: app.get('views') + '/partials',
    helpers: {
        timeago: function(timestamp) {
            return moment(timestamp).startOf('minute').fromNow();
        }
    }
}).engine);
return app;
};

Below is the Handlebar file or (HTML) file :-

Upload an Image

<form method="post" action="/images" enctype="multipart/formdata">

Browse:

<input class="form-control" type="file" name="file" id="file">

Title:

<input class="form-control" type="text" name="title">

Description

<textarea class="form-control" name="description" rows="2"></textarea>

<button type="submit" id="login-btn"
class="btn btn-success" type="button">

 Upload Image</button>

</form>

{{#each images}}

{{/each}}

Below is the image.js Controller File :-

var fs = require('fs');
var path = require('path');
module.exports = {
index: function(req, res) {
    var viewModel = {
        image: {
            uniqueId: 1,
            title: 'Sample Image 1',
            description: 'This is a sample.',
            filename: 'sample1.jpg',
            views: 0,
            likes: 0,
            timestamp: Date.now
        },
        comments: [{
            image_id: 1,
            email: 'test@testing.com',
            name: 'Test Tester',
            gravatar: 'http://lorempixel.com/75/75/animals/1',
            comment: 'This is a test comment...',
            timestamp: Date.now
        }, {
            image_id: 1,
            email: 'test@testing.com',
            name: 'Test Tester',
            gravatar: 'http://lorempixel.com/75/75/animals/2',
            comment: 'Another followup comment!',
            timestamp: Date.now
        }]
    };
    res.render('image.handlebars', viewModel);
},
create: function(req, res) {
    var possible = 'abcdefghijklmnopqrstuvwxyz0123456789',
        imgUrl = '';
    for (var i = 0; i < 6; i += 1) {
        imgUrl += possible.charAt(Math.floor(Math.random() *
            possible.length));
    }
    var tempPath = req.file.path,
        ext = path.extname(req.file.name).toLowerCase(),
        targetPath = path.resolve('./public/upload/' + imgUrl + ext);
    if (ext === '.png' || ext === '.jpg' || ext === '.jpeg' || ext ===
        '.gif') {
        fs.rename(tempPath, targetPath, function(err) {
            if (err) throw err;
            res.redirect('/images/' + imgUrl);
        });
    } else {
        fs.unlink(tempPath, function() {
            if (err) throw err;
            res.json(500, { error: 'Only image files are allowed.' });
        });
    }
},
like: function(req, res) {
    res.send('The image:like POST controller');
},
comment: function(req, res) {
    res.send('The image:comment POST controller');
}
};

When run the server and visit the website on localhost and try to upload a image by clicking on Upload Image button this error comes :-

Cannot read property 'path' of undefined

at create (G:\Docs\Node.js\Project\imgploader.io\controllers\image.js:40:32)
at Layer.handle [as handle_request] (G:\Docs\Node.js\Project\imgploader.io\node_modules\express\lib\router\layer.js:95:5)
at next (G:\Docs\Node.js\Project\imgploader.io\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (G:\Docs\Node.js\Project\imgploader.io\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (G:\Docs\Node.js\Project\imgploader.io\node_modules\express\lib\router\layer.js:95:5)
at G:\Docs\Node.js\Project\imgploader.io\node_modules\express\lib\router\index.js:281:22
at Function.process_params (G:\Docs\Node.js\Project\imgploader.io\node_modules\express\lib\router\index.js:335:12)
at next (G:\Docs\Node.js\Project\imgploader.io\node_modules\express\lib\router\index.js:275:10)
at Function.handle (G:\Docs\Node.js\Project\imgploader.io\node_modules\express\lib\router\index.js:174:3)
at router (G:\Docs\Node.js\Project\imgploader.io\node_modules\express\lib\router\index.js:47:12)

What is the Problem ? I have tried everything available on the Internet but still the same !
Please Help

Body:
Maybe because you have used ( ; ) at the end of error handler declaration

errorHandler = require('errorhandler');

also in your HTML name attribute should be img as you have used it multer.


问:
Is using C# for an embedded device that requires precisely timed TCP messages practical?
Lets say I have a device running Windows CE and there are 2 options: using native c++ and using the .NET Compact Framework using C# to build the application.

I have to establish a connection with an external computer and send out status messages exactly every 0.5 seconds, with only a +/- 10 millisecond error tolerance.

I know you might say that in practice there are too many factors to know the answer, but lets assume that this has been tested with a c++ program, and works, and I wanted to make an equivalent program using C#. The only factor being changed would be the language/framework. Would this be possible, or would the 10 ms +/- error tolerance be too strict to achieve due to C# being a slower garbage collecting language?

答:
The 10ms requirement would be achievable in C#, but would never be guaranteed.  It might be 10ms most of the time, but you can near guarantee a GC is going to happen at an inopportune time and your managed thread is going to get suspended.  You will miss that 10ms window.

But why does the solution have to be one or the other?  I don't know much about your overall app requirements, but given similar requirements, my inclination would be to create a small piece in C (not C++ because you want very fine control over memory allocation and deallocation) for the time sensitive piece, probably as a service since services are easy in CE, and then create any UI, business logic, etc. in C#.  Get the real-time nature of the OS for your tiny time-sensitive routine and the huge benefits of managed code for the rest of the app.  Doing UI in C or C++ any more is just silly.


问:
Docker - Using PHP Cli base image for Cron container
So I've been having loads of fun with Docker and Docker-Compose recently, but need the community's advice here. I have a docker-compose file comprised of:

An Nginx container (based on nginx:1.12-alpine image)

A PHP-7.0 FPM container (based on php:7.0-fpm-alpine image)

A MySQL container (based on alpine:3.6 image)

In keeping with Docker's principles of separating processes into individual containers, I would now like to add a fourth container to run Cron. The crontab will be simply:

```<code>*/5 * * * * www-data sh /var/www/html/cron.sh
</code>```

This is for a Magento site, and cron usually requires decent computing power - therefore I figure it would be great to have it in its own container.

I have 3 questions regarding this ...

1) Magento's cron.sh runs a few checks and then runs cron.php, so I assume that my new cron container has to have php installed and running - correct?

2) Assuming that I do need php running in the cron container, then I'm uncertain if I should create a Dockerfile based off the php:7.0-cli-alpine image or to use an alternative? I've read somewhere that CLI images don't run in daemon mode, so this container may exit immediately after running docker-compose up -d.

3) Assuming that I am correct on (1) and (2) above, will I need to ensure that any PHP/PECL extensions I've installed in my custom PHP-7.0 FPM image are also installed in this new cron image?

Thank you for time!

答:
Ok so I made some headway with this. I created a new image based on php:7.0-cli-alpine here is what my Dockerfile looks like:

```<code>FROM php:7.0-cli-alpine

COPY mycrontab /mycrontab

RUN mkdir /var/log/cron
RUN touch /var/log/cron/cron.log

RUN chown -R www-data:www-data /var/log/cron

RUN /usr/bin/crontab -u www-data /crontab

CMD ["crond", "-f", "-l", "8"]
</code>```

here is what mycrontab looks like:

```<code>*/1 * * * * echo "This is a test" >> /var/log/cron/cron.log 2>&1
</code>```

Built it: docker build -t test/cron:latest .

Ran it: docker run --rm -it -v /home/magz/devtest/cron/cron.log:/var/log/cron/cron.log

After a minute (or so), I got an expected output into cron.log :)

So, so far, so good. I'm yet to test this with my docker-compose setup for my Magento site, but I'm confident this will work.

The only question I have remaining is whether or not to ensure that the new Cron image has the same PHP/PECL extensions installed as my PHP-FPM image.

Body:
So I've been having loads of fun with Docker and Docker-Compose recently, but need the community's advice here. I have a docker-compose file comprised of:

An Nginx container (based on nginx:1.12-alpine image)

A PHP-7.0 FPM container (based on php:7.0-fpm-alpine image)

A MySQL container (based on alpine:3.6 image)

In keeping with Docker's principles of separating processes into individual containers, I would now like to add a fourth container to run Cron. The crontab will be simply:

*/5 * * * * www-data sh /var/www/html/cron.sh

This is for a Magento site, and cron usually requires decent computing power - therefore I figure it would be great to have it in its own container.

I have 3 questions regarding this ...

1) Magento's cron.sh runs a few checks and then runs cron.php, so I assume that my new cron container has to have php installed and running - correct?

2) Assuming that I do need php running in the cron container, then I'm uncertain if I should create a Dockerfile based off the php:7.0-cli-alpine image or to use an alternative? I've read somewhere that CLI images don't run in daemon mode, so this container may exit immediately after running docker-compose up -d.

3) Assuming that I am correct on (1) and (2) above, will I need to ensure that any PHP/PECL extensions I've installed in my custom PHP-7.0 FPM image are also installed in this new cron image?

Thank you for time!

Body:
Ok so I made some headway with this. I created a new image based on php:7.0-cli-alpine here is what my Dockerfile looks like:

FROM php:7.0-cli-alpine

COPY mycrontab /mycrontab

RUN mkdir /var/log/cron
RUN touch /var/log/cron/cron.log

RUN chown -R www-data:www-data /var/log/cron

RUN /usr/bin/crontab -u www-data /crontab

CMD ["crond", "-f", "-l", "8"]

here is what mycrontab looks like:

*/1 * * * * echo "This is a test" >> /var/log/cron/cron.log 2>&1

Built it: docker build -t test/cron:latest .

Ran it: docker run --rm -it -v /home/magz/devtest/cron/cron.log:/var/log/cron/cron.log

After a minute (or so), I got an expected output into cron.log :)

So, so far, so good. I'm yet to test this with my docker-compose setup for my Magento site, but I'm confident this will work.

The only question I have remaining is whether or not to ensure that the new Cron image has the same PHP/PECL extensions installed as my PHP-FPM image.


问:
How to replace all elements in vector by the sum of element digits?
I have trouble understanding how to replace all elements in vector by the sum of element digits. For example if i have sequence of such digits 9 22 54 981 my output has to be 9 4 9 18.I know how to count the sum. I have this vector called file_numbers .But I am stuck at this point. Thanks for the help.

```<code>   int SumOfDigits(int digit)
{

    int sum = 0;
    while (digit > 0)
    {
        sum += digit % 10;
        digit /= 10;
    }
    return sum;
}
void FourthTask(vector<int>& file_numbers)
{
    std::transform(file_numbers.begin(),
        file_numbers.end(),
        file_numbers.begin(),SumOfDigits);
}
</code>```

答:
Code first, then notes:

```<code>void SumTask(std::vector<int>& file_numbers){
    for (auto& i :  file_numbers){
        int sum = 0;
            while (i > 0){
                sum += i % 10;
                i /= 10;
            }
            i = sum;
    }
}
</code>```

Notes:

Sum goes inside the for loop, otherwise you're going to sum all the digits previously processed as well

Use a range-loop, they're pretty well optimized

Body:
I have trouble understanding how to replace all elements in vector by the sum of element digits. For example if i have sequence of such digits 9 22 54 981 my output has to be 9 4 9 18.I know how to count the sum. I have this vector called file_numbers .But I am stuck at this point. Thanks for the help.

   int SumOfDigits(int digit)
{

    int sum = 0;
    while (digit > 0)
    {
        sum += digit % 10;
        digit /= 10;
    }
    return sum;
}
void FourthTask(vector<int>& file_numbers)
{
    std::transform(file_numbers.begin(),
        file_numbers.end(),
        file_numbers.begin(),SumOfDigits);
}

Body:
Code first, then notes:

void SumTask(std::vector<int>& file_numbers){
    for (auto& i :  file_numbers){
        int sum = 0;
            while (i > 0){
                sum += i % 10;
                i /= 10;
            }
            i = sum;
    }
}

Notes:

Sum goes inside the for loop, otherwise you're going to sum all the digits previously processed as well

Use a range-loop, they're pretty well optimized


问:
Is there a SQL statement that lets me create exact duplicate of partitioned table structure in Oracle 12c?
I need to clone a partitioned table in Oracle (without data).
Is there a SQL statement that lets me do it in Oracle 12c?

I tried using DBMS metadata and then executing generated DDL.
Looking for something simpler I can use in PL/SQL or SQL code.

答:
Basically, if you get the DDL from metadata, the partitioning will be handled by Oracle. See this answer on DBA SE site.

You might also perform an empty copy of the table

```<code>CREATE TABLE zxy AS SELECT * FROM xyz WHERE 1=2;
</code>```

And then alter table adding the partition, if you want a "simpler" approach (yet longer)

Body:
Basically, if you get the DDL from metadata, the partitioning will be handled by Oracle. See this answer on DBA SE site.

You might also perform an empty copy of the table

CREATE TABLE zxy AS SELECT * FROM xyz WHERE 1=2;

And then alter table adding the partition, if you want a "simpler" approach (yet longer)


问:
Set angular scope variable in markup
Simple question:  How can I set a scope value in html, to be read by my controller?

var app = angular.module('app', []);

app.controller('MyController', function($scope) {
  console.log($scope.myVar);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app='app'>
  <div ng-controller="MyController" app-myVar="test">
    {{myVar}}
  </div>
</div></code>```

JSFiddle:  http://jsfiddle.net/ncapito/YdQcX/

答:
```<code>$scope.$watch('myVar', function (newValue, oldValue) {
        if (typeof (newValue) !== 'undefined') {
            $scope.someothervar= newValue;
//or get some data
            getData();
        }

    }, true);
</code>```

Variable initializes after controller so you need to watch over it and when it't initialized the use it.

Title: Set angular scope variable in markup

Body:
Simple question:  How can I set a scope value in html, to be read by my controller?

var app = angular.module('app', []);

app.controller('MyController', function($scope) {
  console.log($scope.myVar);
});

    {{myVar}}

JSFiddle:  http://jsfiddle.net/ncapito/YdQcX/

Body:
$scope.$watch('myVar', function (newValue, oldValue) {
        if (typeof (newValue) !== 'undefined') {
            $scope.someothervar= newValue;
//or get some data
            getData();
        }

    }, true);

Variable initializes after controller so you need to watch over it and when it't initialized the use it.


问:
Printing a bitstream data /TCP related
I am trying to make a communication between a Client and a Sever through TCP.

Let's say the client send 10 Hex numbers as bitstream to Sever. send(socketID, pSend, 20, 0); Where pSend = &ArrayClient; and unsigned short ArrayClient[] = { 0A, 0B, BA, B1...., FA }.

The sever receive the bytes stream with recv(acceptID, pRecv, 20, 0). How can I print out the content in my pointer pRecv correctly. As Sever I won't know how many bytes did the Client send, therefore I don't know how many to print.
Because the datas were sent as bitstream, not a string. I can not know the end of the message by finding \0 like working with string.

So is there a way that I can know how many bytes that I received as sever, or any way to print out the bitstream in my pRecv as Hex numbers.

I have tried pointer to a pointer and something similar like this:

```<code>while( ((unsigned int*)pRecv)[i] != 0){
    printf("%X", ((unsigned int*)pRecv)[i]);
    i++;
}
</code>```

答:
When dealing with TCP, there is no built-in way of separating messages, so your protocol needs to delimit the message boundaries in some known way.

A simple way of doing this is by first sending single byte denoting the length of the message, then sending that number of bytes.

For example, before sending the above message, do this:

```<code>char mlen = 20;
send(socketID, &mlen, 1, 0);
</code>```

Title: Printing a bitstream data /TCP related

Body:
I am trying to make a communication between a Client and a Sever through TCP.

Let's say the client send 10 Hex numbers as bitstream to Sever. send(socketID, pSend, 20, 0); Where pSend = &ArrayClient; and unsigned short ArrayClient[] = { 0A, 0B, BA, B1...., FA }.

The sever receive the bytes stream with recv(acceptID, pRecv, 20, 0). How can I print out the content in my pointer pRecv correctly. As Sever I won't know how many bytes did the Client send, therefore I don't know how many to print.
Because the datas were sent as bitstream, not a string. I can not know the end of the message by finding \0 like working with string.

So is there a way that I can know how many bytes that I received as sever, or any way to print out the bitstream in my pRecv as Hex numbers.

I have tried pointer to a pointer and something similar like this:

while( ((unsigned int*)pRecv)[i] != 0){
    printf("%X", ((unsigned int*)pRecv)[i]);
    i++;
}

Body:
When dealing with TCP, there is no built-in way of separating messages, so your protocol needs to delimit the message boundaries in some known way.

A simple way of doing this is by first sending single byte denoting the length of the message, then sending that number of bytes.

For example, before sending the above message, do this:

char mlen = 20;
send(socketID, &mlen, 1, 0);


问:
Sequential list with pairs of the same prefix
I have the simplest possible code for creating string with integer:

```<code>x = []
for i in range(6):
    x.append('a' + str(i))
</code>```

,witch creating that output:

```<code>['a0', 'a1', 'a2', 'a3', 'a4', 'a5']
</code>```

But how could the condition to create a list in this form look like:

```<code> ['a0', 'a0', 'a1', 'a1', 'a2', 'a2']
</code>```

I tried this way:

```<code>x = []
for i in range(6):
   if i%2==0:
       x.append('a' + str(i))
   else:
       x.append('a' + str(i-1))
</code>```

But this ['a0', 'a0', 'a2', 'a2', 'a4', 'a4'] is far from what I need.

答:
This comprehension makes use of integer division:

```<code>x = ['a' + str(i//2) for i in range(6)]
</code>```

It can create lists of odd length, too ;-)

Body:
I have the simplest possible code for creating string with integer:

x = []
for i in range(6):
    x.append('a' + str(i))

,witch creating that output:

['a0', 'a1', 'a2', 'a3', 'a4', 'a5']

But how could the condition to create a list in this form look like:

 ['a0', 'a0', 'a1', 'a1', 'a2', 'a2']

I tried this way:

x = []
for i in range(6):
   if i%2==0:
       x.append('a' + str(i))
   else:
       x.append('a' + str(i-1))

But this ['a0', 'a0', 'a2', 'a2', 'a4', 'a4'] is far from what I need.

Body:
This comprehension makes use of integer division:

x = ['a' + str(i//2) for i in range(6)]

It can create lists of odd length, too ;-)