问:
Spring SPEL : setRemoteDirecotoryExpression issue
I'm trying to set the remote directory for my SFTP server using Java Spring's SPEL language. Basically I'm trying to append two strings together as my remote directory path, but for some reason I'm still trying to figure out, it does not work.
Here's what I do :

ExpressionParser EXPRESSION_PARSER = new SpelExpressionParser();
Expression exp = EXPRESSION_PARSER.parseExpression("headers['path']"); //which contains the 2nd part of the path to my dir
String fullFilePath = this.remoteDir; //which has the 1st part of the path to my directory
SftpMessageHandler handler = new SftpMessageHandler(sftpSessionFactory());
handler.setRemoteDirectoryExpressionString(this.remoteDir.concat("/").concat(exp.getValue().toString()));
handler.setAutoCreateDirectory(true);
```

<p>There is seemingly something wrong with the <code>exp.getValue()</code>method, because I get the following exception whenever that line is not commented :</p>

```org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'SFTPConfig' defined in file [/Users/psdev/PrediSurge/backend/file-service/target/classes/com/predisurge/planopsuite/microservices/fileservice/sftp/SFTPConfig.class]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'handler' defined in class path resource [com/predisurge/planopsuite/microservices/fileservice/sftp/SFTPConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.messaging.MessageHandler]: Circular reference involving containing bean 'SFTPConfig' - consider declaring the factory method as static for independence from its containing instance. Factory method 'handler' threw exception; nested exception is org.springframework.expression.spel.SpelEvaluationException: EL1007E: Property or field 'headers' cannot be found on null
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:584) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:846) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:863) ~[spring-context-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:546) ~[spring-context-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:142) ~[spring-boot-2.1.2.RELEASE.jar:2.1.2.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:775) [spring-boot-2.1.2.RELEASE.jar:2.1.2.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) [spring-boot-2.1.2.RELEASE.jar:2.1.2.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:316) [spring-boot-2.1.2.RELEASE.jar:2.1.2.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1260) [spring-boot-2.1.2.RELEASE.jar:2.1.2.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1248) [spring-boot-2.1.2.RELEASE.jar:2.1.2.RELEASE]
    at com.predisurge.planopsuite.microservices.fileservice.FileServiceApplication.main(FileServiceApplication.java:26) [classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_241]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_241]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_241]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_241]
    at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-2.1.2.RELEASE.jar:2.1.2.RELEASE]
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'handler' defined in class path resource [com/predisurge/planopsuite/microservices/fileservice/sftp/SFTPConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.messaging.MessageHandler]: Circular reference involving containing bean 'SFTPConfig' - consider declaring the factory method as static for independence from its containing instance. Factory method 'handler' threw exception; nested exception is org.springframework.expression.spel.SpelEvaluationException: EL1007E: Property or field 'headers' cannot be found on null
    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:627) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:456) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1288) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1127) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:538) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.integration.config.annotation.AbstractMethodAnnotationPostProcessor.resolveTargetBeanFromMethodWithBeanAnnotation(AbstractMethodAnnotationPostProcessor.java:464) ~[spring-integration-core-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.integration.config.annotation.AbstractMethodAnnotationPostProcessor.postProcess(AbstractMethodAnnotationPostProcessor.java:146) ~[spring-integration-core-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.integration.config.annotation.MessagingAnnotationPostProcessor.processAnnotationTypeOnMethod(MessagingAnnotationPostProcessor.java:190) ~[spring-integration-core-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.integration.config.annotation.MessagingAnnotationPostProcessor.lambda$postProcessAfterInitialization$0(MessagingAnnotationPostProcessor.java:163) ~[spring-integration-core-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.util.ReflectionUtils.doWithMethods(ReflectionUtils.java:589) ~[spring-core-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.integration.config.annotation.MessagingAnnotationPostProcessor.postProcessAfterInitialization(MessagingAnnotationPostProcessor.java:144) ~[spring-integration-core-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization(AbstractAutowireCapableBeanFactory.java:434) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1749) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:576) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    ... 20 common frames omitted
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.messaging.MessageHandler]: Circular reference involving containing bean 'SFTPConfig' - consider declaring the factory method as static for independence from its containing instance. Factory method 'handler' threw exception; nested exception is org.springframework.expression.spel.SpelEvaluationException: EL1007E: Property or field 'headers' cannot be found on null
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:622) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    ... 38 common frames omitted
Caused by: org.springframework.expression.spel.SpelEvaluationException: EL1007E: Property or field 'headers' cannot be found on null
    at org.springframework.expression.spel.ast.PropertyOrFieldReference.readProperty(PropertyOrFieldReference.java:213) ~[spring-expression-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.expression.spel.ast.PropertyOrFieldReference.getValueInternal(PropertyOrFieldReference.java:104) ~[spring-expression-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.expression.spel.ast.PropertyOrFieldReference.getValueInternal(PropertyOrFieldReference.java:91) ~[spring-expression-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.expression.spel.ast.CompoundExpression.getValueRef(CompoundExpression.java:53) ~[spring-expression-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.expression.spel.ast.CompoundExpression.getValueInternal(CompoundExpression.java:89) ~[spring-expression-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.expression.spel.ast.SpelNodeImpl.getValue(SpelNodeImpl.java:109) ~[spring-expression-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.expression.spel.standard.SpelExpression.getValue(SpelExpression.java:138) ~[spring-expression-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at com.predisurge.planopsuite.microservices.fileservice.sftp.SFTPConfig.handler(SFTPConfig.java:101) ~[classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_241]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_241]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_241]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_241]
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    ... 39 common frames omitted
```

I'm not new to Java Spring but I've never used SPEL before, so I'm very unsure what's wrong.
Any help would be appreciated.

答:
The EL expression "headers['path']" probably refers to a map, containing key "path". By default spring expression parser has no information about external variables. You should create an instance of StandardEvaluationContext, register the variable "headers" there and use this context, when getting expression value:

```<code>ExpressionParser EXPRESSION_PARSER = new SpelExpressionParser();

// create context and register variable "headers"
StandardEvaluationContext context = new StandardEvaluationContext();
context.setVariable("headers",headers);

Expression exp = EXPRESSION_PARSER.parseExpression("headers['path']");
String fullFilePath = this.remoteDir;
SftpMessageHandler handler = new SftpMessageHandler(sftpSessionFactory());

// use context, when getting evaluated value
 handler.setRemoteDirectoryExpressionString(this.remoteDir.concat("/").concat(exp.getValue(context).toString()));
        handler.setAutoCreateDirectory(true);
</code>```

Here is a reference for using variables in spring EL.

Body:
I'm trying to set the remote directory for my SFTP server using Java Spring's SPEL language. Basically I'm trying to append two strings together as my remote directory path, but for some reason I'm still trying to figure out, it does not work.
Here's what I do :

ExpressionParser EXPRESSION_PARSER = new SpelExpressionParser();
Expression exp = EXPRESSION_PARSER.parseExpression("headers['path']"); //which contains the 2nd part of the path to my dir
String fullFilePath = this.remoteDir; //which has the 1st part of the path to my directory
SftpMessageHandler handler = new SftpMessageHandler(sftpSessionFactory());
handler.setRemoteDirectoryExpressionString(this.remoteDir.concat("/").concat(exp.getValue().toString()));
handler.setAutoCreateDirectory(true);

There is seemingly something wrong with the exp.getValue()method, because I get the following exception whenever that line is not commented :

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'SFTPConfig' defined in file [/Users/psdev/PrediSurge/backend/file-service/target/classes/com/predisurge/planopsuite/microservices/fileservice/sftp/SFTPConfig.class]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'handler' defined in class path resource [com/predisurge/planopsuite/microservices/fileservice/sftp/SFTPConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.messaging.MessageHandler]: Circular reference involving containing bean 'SFTPConfig' - consider declaring the factory method as static for independence from its containing instance. Factory method 'handler' threw exception; nested exception is org.springframework.expression.spel.SpelEvaluationException: EL1007E: Property or field 'headers' cannot be found on null
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:584) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:846) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:863) ~[spring-context-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:546) ~[spring-context-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:142) ~[spring-boot-2.1.2.RELEASE.jar:2.1.2.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:775) [spring-boot-2.1.2.RELEASE.jar:2.1.2.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) [spring-boot-2.1.2.RELEASE.jar:2.1.2.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:316) [spring-boot-2.1.2.RELEASE.jar:2.1.2.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1260) [spring-boot-2.1.2.RELEASE.jar:2.1.2.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1248) [spring-boot-2.1.2.RELEASE.jar:2.1.2.RELEASE]
    at com.predisurge.planopsuite.microservices.fileservice.FileServiceApplication.main(FileServiceApplication.java:26) [classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_241]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_241]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_241]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_241]
    at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-2.1.2.RELEASE.jar:2.1.2.RELEASE]
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'handler' defined in class path resource [com/predisurge/planopsuite/microservices/fileservice/sftp/SFTPConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.messaging.MessageHandler]: Circular reference involving containing bean 'SFTPConfig' - consider declaring the factory method as static for independence from its containing instance. Factory method 'handler' threw exception; nested exception is org.springframework.expression.spel.SpelEvaluationException: EL1007E: Property or field 'headers' cannot be found on null
    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:627) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:456) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1288) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1127) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:538) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.integration.config.annotation.AbstractMethodAnnotationPostProcessor.resolveTargetBeanFromMethodWithBeanAnnotation(AbstractMethodAnnotationPostProcessor.java:464) ~[spring-integration-core-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.integration.config.annotation.AbstractMethodAnnotationPostProcessor.postProcess(AbstractMethodAnnotationPostProcessor.java:146) ~[spring-integration-core-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.integration.config.annotation.MessagingAnnotationPostProcessor.processAnnotationTypeOnMethod(MessagingAnnotationPostProcessor.java:190) ~[spring-integration-core-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.integration.config.annotation.MessagingAnnotationPostProcessor.lambda$postProcessAfterInitialization$0(MessagingAnnotationPostProcessor.java:163) ~[spring-integration-core-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.util.ReflectionUtils.doWithMethods(ReflectionUtils.java:589) ~[spring-core-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.integration.config.annotation.MessagingAnnotationPostProcessor.postProcessAfterInitialization(MessagingAnnotationPostProcessor.java:144) ~[spring-integration-core-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization(AbstractAutowireCapableBeanFactory.java:434) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1749) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:576) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    ... 20 common frames omitted
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.messaging.MessageHandler]: Circular reference involving containing bean 'SFTPConfig' - consider declaring the factory method as static for independence from its containing instance. Factory method 'handler' threw exception; nested exception is org.springframework.expression.spel.SpelEvaluationException: EL1007E: Property or field 'headers' cannot be found on null
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:622) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    ... 38 common frames omitted
Caused by: org.springframework.expression.spel.SpelEvaluationException: EL1007E: Property or field 'headers' cannot be found on null
    at org.springframework.expression.spel.ast.PropertyOrFieldReference.readProperty(PropertyOrFieldReference.java:213) ~[spring-expression-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.expression.spel.ast.PropertyOrFieldReference.getValueInternal(PropertyOrFieldReference.java:104) ~[spring-expression-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.expression.spel.ast.PropertyOrFieldReference.getValueInternal(PropertyOrFieldReference.java:91) ~[spring-expression-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.expression.spel.ast.CompoundExpression.getValueRef(CompoundExpression.java:53) ~[spring-expression-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.expression.spel.ast.CompoundExpression.getValueInternal(CompoundExpression.java:89) ~[spring-expression-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.expression.spel.ast.SpelNodeImpl.getValue(SpelNodeImpl.java:109) ~[spring-expression-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.expression.spel.standard.SpelExpression.getValue(SpelExpression.java:138) ~[spring-expression-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at com.predisurge.planopsuite.microservices.fileservice.sftp.SFTPConfig.handler(SFTPConfig.java:101) ~[classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_241]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_241]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_241]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_241]
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    ... 39 common frames omitted

I'm not new to Java Spring but I've never used SPEL before, so I'm very unsure what's wrong.
Any help would be appreciated.

Body:
The EL expression "headers['path']" probably refers to a map, containing key "path". By default spring expression parser has no information about external variables. You should create an instance of StandardEvaluationContext, register the variable "headers" there and use this context, when getting expression value:

ExpressionParser EXPRESSION_PARSER = new SpelExpressionParser();

// create context and register variable "headers"
StandardEvaluationContext context = new StandardEvaluationContext();
context.setVariable("headers",headers);

Expression exp = EXPRESSION_PARSER.parseExpression("headers['path']");
String fullFilePath = this.remoteDir;
SftpMessageHandler handler = new SftpMessageHandler(sftpSessionFactory());

// use context, when getting evaluated value
 handler.setRemoteDirectoryExpressionString(this.remoteDir.concat("/").concat(exp.getValue(context).toString()));
        handler.setAutoCreateDirectory(true);

Here is a reference for using variables in spring EL.


来源: stackexchange

问:
Vue / Router: How do I correctly fetch data before rendering page content?
I'm using Nuxt with Vue Router and Axios. I see Vue Router has this fantastic feature called Navigation Guards.

Unfortunately, in the example below, my beforeRouteEnter() function is called but seems to exit and switch pages before my manual next() method is called in fetchPageData(next).

What is the correct pattern here?

```<code>export default {
    beforeRouteEnter (to, from, next) {
        next(vm => {
            vm.fetchPageData(next);
        });
    },
    methods: {
        async fetchPageData(next) {
            const result = await this.$axios.$get('/api/v2/inventory/3906?apiKey=f54761e0-673e-4baf-86c1-0b85a6c8c118');
            this.$store.commit('property/setProperty', result[0]);
            next();
        }
    }
}
</code>```

I assume that my first call to next(vm => {}) is running asynchronously, allowing execution to continue, resulting in a page change before I (most likely incorrectly) try to callback next().

答:
You are right, calling next() second time is incorrect. Your first call to next() tells Router "go on, you can proceed with changing active component (create/mount/render) and when the component is created, call my callback (passed as an argument to next())

You can follow guidance in Data fetching - fetching before navigation Docs ie. fetching data first and call next() after but that requires to extract fetch logic from the component itself.

Generally I find easier to write all component in the way assuming data are not here on 1st render and are coming later when all async calls resolve...

UPDATE Nuxt async data fetching options

As you are using Nuxt.js you have some other options how to use async data:

nuxtServerInit - useful to fill client-side Vuex store with data from server side

fetch method - The fetch method is used to fill the store before rendering the page. It's like the asyncData method except it doesn't set the component data and allows you to put the data into the store. Returning Promise from fetch method will make Nuxt wait for promise to resolve before it renders the component...

asyncData method can be used to to fetch data and put it inside component's data. Returning Promise from asyncData method will make Nuxt wait for promise to resolve before it renders the component...

export default {
  async fetch({store, $axios}) {
    const result = await $axios.$get('/api/v2/inventory/3906');
    store.commit('property/setProperty', result[0]);
  }
}
```

ContentLicense: CC BY-SA 4.0

Body:
I'm using Nuxt with Vue Router and Axios. I see Vue Router has this fantastic feature called Navigation Guards.

Unfortunately, in the example below, my beforeRouteEnter() function is called but seems to exit and switch pages before my manual next() method is called in fetchPageData(next).

What is the correct pattern here?

export default {
    beforeRouteEnter (to, from, next) {
        next(vm => {
            vm.fetchPageData(next);
        });
    },
    methods: {
        async fetchPageData(next) {
            const result = await this.$axios.$get('/api/v2/inventory/3906?apiKey=f54761e0-673e-4baf-86c1-0b85a6c8c118');
            this.$store.commit('property/setProperty', result[0]);
            next();
        }
    }
}

I assume that my first call to next(vm => {}) is running asynchronously, allowing execution to continue, resulting in a page change before I (most likely incorrectly) try to callback next().


问:
Error while configuring CSS modules with webpack
I am trying to configure CSS modules with webpack but I get an error.

I have checked the other answers here on stackoverflow but none of the solutions have made it work for me so far.

I have added the loader as the docs suggest but it still shows an error.

This is my webpack.configuration.js file.

```<code>const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    entry: './src/index.js',
    output: {
        path: path.join(__dirname, '/dist'),
        filename: 'index_bundle.js',
        publicPath: '/'
    },
    module: {
        rules: [

            {
                test: /\.css$/,
                loader: 'style-loader!css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]'
            },

            {
                test: /\.js$/,
                exclude: /node_modules/,
                use: {
                    loader: 'babel-loader'
                }
            }
        ]
    },
    devServer: {
        historyApiFallback: true,
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: './src/index.html'
        })
    ]
}
</code>```

The error I get is this.

```<code>ERROR in ./src/index.css (./node_modules/css-loader/dist/cjs.js?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]!./src/index.css)
    Module build failed (from ./node_modules/css-loader/dist/cjs.js):
    ValidationError: Invalid options object. CSS Loader has been initialised using an options object that does not match the API schema.
     - options has an unknown property 'localIdentName'. These properties are valid:
       object { url?, import?, modules?, sourceMap?, importLoaders?, localsConvention?, onlyLocals? }
     - options.importLoaders should be one of these:
       boolean | number
       -> Enables/Disables or setups number of loaders applied before CSS loader (https://github.com/webpack-contrib/css-loader#importloaders).
       Details:
        * options.importLoaders should be a boolean.
        * options.importLoaders should be a number.
        at validate (C:\Users\Arjun\Desktop\manpro\node_modules\css-loader\node_modules\schema-utils\dist\validate.js:49:11)
        at Object.loader (C:\Users\Arjun\Desktop\manpro\node_modules\css-loader\dist\index.js:34:28)
     @ ./src/index.css 1:14-150 20:4-31:5 23:25-161
     @ ./src/index.js

    ERROR in ./src/components/layout/Navbar.css (./node_modules/css-loader/dist/cjs.js?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]!./src/components/layout/Navbar.css)
    Module build failed (from ./node_modules/css-loader/dist/cjs.js):
    ValidationError: Invalid options object. CSS Loader has been initialised using an options object that does not match the API schema.
     - options has an unknown property 'localIdentName'. These properties are valid
</code>```

update: I was able to fix it with this:

```<code>{
            test: /\.css$/,
            use: [
                'style-loader',
                {
                    loader: 'css-loader',
                    options: {
                        importLoaders: 1,
                        modules: true
                    }
                }
            ]
        }
</code>```

答:
I had this issue and fixed it with the below solution

```<code>ValidationError: Invalid options object. CSS Loader has been initialized using an options object that does not match the API schema.<br>

 - options has an unknown property 'localIndentName'. These properties are valid:
   object { url?, import?, modules?, sourceMap?, importLoaders?, localsConvention?, onlyLocals?, esModule? }
</code>```

In the latest version of react the webpack.config.js has
localIdentName nested in modules.

Move your localIdentName: '[name]__[local]___[hash:base64:5]' to modules by replaing modules : true with the below format

```<code>{
              test: cssRegex,
              exclude: cssModuleRegex,
              use: getStyleLoaders({
                importLoaders: 1,
                sourceMap: isEnvProduction && shouldUseSourceMap,
              modules: {
                    localIdentName: '[name]__[local]___[hash:base64:5]'
                }
}
</code>```

This should fix the issue

Body:
I am trying to configure CSS modules with webpack but I get an error.

I have checked the other answers here on stackoverflow but none of the solutions have made it work for me so far.

I have added the loader as the docs suggest but it still shows an error.

This is my webpack.configuration.js file.

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    entry: './src/index.js',
    output: {
        path: path.join(__dirname, '/dist'),
        filename: 'index_bundle.js',
        publicPath: '/'
    },
    module: {
        rules: [

            {
                test: /\.css$/,
                loader: 'style-loader!css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]'
            },

            {
                test: /\.js$/,
                exclude: /node_modules/,
                use: {
                    loader: 'babel-loader'
                }
            }
        ]
    },
    devServer: {
        historyApiFallback: true,
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: './src/index.html'
        })
    ]
}

The error I get is this.

ERROR in ./src/index.css (./node_modules/css-loader/dist/cjs.js?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]!./src/index.css)
    Module build failed (from ./node_modules/css-loader/dist/cjs.js):
    ValidationError: Invalid options object. CSS Loader has been initialised using an options object that does not match the API schema.
     - options has an unknown property 'localIdentName'. These properties are valid:
       object { url?, import?, modules?, sourceMap?, importLoaders?, localsConvention?, onlyLocals? }
     - options.importLoaders should be one of these:
       boolean | number
       -> Enables/Disables or setups number of loaders applied before CSS loader (https://github.com/webpack-contrib/css-loader#importloaders).
       Details:
        * options.importLoaders should be a boolean.
        * options.importLoaders should be a number.
        at validate (C:\Users\Arjun\Desktop\manpro\node_modules\css-loader\node_modules\schema-utils\dist\validate.js:49:11)
        at Object.loader (C:\Users\Arjun\Desktop\manpro\node_modules\css-loader\dist\index.js:34:28)
     @ ./src/index.css 1:14-150 20:4-31:5 23:25-161
     @ ./src/index.js

    ERROR in ./src/components/layout/Navbar.css (./node_modules/css-loader/dist/cjs.js?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]!./src/components/layout/Navbar.css)
    Module build failed (from ./node_modules/css-loader/dist/cjs.js):
    ValidationError: Invalid options object. CSS Loader has been initialised using an options object that does not match the API schema.
     - options has an unknown property 'localIdentName'. These properties are valid

update: I was able to fix it with this:

{
            test: /\.css$/,
            use: [
                'style-loader',
                {
                    loader: 'css-loader',
                    options: {
                        importLoaders: 1,
                        modules: true
                    }
                }
            ]
        }

Body:
I had this issue and fixed it with the below solution

ValidationError: Invalid options object. CSS Loader has been initialized using an options object that does not match the API schema.<br>

 - options has an unknown property 'localIndentName'. These properties are valid:
   object { url?, import?, modules?, sourceMap?, importLoaders?, localsConvention?, onlyLocals?, esModule? }

In the latest version of react the webpack.config.js has
localIdentName nested in modules.

Move your localIdentName: '[name]__[local]___[hash:base64:5]' to modules by replaing modules : true with the below format

{
              test: cssRegex,
              exclude: cssModuleRegex,
              use: getStyleLoaders({
                importLoaders: 1,
                sourceMap: isEnvProduction && shouldUseSourceMap,
              modules: {
                    localIdentName: '[name]__[local]___[hash:base64:5]'
                }
}

This should fix the issue


问:
How to update data in RecycleView in kivy?
I have read from kivy that RecycleView is able to update data by calling refresh_from_data() manually after data is changed. I still have a few questions.

Here is my code. I tried to simplified it as the original one is pretty long.

In .py,

```<code>class FilterPage(Screen):
    def call_DB(self, price_min, price_max):
        'codes and shits'
        'Basically, I filter some result according to users input'
        'and store it in a list called real_result'
        'I want to update content and length of real_result for RecycleView'

        self.app = App.get_running_app()
        self.rv = self.app.rv
        self.rv.refresh_from_data()

class RV(RecycleView):
    def __init__(self, **kwargs):
        super(RV, self).__init__(**kwargs)

        global real_result
        self.data = [{'text': str(x)} for x in range(len(real_result))]

kv = Builder.load_file("test.kv")
class MyApp(App):
    rv = RV()
    def build(self):
        return kv

MyApp().run()
</code>```

In .kv,

```<code><ProductButton>:
    on_release: print("success")
    canvas.before:
        Color:
            rgba: (0.4, 0.9, 0.1, 0.3)
        Rectangle:
            pos: self.pos
            size: self.size

<RV>:
    viewclass: 'ProductButton'
    RecycleBoxLayout:
        default_size: None, dp(56)
        default_size_hint: 1, None
        size_hint_y: None
        height: self.minimum_height
        orientation: 'vertical'
        multiselect: True
        touch_multiselect: True
        spacing: 10

<ProductPage>:
    canvas:
        Rectangle:
            source: "dot01.png"
            size: root.width, root.height
            pos: self.pos
    BoxLayout:
        orientation: "vertical"
        RV:
        Button:
            text: 'Previous screen'
            size_hint: None, None
            size: 150, 50
</code>```

Any limitation on the format of data to be updated?
I read this, https://kivy.org/doc/stable/_modules/kivy/uix/recycleview.html. Should I also include this part of code in my RecycleView class?

```<code>def refresh_from_data(self, *largs, **kwargs):
    self._refresh_flags['data'].append(kwargs)
    self._refresh_trigger()
</code>```

I just want to update content in real_result and its length. Can it be done by calling refresh_from_data()? Should I pass any variables when calling it?

I want to include a few pieces of information in self.data. How?

The question is a bit long and I have cut many codes. If you need more details, please comment below. Thank you so much.

答:
To change the content you only need to change the included data. No need to do anything additional.

```<code>class RV(RecycleView):
    def __init__(self, **kwargs):
        super(RV, self).__init__(**kwargs)

        global real_result
        self.data = [{'text': str(x)} for x in range(len(real_result))]

    def alter_data(self):
        self.data = [{'text': str(x+x)} for x in range(len(real_result))]
</code>```

and then call alter_data

In my code I use:

```<code>def refresh_data(self):
    self.data = []
    records_new = self.PW.dbcon.session.query ...

    for n_rows in records_new:
        r_tab_name = n_rows.tab_name
        d={'t_col1': r_tab_name.c1
            , 't_col2': r_tab_name.c2
            , 's_col3': r_tab_name.s3 if r_tab_name.s3 is not None else 0
            }

        self.data.append(d)
    self.data_for_thz=self.data
</code>```

kv:

```<code><LocalRecyWidget>:
    BoxLayout:
        BoxLayout:

            Label:
            Button:
            Button:
            ...

<MyClass>:
    BoxLayout:
        Label:
            ...
        RecycleView:
            viewclass: 'LocalRecyWidget'
            id: ....
            data: root.data_for_thz
            RecycleBoxLayout:
                ...
</code>```

Body:
I have read from kivy that RecycleView is able to update data by calling refresh_from_data() manually after data is changed. I still have a few questions.

Here is my code. I tried to simplified it as the original one is pretty long.

In .py,

class FilterPage(Screen):
    def call_DB(self, price_min, price_max):
        'codes and shits'
        'Basically, I filter some result according to users input'
        'and store it in a list called real_result'
        'I want to update content and length of real_result for RecycleView'

        self.app = App.get_running_app()
        self.rv = self.app.rv
        self.rv.refresh_from_data()

class RV(RecycleView):
    def __init__(self, **kwargs):
        super(RV, self).__init__(**kwargs)

        global real_result
        self.data = [{'text': str(x)} for x in range(len(real_result))]

kv = Builder.load_file("test.kv")
class MyApp(App):
    rv = RV()
    def build(self):
        return kv

MyApp().run()

In .kv,

<ProductButton>:
    on_release: print("success")
    canvas.before:
        Color:
            rgba: (0.4, 0.9, 0.1, 0.3)
        Rectangle:
            pos: self.pos
            size: self.size

<RV>:
    viewclass: 'ProductButton'
    RecycleBoxLayout:
        default_size: None, dp(56)
        default_size_hint: 1, None
        size_hint_y: None
        height: self.minimum_height
        orientation: 'vertical'
        multiselect: True
        touch_multiselect: True
        spacing: 10

<ProductPage>:
    canvas:
        Rectangle:
            source: "dot01.png"
            size: root.width, root.height
            pos: self.pos
    BoxLayout:
        orientation: "vertical"
        RV:
        Button:
            text: 'Previous screen'
            size_hint: None, None
            size: 150, 50

Any limitation on the format of data to be updated?
I read this, https://kivy.org/doc/stable/_modules/kivy/uix/recycleview.html. Should I also include this part of code in my RecycleView class?

def refresh_from_data(self, *largs, **kwargs):
    self._refresh_flags['data'].append(kwargs)
    self._refresh_trigger()

I just want to update content in real_result and its length. Can it be done by calling refresh_from_data()? Should I pass any variables when calling it?

I want to include a few pieces of information in self.data. How?

The question is a bit long and I have cut many codes. If you need more details, please comment below. Thank you so much.

Body:
To change the content you only need to change the included data. No need to do anything additional.

class RV(RecycleView):
    def __init__(self, **kwargs):
        super(RV, self).__init__(**kwargs)

        global real_result
        self.data = [{'text': str(x)} for x in range(len(real_result))]

    def alter_data(self):
        self.data = [{'text': str(x+x)} for x in range(len(real_result))]

and then call alter_data

In my code I use:

def refresh_data(self):
    self.data = []
    records_new = self.PW.dbcon.session.query ...

    for n_rows in records_new:
        r_tab_name = n_rows.tab_name
        d={'t_col1': r_tab_name.c1
            , 't_col2': r_tab_name.c2
            , 's_col3': r_tab_name.s3 if r_tab_name.s3 is not None else 0
            }

        self.data.append(d)
    self.data_for_thz=self.data

kv:

<LocalRecyWidget>:
    BoxLayout:
        BoxLayout:

            Label:
            Button:
            Button:
            ...

<MyClass>:
    BoxLayout:
        Label:
            ...
        RecycleView:
            viewclass: 'LocalRecyWidget'
            id: ....
            data: root.data_for_thz
            RecycleBoxLayout:
                ...


问:
How many docker containers do i need, and how do i sperate code between them?
I'm in the process of designing a web-service hosted with Google App Engine comprised of three parts, a client website (or more), a simple CMS I designed to edit and view the content of that website, and lastly a server component to communicate between these two services and the database. I am new to docker and currently doing research to figure out how exactly to set up my containers along with the structure of my project.

I would like each of these to be a separate service, and therefor put them in different containers. From my research it seems perfectly possible to put them in separate containers and still have them communicate, but is this the optimal solution? Also given that in the future I might want to scale up so that my backed can supply multiple different frontends all managed from the same CMS.

tldr:

How should I best structure my web-service with docker, as well as assuming my back-end supplies more than one front end managed from a CMS.

Any suggestion for tools, or design patterns that make my life easier are welcome!

答:
Personally, I don't like to think of designing whatever in terms of containers. Containers should be good for deployment process, for their main goal.

If you keep your logic in separate components/services you'll be able to combine them within containers in many different ways.

Once you have criteria what suits your product requirements (performance, price, security etc) you'll configure your docker images in the way you prefer.

So my advise is focus on design of your application first. Start from the number of solutions you have, provide a dockerfile for each one and then see what you will have to change.


问:
Python while loop with input function and multiple condition checks
I am solving the following problem, and came across the situation where I'm unable to define either decision operators or the while loop properly.

The task:

Customers get a monthly discount depending on the length of contract they take out as shown below:

3 – 6 months        2% discount

7 – 12 months       5% discount

over 12 months      10% discount

The program should ask users for their name and the monthly cost of their game package. It should then ask them to enter the contract length they would like. The maximum contract length is 18 months. The program should finally display the entered details and the final cost of the package with the discount applied.

```<code>contract_length = 0
final_cost = 0

#prompt the user to enter their name
user_name = input("What is your name? ")

#prompt the user to enter monthly cost for the game package
package_cost = float(input("Monthly cost of your game package: "))

while contract_length > 0 and contract_length <= 18:

    #prompt the user to enter the contract length
    contract_length = int(input("Enter the contract length you would like: "))

    #selection statement to calculate final cost
    if contract_length > 12:
        discount = (package_cost * 0.1)
        final_cost = format(package_cost - discount,".2f")

    elif contract_length > 6:
        discount = (package_cost * 0.05)
        final_cost = format(package_cost - discount, ".2f")

    elif contract_length >= 3:
        discount = (package_cost * 0.02)
        final_cost = format(package_cost - discount, ".2f")
    else:
        print("Invalid entry")

#display results
print("Name " +user_name)
print("Package Cost £",str(package_cost))
print("Months in Contract " , str(contract_length))
print("The final cost is £",str(final_cost))
</code>```

Error I am having

```<code>What is your name? Jhon
Monthly cost of your game package: 35.12
Name Jhon
Package Cost £ 35.12
Months in Contract  0
The final cost is £ 0
>>>
</code>```

I even tried "and" to "or" but with or operator it's start repeating the input function under while loop. Any help? Thanks.

答:
I would recommend you to have a condition on the final_cost, like this:</p>

```<code>contract_length = 0
final_cost = 'none'

#...

while final_cost == 'none':

    #prompt the user to enter the contract length
    contract_length = int(input("Enter the contract length you would like: "))

    if contract_length > 18:
        print("Invalid entry")
        continue

    #selection statement to calculate final cost
    if contract_length > 12:
        discount = (package_cost * 0.1)
        final_cost = format(package_cost - discount,".2f")

    elif contract_length > 6:
        discount = (package_cost * 0.05)
        final_cost = format(package_cost - discount, ".2f")

    elif contract_length >= 3:
        discount = (package_cost * 0.02)
        final_cost = format(package_cost - discount, ".2f")

    else:
        print("Invalid entry")
</code>```

Body:
I am solving the following problem, and came across the situation where I'm unable to define either decision operators or the while loop properly.

The task:

Customers get a monthly discount depending on the length of contract they take out as shown below:

3 – 6 months        2% discount

7 – 12 months       5% discount

over 12 months      10% discount

The program should ask users for their name and the monthly cost of their game package. It should then ask them to enter the contract length they would like. The maximum contract length is 18 months. The program should finally display the entered details and the final cost of the package with the discount applied.

contract_length = 0
final_cost = 0

#prompt the user to enter their name
user_name = input("What is your name? ")

#prompt the user to enter monthly cost for the game package
package_cost = float(input("Monthly cost of your game package: "))

while contract_length > 0 and contract_length <= 18:

    #prompt the user to enter the contract length
    contract_length = int(input("Enter the contract length you would like: "))

    #selection statement to calculate final cost
    if contract_length > 12:
        discount = (package_cost * 0.1)
        final_cost = format(package_cost - discount,".2f")

    elif contract_length > 6:
        discount = (package_cost * 0.05)
        final_cost = format(package_cost - discount, ".2f")

    elif contract_length >= 3:
        discount = (package_cost * 0.02)
        final_cost = format(package_cost - discount, ".2f")
    else:
        print("Invalid entry")

#display results
print("Name " +user_name)
print("Package Cost £",str(package_cost))
print("Months in Contract " , str(contract_length))
print("The final cost is £",str(final_cost))

Error I am having

What is your name? Jhon
Monthly cost of your game package: 35.12
Name Jhon
Package Cost £ 35.12
Months in Contract  0
The final cost is £ 0
>>>

I even tried "and" to "or" but with or operator it's start repeating the input function under while loop. Any help? Thanks.

Body:
I would recommend you to have a condition on the final_cost, like this:

contract_length = 0
final_cost = 'none'

#...

while final_cost == 'none':

    #prompt the user to enter the contract length
    contract_length = int(input("Enter the contract length you would like: "))

    if contract_length > 18:
        print("Invalid entry")
        continue

    #selection statement to calculate final cost
    if contract_length > 12:
        discount = (package_cost * 0.1)
        final_cost = format(package_cost - discount,".2f")

    elif contract_length > 6:
        discount = (package_cost * 0.05)
        final_cost = format(package_cost - discount, ".2f")

    elif contract_length >= 3:
        discount = (package_cost * 0.02)
        final_cost = format(package_cost - discount, ".2f")

    else:
        print("Invalid entry")


问:
What is the difference between maxSession and maxInstances when using Selenium Grid for parallel testing
I am new to selenium grid. So can someone please explain me the difference between the maxSession and maxInstances. And also how many parallel browsers can be used in one node?

答:
As per the documentation by default, starting a Selenium Grid Node allows for concurrent use of 11 browsers, comprising of 5 Firefox, 5 Chrome and 1 Internet Explorer browser.

The maximum number of concurrent tests is set to 5 by default. To change this configuration and other browser settings, you can pass in parameters to each -browser switch (each switch represents a node based on your parameters). If you use the -browser parameter, the default browsers will be ignored and only what you specify command line will be used.

maxInstances

maxInstances is an optional parameter which can be passed through the -browser optional parameter. To configure a Selenium Grid Node for 20 instances of Firefox version=X.Y.Z you can use the following solution:

Command:

```<code>java -Dwebdriver.gecko.driver=geckodriver.exe -jar selenium-server-standalone-3.141.59.jar -role node -hub http://192.168.1.125:4444/grid/register -browser browserName=firefox,version=X.Y.Z,maxInstances=20,platform=WINDOWS
</code>```

Grid Console Snapshot:

-maxSession

-maxSession is also an optional parameter which can be passed through the -browser optional parameter to configure the maximum number of browsers that can run in parallel on the node. This is different from the maxInstance of supported browsers (Example: For a node that supporting Firefox version A.B.C, Firefox version P.Q.R  and Chrome version X.Y.Z, maxSession=1 will ensure that you never have more than 1 browser running. With maxSession=2 you can have 2 Firefox tests executing at the same time, or 1 Firefox and 1 Chrome test).

Example:

```<code>java -Dwebdriver.gecko.driver=geckodriver.exe -Dwebdriver.chrome.driver=chromedriver.exe -jar selenium-server-standalone-3.141.59.jar -role node -hub http://192.168.1.125:4444/grid/register -browser "browserName=firefox,version=A.B.C,maxInstances=10,platform=WINDOWS" -browser "browserName=firefox,version=P.Q.R,maxInstances=10,platform=WINDOWS" -browser "browserName=chrome,version=X.Y.Z,maxInstances=20,platform=WINDOWS" -maxSession 2
</code>```

Grid Console Snapshot:

Body:
As per the documentation by default, starting a Selenium Grid Node allows for concurrent use of 11 browsers, comprising of 5 Firefox, 5 Chrome and 1 Internet Explorer browser.

The maximum number of concurrent tests is set to 5 by default. To change this configuration and other browser settings, you can pass in parameters to each -browser switch (each switch represents a node based on your parameters). If you use the -browser parameter, the default browsers will be ignored and only what you specify command line will be used.

maxInstances

maxInstances is an optional parameter which can be passed through the -browser optional parameter. To configure a Selenium Grid Node for 20 instances of Firefox version=X.Y.Z you can use the following solution:

Command:

java -Dwebdriver.gecko.driver=geckodriver.exe -jar selenium-server-standalone-3.141.59.jar -role node -hub http://192.168.1.125:4444/grid/register -browser browserName=firefox,version=X.Y.Z,maxInstances=20,platform=WINDOWS

Grid Console Snapshot:

-maxSession

-maxSession is also an optional parameter which can be passed through the -browser optional parameter to configure the maximum number of browsers that can run in parallel on the node. This is different from the maxInstance of supported browsers (Example: For a node that supporting Firefox version A.B.C, Firefox version P.Q.R  and Chrome version X.Y.Z, maxSession=1 will ensure that you never have more than 1 browser running. With maxSession=2 you can have 2 Firefox tests executing at the same time, or 1 Firefox and 1 Chrome test).

Example:

java -Dwebdriver.gecko.driver=geckodriver.exe -Dwebdriver.chrome.driver=chromedriver.exe -jar selenium-server-standalone-3.141.59.jar -role node -hub http://192.168.1.125:4444/grid/register -browser "browserName=firefox,version=A.B.C,maxInstances=10,platform=WINDOWS" -browser "browserName=firefox,version=P.Q.R,maxInstances=10,platform=WINDOWS" -browser "browserName=chrome,version=X.Y.Z,maxInstances=20,platform=WINDOWS" -maxSession 2

Grid Console Snapshot:


问:
Scala (JavaFX) sbt-assembly does not package images/photos
The following code perfectly works inside Eclipse IDE. But, SBT does not assemble the image when packages a jar.</p>

```<code>val myImg = new ImageView("/assets/images/sample.jpg")
val imgLabel = new Label("", myImg)
</code>```

答:
sbt-assembly will take resources from src/main/resources folder into a Jar, not from assets folder - it does not know about it at all.
Try to do next:

1) Add assets folder as resource folder. In your build.sbt add next line:

```<code>resourceDirectory := baseDirectory.value / "assets"
</code>```

2) Load image from the resources, not from the file file path of your project:

```<code>val url: URL = Thread.currentThread().getContextClassLoader.getResource("images/sample.jpg")
val myImg = new ImageView("images/sample.jpg")
</code>```

Hope this help!

Body:
The following code perfectly works inside Eclipse IDE. But, SBT does not assemble the image when packages a jar.

val myImg = new ImageView("/assets/images/sample.jpg")
val imgLabel = new Label("", myImg)

Body:
sbt-assembly will take resources from src/main/resources folder into a Jar, not from assets folder - it does not know about it at all.
Try to do next:

1) Add assets folder as resource folder. In your build.sbt add next line:

resourceDirectory := baseDirectory.value / "assets"

2) Load image from the resources, not from the file file path of your project:

val url: URL = Thread.currentThread().getContextClassLoader.getResource("images/sample.jpg")
val myImg = new ImageView("images/sample.jpg")

Hope this help!


问:
How to find time difference in Hours Minutes and seconds in PHP
I want to calculate the time difference in Hours, Minutes and seconds between two-time intervals.

Here is my Code

```<code> $actualLoginTime = strtotime('13:49:13.0000000');
 $loginTime = strtotime('09:00:00.0000000');
 $nInterval = ($actualLoginTime) - ($loginTime);
 {{date("H:i:s ", strtotime($nInterval))}}
</code>```

It's giving me the wrong Output and showing the difference 5:00:00.

Can you guys please help me.

答:
I found the solution to my Question by using  gmdate() function:

```<code>echo gmdate("H:i:s", $nInterval );
</code>```

Body:
I want to calculate the time difference in Hours, Minutes and seconds between two-time intervals.

Here is my Code

 $actualLoginTime = strtotime('13:49:13.0000000');
 $loginTime = strtotime('09:00:00.0000000');
 $nInterval = ($actualLoginTime) - ($loginTime);
 {{date("H:i:s ", strtotime($nInterval))}}

It's giving me the wrong Output and showing the difference 5:00:00.

Can you guys please help me.

Body:
I found the solution to my Question by using  gmdate() function:

echo gmdate("H:i:s", $nInterval );


问:
Set correct pandas.DataFrame datatypes from cx_Oracle default data types
I have some oracle table with next field datatype:

```<code>ID|              NOT NULL NUMBER
VERSION|         NOT NULL NUMBER
STAT_ACTUAL|     NOT NULL NUMBER
REGION|          NOT NULL VARCHAR2(5 CHAR)
PARENTID|                 NUMBER
CITY|                 VARCHAR2(5 CHAR)
...
</code>```

and if I had trying  to add them from cx_Oracle  to pandas.DataFrame like that:

```<code>import pandas as pd
from sqlalchemy import *

conn = cx_Oracle.connect('datbs/datbs@host/serv')
cursorr = conn.cursor()
SQL  = "select * from table where region = 1"

df= pd.read_sql_query(SQL, con=conn)
</code>```

datatypes looks like:

```<code>ID                          int64
VERSION                     int64
STAT_ACTUAL                 int64
REGION                     object
PARENTID                    int64
CITY                       object
...
</code>```

So, all my oracle varchar2 (which looks in cx_Oracle as ('REGION', <class 'cx_Oracle.STRING'>)) are object in pandas.df!

I tried to convert them by this:

```<code>def OutConverter(value):
    if value is None:
        return ''
    return value

def VarToStr(cursor, name, defaultType, size, precision, scale):
    if defaultType in (cx_Oracle.STRING, cx_Oracle.OBJECT):
        return cursor.var(str, size, cursorr.arraysize, outconverter=OutConverter)

conn.outputtypehandler = VarToStr
</code>```

but result hasn't been taken...df.dtypes show object type again

How to map oracle and cx_Oracle datatypes to pandas df?

答:
I had used manual cast of uncorrectly columns like:

```<code>newdf = df.astype({"REGION": "Int64", ..., "CITY": "Int32", ...})
</code>```

outupt:

```<code>REGION                      int64
CITY                        Int32
</code>```

Body:
I have some oracle table with next field datatype:

ID|              NOT NULL NUMBER
VERSION|         NOT NULL NUMBER
STAT_ACTUAL|     NOT NULL NUMBER
REGION|          NOT NULL VARCHAR2(5 CHAR)
PARENTID|                 NUMBER
CITY|                 VARCHAR2(5 CHAR)
...

and if I had trying  to add them from cx_Oracle  to pandas.DataFrame like that:

import pandas as pd
from sqlalchemy import *

conn = cx_Oracle.connect('datbs/datbs@host/serv')
cursorr = conn.cursor()
SQL  = "select * from table where region = 1"

df= pd.read_sql_query(SQL, con=conn)

datatypes looks like:

ID                          int64
VERSION                     int64
STAT_ACTUAL                 int64
REGION                     object
PARENTID                    int64
CITY                       object
...

So, all my oracle varchar2 (which looks in cx_Oracle as ('REGION', <class 'cx_Oracle.STRING'>)) are object in pandas.df!

I tried to convert them by this:

def OutConverter(value):
    if value is None:
        return ''
    return value

def VarToStr(cursor, name, defaultType, size, precision, scale):
    if defaultType in (cx_Oracle.STRING, cx_Oracle.OBJECT):
        return cursor.var(str, size, cursorr.arraysize, outconverter=OutConverter)

conn.outputtypehandler = VarToStr

but result hasn't been taken...df.dtypes show object type again

How to map oracle and cx_Oracle datatypes to pandas df?

Body:
I had used manual cast of uncorrectly columns like:

newdf = df.astype({"REGION": "Int64", ..., "CITY": "Int32", ...})

outupt:

REGION                      int64
CITY                        Int32


问:
How to add variable in Django model
I want to add variable in Django model and I don't want to save it to database at the same time I want to return this variable to user when calling the endpoint.

this is what i found in the web, but the problem is the variable is not rerun to user

class User (models.Model):
   f_name = models.CharField(max_length=255)
   l_name = models.CharField(max_length=300)
   full_name = ''
```

How to rerun the full_name to user when he call the api ?

答:
You can define model's property:

```<code>class User (models.Model):
   f_name = models.CharField(max_length=255)
   l_name = models.CharField(max_length=300)

   @property
   def full_name(self):
       return self.f_name + self.l_name
</code>```

now you use full_name same way as normal attribute user.full_name.

Title: How to add variable in Django model

Body:
I want to add variable in Django model and I don't want to save it to database at the same time I want to return this variable to user when calling the endpoint.

this is what i found in the web, but the problem is the variable is not rerun to user

class User (models.Model):
   f_name = models.CharField(max_length=255)
   l_name = models.CharField(max_length=300)
   full_name = ''

How to rerun the full_name to user when he call the api ?

Body:
You can define model's property:

class User (models.Model):
   f_name = models.CharField(max_length=255)
   l_name = models.CharField(max_length=300)

   @property
   def full_name(self):
       return self.f_name + self.l_name

now you use full_name same way as normal attribute user.full_name.


问:
How would I limit upload speed from the server in node.js?
How would I limit upload speed from the server in node.js?

Is this even an option?

Scenario: I'm writing some methods to allow users to automated-ly upload files to my server. I want to limit the upload speed to (for instance) 50kB/s (configurable of course).

答: Instead of rolling your own, the normal way to do this in production, is to let your load balancer or entry server throttle the incoming requests.  See http://en.wikipedia.org/wiki/Bandwidth_throttling.  It's not typically something an application needs to handle itself.</p>

ContentLicense: CC BY-SA 3.0


问:
Automatization Spring Cloud Profile
Actually have a little problem.

I want switch the url of my bootstrap.yml

It looks as follows:

```<code>spring:
  application:
    name: <project-name>
  profiles:
    active: dev
  cloud:
    config:
      uri: http://<git-repository>:8080
      fail-fast: false
</code>```

This works, but i want have an propertie or anything what can switch if are in local or another enviroment.

I try to see this documentation but dont see any work for me.

答:
I don't think Spring Cloud is any different from any Spring application, so you could use the Spring profiles.

Something similar is suggested on this answer: https://stackoverflow.com/a/22759706/6908551.

You could define a separate .yml file just for your cloud config uri, like cloud-config-dev.yml, cloud-config-prod.yml. Then, for a Java config, you could have something like:

```<code>@Configuration
public class MyApplicationConfiguration {

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer() {
        String activeProfile = System.getProperty("spring.profiles.active", "production");
        String ymlFilename = "cloud-config-" + activeProfile + ".yml";

        PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
        configurer.setLocation(new ClassPathResource(ymlFilename));

        return configurer;
    }
}
</code>```

Title: Automatization Spring Cloud Profile

Body:
Actually have a little problem.

I want switch the url of my bootstrap.yml

It looks as follows:

spring:
  application:
    name: <project-name>
  profiles:
    active: dev
  cloud:
    config:
      uri: http://<git-repository>:8080
      fail-fast: false

This works, but i want have an propertie or anything what can switch if are in local or another enviroment.

I try to see this documentation but dont see any work for me.

Body:
I don't think Spring Cloud is any different from any Spring application, so you could use the Spring profiles.

Something similar is suggested on this answer: https://stackoverflow.com/a/22759706/6908551.

You could define a separate .yml file just for your cloud config uri, like cloud-config-dev.yml, cloud-config-prod.yml. Then, for a Java config, you could have something like:

@Configuration
public class MyApplicationConfiguration {

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer() {
        String activeProfile = System.getProperty("spring.profiles.active", "production");
        String ymlFilename = "cloud-config-" + activeProfile + ".yml";

        PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
        configurer.setLocation(new ClassPathResource(ymlFilename));

        return configurer;
    }
}


问:
Optimal threshold for imbalanced binar classification problem
i have trouble optimizing threshold for binar classification. I am using 3 models: Logistic Regression, Catboost and Sklearn RandomForestClassifier.

For each model I am doing the following steps:

1) fit model

2) get 0.0 recall for first class (which belongs to 5% of dataset) and 1.0 recall for zero class. (this can't be fixed with gridsearch and class_weight='balanced' parameter.) >:(

3) Find optimal treshold

```<code>fpr, tpr, thresholds = roc_curve(y_train, model.predict_proba(X_train)[:, 1])
optimal_threshold = thresholds[np.argmax(tpr - fpr)]
</code>```

4) Enjoy ~70 recall ratio for both classes.

5) Predict probabilities for test dataset and use optimal_threshold, i calculated above, to get classes.

Here comes the question: when I am starting code again and again, if i don't fix random_state, optimal treshold is variant and shifts quiet dramatically. This leads to dramatic changes in accuracy metrics based on test sample.

Do i need to calculate some average threshold and use it as a constant hard value? Or maybe i have to fix random_state everywhere? Or maybe the method of finding optimal_threshold isnt correct?

答:
If you do not set random_state to a fixed values results will be different in every run. To get reproducible results set random_state everywhere required to a fixed value or, use fixed numpy random seed numpy.random.seed.

https://scikit-learn.org/stable/faq.html#how-do-i-set-a-random-state-for-an-entire-execution

Scikit FAQ mentions it is better to use random_state where required instead of global random state.

Global Random State Example:

```<code>import numpy as np
np.random.seed(42)
</code>```

Some examples locally setting random_state:

```<code>X_train, X_test, y_train, y_test = train_test_split(sample.data, sample.target, test_size=0.3, random_state=0)

skf =  StratifiedKFold(n_splits=10, random_state=0, shuffle=True)

classifierAlgorithm = LGBMClassifier(objective='binary', random_state=0)
</code>```

Body:
i have trouble optimizing threshold for binar classification. I am using 3 models: Logistic Regression, Catboost and Sklearn RandomForestClassifier.

For each model I am doing the following steps:

1) fit model

2) get 0.0 recall for first class (which belongs to 5% of dataset) and 1.0 recall for zero class. (this can't be fixed with gridsearch and class_weight='balanced' parameter.) >:(

3) Find optimal treshold

fpr, tpr, thresholds = roc_curve(y_train, model.predict_proba(X_train)[:, 1])
optimal_threshold = thresholds[np.argmax(tpr - fpr)]

4) Enjoy ~70 recall ratio for both classes.

5) Predict probabilities for test dataset and use optimal_threshold, i calculated above, to get classes.

Here comes the question: when I am starting code again and again, if i don't fix random_state, optimal treshold is variant and shifts quiet dramatically. This leads to dramatic changes in accuracy metrics based on test sample.

Do i need to calculate some average threshold and use it as a constant hard value? Or maybe i have to fix random_state everywhere? Or maybe the method of finding optimal_threshold isnt correct?

Body:
If you do not set random_state to a fixed values results will be different in every run. To get reproducible results set random_state everywhere required to a fixed value or, use fixed numpy random seed numpy.random.seed.

https://scikit-learn.org/stable/faq.html#how-do-i-set-a-random-state-for-an-entire-execution

Scikit FAQ mentions it is better to use random_state where required instead of global random state.

Global Random State Example:

import numpy as np
np.random.seed(42)

Some examples locally setting random_state:

X_train, X_test, y_train, y_test = train_test_split(sample.data, sample.target, test_size=0.3, random_state=0)

skf =  StratifiedKFold(n_splits=10, random_state=0, shuffle=True)

classifierAlgorithm = LGBMClassifier(objective='binary', random_state=0)


问:
vertx-lang-kotlin-coroutines test failed
I have been writing a test class:

```<code>class TestVerticle {

  @BeforeEach
  fun deploy_verticle(vertx: Vertx, testContext: VertxTestContext) {
    vertx.deployVerticle(Verticle(), testContext.completing())
  }

  @Test
  fun test(vertx: Vertx, testContext: VertxTestContext) {
    testContext.verify {
      GlobalScope.launch(vertx.dispatcher()) {

        val reply = vertx.eventBus().requestAwait<Long>(AVIOEXTDMZAddr, "1")

        assert(reply.body() == 1010L)
        testContext.completeNow()
      }

    }
  }
}
</code>```

If the method start() of  Verticle is written in the "common" way, the Test is passed positively:

```<code>override suspend fun start() {
   vertx.eventBus().consumer<String>(AVIOEXTDMZAddr){
         it.reply(1010L)
      }
    }
</code>```

Differently, if I implement a different solution, with the use of vertx-lang-kotlin-coroutines API, the test throws a java.util.concurrent.TimeoutException

```<code>override suspend fun start() {
 val consumerChannel = vertx.eventBus().consumer<String>(AVIOEXTDMZAddr).toChannel(vertx)
    for (msg in consumerChannel) {
        msg.reply(1010L)
      }
    }
</code>```

what am I doing wrong?

答:
Loop on channel blocks the coroutine. In this case, it blocks start of your verticle.

Wrap your for loop in launch block:

```<code>async {
    for (msg in consumerChannel) {
        msg.reply(1010L)
      }
    }
}
</code>```

Body:
I have been writing a test class:

class TestVerticle {

  @BeforeEach
  fun deploy_verticle(vertx: Vertx, testContext: VertxTestContext) {
    vertx.deployVerticle(Verticle(), testContext.completing())
  }

  @Test
  fun test(vertx: Vertx, testContext: VertxTestContext) {
    testContext.verify {
      GlobalScope.launch(vertx.dispatcher()) {

        val reply = vertx.eventBus().requestAwait<Long>(AVIOEXTDMZAddr, "1")

        assert(reply.body() == 1010L)
        testContext.completeNow()
      }

    }
  }
}

If the method start() of  Verticle is written in the "common" way, the Test is passed positively:

override suspend fun start() {
   vertx.eventBus().consumer<String>(AVIOEXTDMZAddr){
         it.reply(1010L)
      }
    }

Differently, if I implement a different solution, with the use of vertx-lang-kotlin-coroutines API, the test throws a java.util.concurrent.TimeoutException

override suspend fun start() {
 val consumerChannel = vertx.eventBus().consumer<String>(AVIOEXTDMZAddr).toChannel(vertx)
    for (msg in consumerChannel) {
        msg.reply(1010L)
      }
    }

what am I doing wrong?

Body:
Loop on channel blocks the coroutine. In this case, it blocks start of your verticle.

Wrap your for loop in launch block:

async {
    for (msg in consumerChannel) {
        msg.reply(1010L)
      }
    }
}


问:
Python3 installed using homebrew but not updated version being used
On my Mac terminal i've installed python3 (3.7.6) using homebrew - e.g. if I issue command to upgrade via homebrew, it returns the up to date version:

```<code>$brew upgrade python3
Warning: python3 3.7.6_1 already installed
</code>```

However when I ask for the version it tells me an older version (3.4.0) is installed:

```<code>$python3 --version
Python 3.4.0
</code>```

So it's installed but not updated. I'd quite like 3.6 or later on my mac. I've tried uninstalling and reinstalling using homebrew, and had no luck. Wondering if anyone has any ideas?

//

Sidenote (1) - i'm relatively new to homebrew... $ brew doctor returns config scripts "outside your system or Homebrew directories" - not sure if this helps, and if this is the issue where to move them to.

```<code>/Library/Frameworks/Python.framework/Versions/3.4/bin/python3.4m-config
/Library/Frameworks/Python.framework/Versions/3.4/bin/python3-config
/Library/Frameworks/Python.framework/Versions/3.4/bin/python3.4-config
</code>```

Sidenote (2) - 3.7.6 isn't the newest version out, but this is the latest version that homebrew will install. Is there any way to get an even newer version?

答:
Quick fix:

You should be able to run the required version by running python3.7 instead of python3. You can set up an alias if you like with

"alias python=/usr/local/bin/python3.7"

where you put the desired binary on the RHS. This will create an alias for your current session. To always evoke this functionality, you can add this line to your bashrc file so this alias will work every time you log in to a new session

echo "alias python=/usr/local/bin/python3.7" >> ~/.bashrc

These commands were lifted from
https://opensource.com/article/19/5/python-3-default-mac
which explains some do and do-nots.

Alternative:

Also check out Python virtual environments, particularly virtualenv and virtualenvwrapper, which are great tools for separating out your Python working environments and allow you to set default Python version for each project separately, as well as managing any modules you pip install separately for each project. This is much cleaner in my opinion.

https://www.bogotobogo.com/python/python_virtualenv_virtualenvwrapper.php

Body:
On my Mac terminal i've installed python3 (3.7.6) using homebrew - e.g. if I issue command to upgrade via homebrew, it returns the up to date version:

$brew upgrade python3
Warning: python3 3.7.6_1 already installed

However when I ask for the version it tells me an older version (3.4.0) is installed:

$python3 --version
Python 3.4.0

So it's installed but not updated. I'd quite like 3.6 or later on my mac. I've tried uninstalling and reinstalling using homebrew, and had no luck. Wondering if anyone has any ideas?

//

Sidenote (1) - i'm relatively new to homebrew... $ brew doctor returns config scripts "outside your system or Homebrew directories" - not sure if this helps, and if this is the issue where to move them to.

/Library/Frameworks/Python.framework/Versions/3.4/bin/python3.4m-config
/Library/Frameworks/Python.framework/Versions/3.4/bin/python3-config
/Library/Frameworks/Python.framework/Versions/3.4/bin/python3.4-config

Sidenote (2) - 3.7.6 isn't the newest version out, but this is the latest version that homebrew will install. Is there any way to get an even newer version?


问:
I need to backup views and procedures with generate scripts on sql server
I need to backup views and procedures with generate scripts on sql server

it's possible to do?

答: You can do it with SQL Server Mangement Studio. Right click on a database and select Tasks - Generate scripts...</p>


问:
How to plot a graph from a dataframe with a condition?
I have some data of some options where I want to plot the data yet with the conditions of either a call or a put. The following data looks like this:

```<code>            underlying_last  exchange  ...   IVBid   IVAsk
underlying                             ...
BP                    39.00         *  ...  0.0000  4.0743
BP                    39.00         *  ...  0.0000  3.0846
BP                    39.00         *  ...  0.0000  3.9024
BP                    39.00         *  ...  0.0000  2.6644
BP                    39.00         *  ...  0.0000  3.3525
</code>```

There is a column 'type' which contains if the option is a call or a put. I want to select only call values and plot the quote date against the price. I have the following code:

```<code>#import modules needed
import numpy as np
import pandas_datareader as web
import matplotlib.pyplot as plt
import datetime as dt
import pandas as pd
from matplotlib import style
from matplotlib import rc
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
import GPy
from numpy.random import randn

#styel of plot
style.use('default')

df = pd.read_csv('BP_2019.csv',index_col = 'underlying',parse_dates = ['expiration','quotedate'])
c = df['type'] = "call"
x = df[c].index
y = df[c]['bid'].tolist()

fig, ax = plt.subplots()
ax.plot(x,y)
</code>```

I am receiving the following error:

```<code>  File "pandas/_libs/hashtable_class_helper.pxi", line 1614, in pandas._libs.hashtable.PyObjectHashTable.get_item

KeyError: 'call'
</code>```

答:
to get x, y for your " plot the quote date against the price" try:</p>

```<code>x = df['date'][df.type == 'call']
y = df['bid'][df.type == 'call']
</code>```

Body:
I have some data of some options where I want to plot the data yet with the conditions of either a call or a put. The following data looks like this:

            underlying_last  exchange  ...   IVBid   IVAsk
underlying                             ...
BP                    39.00         *  ...  0.0000  4.0743
BP                    39.00         *  ...  0.0000  3.0846
BP                    39.00         *  ...  0.0000  3.9024
BP                    39.00         *  ...  0.0000  2.6644
BP                    39.00         *  ...  0.0000  3.3525

There is a column 'type' which contains if the option is a call or a put. I want to select only call values and plot the quote date against the price. I have the following code:

#import modules needed
import numpy as np
import pandas_datareader as web
import matplotlib.pyplot as plt
import datetime as dt
import pandas as pd
from matplotlib import style
from matplotlib import rc
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
import GPy
from numpy.random import randn

#styel of plot
style.use('default')

df = pd.read_csv('BP_2019.csv',index_col = 'underlying',parse_dates = ['expiration','quotedate'])
c = df['type'] = "call"
x = df[c].index
y = df[c]['bid'].tolist()

fig, ax = plt.subplots()
ax.plot(x,y)

I am receiving the following error:

  File "pandas/_libs/hashtable_class_helper.pxi", line 1614, in pandas._libs.hashtable.PyObjectHashTable.get_item

KeyError: 'call'

Body:
to get x, y for your " plot the quote date against the price" try:

x = df['date'][df.type == 'call']
y = df['bid'][df.type == 'call']


问:
PasswordBox PasswordHelper multibinding
In WPF the Password property of a PasswordBox is not a DependencyProperty so I can't bind to it directly. As a workaround I am using this PasswordHelper from https://www.wpftutorial.net/PasswordBox.html which attaches a PasswordHelper.Password to the PasswordBox so I can bind to it.

To prevent the password from staying in the DataContext as plain text I would like to use a converter which generates a salted hash of the password before saving it to the DataContext. As I need to save both the salt and the salted hash to the DataContext I am using a MultiBinding and  a IMultiValueConverter converter StringToSaltedHashConverter.

My problem is that the Password and PasswordSalt properties of my DataContext are not getting updated when I fill the PasswordBox. I have checked with Snoop and both the Password and PasswordHelper.Password properties of the PasswordBoxare changing accordingly to what I type. Also my StringToSaltedHashConverter is being called and I am returning the correct values.

I have some other bindings on this form (username, first name, last name, gender...) and they all work fine. This is the only one that is not updating.

¿Why is my DataContext not getting updated?

XAML:

```<code><PasswordBox x:Name="Password"
             Style="{DynamicResource PasswordBoxStyle1}"
             local:PasswordHelper.Attach="True">
    <local:PasswordHelper.Password>
        <MultiBinding Converter="{StaticResource StringToSaltedHashConverter}"
                      Mode="OneWayToSource">
            <Binding Path="Password" />
            <Binding Path="PasswordSalt" />
        </MultiBinding>
    </local:PasswordHelper.Password>
</PasswordBox>
</code>```

Code behind:

```<code>public class StringToSaltedHashConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        string str = value as string;
        string salt = Hash.CreateSalt();
        string hash = Hash.CreateHash(str, salt);
        object[] vs = { hash, salt };
        return vs;
    }
}
</code>```

答:
Before I need the password from a PasswordBox the User will tell me that he has finished with input by pressing a button.

The best option for me is to use the CommandParameter of the Button with the LoginCommand:

<StackPanel
        Width="300"
        HorizontalAlignment="Center"
        VerticalAlignment="Center">

    <TextBox Text="{Binding Username}" />

    <PasswordBox PasswordChanged="PasswordChanged" />
    <StackPanel
            Orientation="Horizontal">
        <Button
                Name="LoginButton"
                Command="{Binding LoginCommand}"
                Content="Login" />
    </StackPanel>
</StackPanel>
```

<p>View code</p>

<pre class="lang-cs prettyprint-override"><code>private void PasswordChanged( object sender, RoutedEventArgs e )
{
    LoginButton.CommandParameter = ( sender as PasswordBox ).SecurePassword;
}
</code>```

ViewModel Command

Login = ReactiveCommand.CreateFromTask( async ( SecureString password, CancellationToken cancellationToken ) =>
{
    var loggedIn = await AuthenticationService.LoginAsync( Username, password, cancellationToken );
    ...
} );
```

Title: PasswordBox PasswordHelper multibinding

Body:
In WPF the Password property of a PasswordBox is not a DependencyProperty so I can't bind to it directly. As a workaround I am using this PasswordHelper from https://www.wpftutorial.net/PasswordBox.html which attaches a PasswordHelper.Password to the PasswordBox so I can bind to it.

To prevent the password from staying in the DataContext as plain text I would like to use a converter which generates a salted hash of the password before saving it to the DataContext. As I need to save both the salt and the salted hash to the DataContext I am using a MultiBinding and  a IMultiValueConverter converter StringToSaltedHashConverter.

My problem is that the Password and PasswordSalt properties of my DataContext are not getting updated when I fill the PasswordBox. I have checked with Snoop and both the Password and PasswordHelper.Password properties of the PasswordBoxare changing accordingly to what I type. Also my StringToSaltedHashConverter is being called and I am returning the correct values.

I have some other bindings on this form (username, first name, last name, gender...) and they all work fine. This is the only one that is not updating.

¿Why is my DataContext not getting updated?

XAML:

<PasswordBox x:Name="Password"
             Style="{DynamicResource PasswordBoxStyle1}"
             local:PasswordHelper.Attach="True">
    <local:PasswordHelper.Password>
        <MultiBinding Converter="{StaticResource StringToSaltedHashConverter}"
                      Mode="OneWayToSource">
            <Binding Path="Password" />
            <Binding Path="PasswordSalt" />
        </MultiBinding>
    </local:PasswordHelper.Password>
</PasswordBox>

Code behind:

public class StringToSaltedHashConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        string str = value as string;
        string salt = Hash.CreateSalt();
        string hash = Hash.CreateHash(str, salt);
        object[] vs = { hash, salt };
        return vs;
    }
}

Body:
Before I need the password from a PasswordBox the User will tell me that he has finished with input by pressing a button.

The best option for me is to use the CommandParameter of the Button with the LoginCommand:

<StackPanel
        Width="300"
        HorizontalAlignment="Center"
        VerticalAlignment="Center">
    <Label Content="Username:" />
    <TextBox Text="{Binding Username}" />
    <Label Content="Password:" />
    <PasswordBox PasswordChanged="PasswordChanged" />
    <StackPanel
            Orientation="Horizontal">
        <Button
                Name="LoginButton"
                Command="{Binding LoginCommand}"
                Content="Login" />
    </StackPanel>
</StackPanel>

View code

private void PasswordChanged( object sender, RoutedEventArgs e )
{
    LoginButton.CommandParameter = ( sender as PasswordBox ).SecurePassword;
}

ViewModel Command

Login = ReactiveCommand.CreateFromTask( async ( SecureString password, CancellationToken cancellationToken ) =>
{
    var loggedIn = await AuthenticationService.LoginAsync( Username, password, cancellationToken );
    ...
} );


问:
How to iterate a big list to make it smaller for a REST call using Java streams?
I have logic something like this to process in chunks.

```<code>List<String> bigList = getList(); // Returns a big list of 1000 recs
int startIndex=0;
boolean entireListNotProcessed=false;
while(entireListNotProcessed) {
   int endIndex = startIndex + 100;
   if(endIndex > myList.size()-1) {
      endIndex=myList.size()-1;
   }
   List<String> subList= bigList.subList(startIndex, endIndex);
   //call Rest API with subList and update entireListNotProcessed flag...
}
</code>```

Is there a better way of doing this iteration using java streams?

答:
You can do similar to this answer, by creating range with stepping and then subList:

int step = 100;
IntStream
  .iterate(0, o -> o < bigList.size(), o -> o + step)
  .mapToObj(i -> bigList.subList(i, Math.min(i + step, bigList.size()))
  .forEach(subList -> callRestApi(subList));
```

<p>Or you can extract method:</p>

<pre class="lang-java prettyprint-override"><code>private static <T>  Stream<List<T>> partition(List<T> list, int step) {
    return IntStream
        .iterate(0, o -> o < list.size(), o -> o + step)
        .mapToObj(i -> list
            .subList(i, Math.min(i + step, list.size()))
        );
}
</code>```

and then

```<code>partition(bigList, 100).forEach(subList -> callRestApi(subList));
</code>```

Body:
I have logic something like this to process in chunks.

List<String> bigList = getList(); // Returns a big list of 1000 recs
int startIndex=0;
boolean entireListNotProcessed=false;
while(entireListNotProcessed) {
   int endIndex = startIndex + 100;
   if(endIndex > myList.size()-1) {
      endIndex=myList.size()-1;
   }
   List<String> subList= bigList.subList(startIndex, endIndex);
   //call Rest API with subList and update entireListNotProcessed flag...
}

Is there a better way of doing this iteration using java streams?

Body:
You can do similar to this answer, by creating range with stepping and then subList:

int step = 100;
IntStream
  .iterate(0, o -> o < bigList.size(), o -> o + step)
  .mapToObj(i -> bigList.subList(i, Math.min(i + step, bigList.size()))
  .forEach(subList -> callRestApi(subList));

Or you can extract method:

private static <T>  Stream<List<T>> partition(List<T> list, int step) {
    return IntStream
        .iterate(0, o -> o < list.size(), o -> o + step)
        .mapToObj(i -> list
            .subList(i, Math.min(i + step, list.size()))
        );
}

and then

partition(bigList, 100).forEach(subList -> callRestApi(subList));