问:
Trying to get the duplicate serial numbers repeating more than three times from this list using perl or awk command
For example: From the below example I was trying to get the duplicated serial numbers which only repeats more than three times.

```<code>Time     serial no's     oui   product class
23:38:17 G1A114071803436|D4A928|FiOS-Gen4
23:38:18 G1A117072200565|D4A928|FiOS-Gen4
22:38:17 G1A114071803436|D4A928|FiOS-Gen4
23:38:17 G1A114071803436|D4A928|FiOS-Gen4
23:38:18 G1A117072200565|D4A928|FiOS-Gen4
23:07:51 G1A114080901301|D4A928|FiOS-Gen4
23:10:36 G1A114080901301|D4A928|FiOS-Gen4
20:11:51 G1A114080901301|D4A928|FiOS-Gen4
</code>```

So if I return the output it should be something like this:

Only duplicated serial no's

output should be:

```<code>G1A114080901301|D4A928|FiOS-Gen4
G1A114071803436|D4A928|FiOS-Gen4
</code>```

(as this serial no's are only repeating more than two times)

Commands I used:

```<code>sort  sed2file.csv | uniq -id > sortedfile.csv
perl -ne 'print if $a{$_}++' filename
</code>```

答:
Perl command line solution (assuming your data is in a file called data.txt):

```<code>perl -anE 'BEGIN { <> } \
           END { for (keys %id) { say $_ if $id{$_} > 2 } } \
           $id{$F[1]}++' data.txt
</code>```

I've split the code across three lines (which is, to be honest, a bit big for a command-line program). I hope that makes it easier to follow.

-anE : Command line options. -a Autosplits input into @F, -n loops over input a line at a time, -E executes the code that follows.

BEGIN { <> } : Block that is executed before starting to read the input file. Simply reads a line from the file (to skip the headers).

END { ... } : Block that executed after the input file is all read.

for (keys %id) { ... } : Execute this loop for every key in the %id hash.

say $_ if $id{$_} > 2 : If we've seen more than two lines, print the key.

$id{$F[1]}++ : This is all of the code that is actually executed for each line in the input file. The input record is split on whitespace and stored in @F. $F[1] is, therefore, the second field in the record (the ID that you're interested in) and we increment the value in the %id hash using that ID as a key.

Body:
For example: From the below example I was trying to get the duplicated serial numbers which only repeats more than three times.

Time     serial no's     oui   product class
23:38:17 G1A114071803436|D4A928|FiOS-Gen4
23:38:18 G1A117072200565|D4A928|FiOS-Gen4
22:38:17 G1A114071803436|D4A928|FiOS-Gen4
23:38:17 G1A114071803436|D4A928|FiOS-Gen4
23:38:18 G1A117072200565|D4A928|FiOS-Gen4
23:07:51 G1A114080901301|D4A928|FiOS-Gen4
23:10:36 G1A114080901301|D4A928|FiOS-Gen4
20:11:51 G1A114080901301|D4A928|FiOS-Gen4

So if I return the output it should be something like this:

Only duplicated serial no's

output should be:

G1A114080901301|D4A928|FiOS-Gen4
G1A114071803436|D4A928|FiOS-Gen4

(as this serial no's are only repeating more than two times)

Commands I used:

sort  sed2file.csv | uniq -id > sortedfile.csv
perl -ne 'print if $a{$_}++' filename

Body:
Perl command line solution (assuming your data is in a file called data.txt):

perl -anE 'BEGIN { <> } \
           END { for (keys %id) { say $_ if $id{$_} > 2 } } \
           $id{$F[1]}++' data.txt

I've split the code across three lines (which is, to be honest, a bit big for a command-line program). I hope that makes it easier to follow.

-anE : Command line options. -a Autosplits input into @F, -n loops over input a line at a time, -E executes the code that follows.

BEGIN { <> } : Block that is executed before starting to read the input file. Simply reads a line from the file (to skip the headers).

END { ... } : Block that executed after the input file is all read.

for (keys %id) { ... } : Execute this loop for every key in the %id hash.

say $_ if $id{$_} > 2 : If we've seen more than two lines, print the key.

$id{$F[1]}++ : This is all of the code that is actually executed for each line in the input file. The input record is split on whitespace and stored in @F. $F[1] is, therefore, the second field in the record (the ID that you're interested in) and we increment the value in the %id hash using that ID as a key.


来源: stackexchange

问:
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.

答:
handler.setRemoteDirectoryExpressionString(this.remoteDir.concat("/").concat(exp.getValue().toString()));

The expression has to be evaluated at runtime against a messagee, you are evaluating the expression during configuration time against nothing.

Use

```<code>"'" + this.remoteDir + "/' + headers['path']"
</code>```

so the headers['path'] is evaluated against the message sent to the handler.

ContentLicense: CC BY-SA 4.0

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:
handler.setRemoteDirectoryExpressionString(this.remoteDir.concat("/").concat(exp.getValue().toString()));

The expression has to be evaluated at runtime against a messagee, you are evaluating the expression during configuration time against nothing.

Use

"'" + this.remoteDir + "/' + headers['path']"

so the headers['path'] is evaluated against the message sent to the handler.


问:
Phabricator installation problem " FATAL ERROR: Unable to load the "Arcanist" library. Put "arcanist/" next to "phabricator/" on disk."
I'm trying to install Phabricator with that documentation: https://websiteforstudents.com/install-phabricator-platform-on-ubuntu-16-04-18-04-with-apache2-mariadb-and-php-7-2

When i use "sudo ./bin/config set mysql.host localhost" command there was a error:

```<code>FATAL ERROR: Unable to load the "Arcanist" library. Put "arcanist/" next to "phabricator/" on disk.
</code>```

Any solution?

答:
It looks like the most recent git commit is missing some critical files from the arcanist directory.

I downloaded commit 26f853b from 2 days ago (26f853b6343083c3ddfb6a393843edb20248ee71.zip) from here and the script ran through. I haven't tested if phabricator actually works with it however.

You might want to submit a bugreport.

Body:
I'm trying to install Phabricator with that documentation: https://websiteforstudents.com/install-phabricator-platform-on-ubuntu-16-04-18-04-with-apache2-mariadb-and-php-7-2

When i use "sudo ./bin/config set mysql.host localhost" command there was a error:

FATAL ERROR: Unable to load the "Arcanist" library. Put "arcanist/" next to "phabricator/" on disk.

Any solution?


问:
Create fixed sidebar and fixed menu bar with css/html with "browser chosen width/height"
I want to create a fixed sidebar and fixed menu bar and a content page like this example with bootstrap:

For the menu bar, I use the following css (which works)

```<code>.fixed-top {
  position: fixed;
  top: 0;
  right: 0;
  left: 0;
  z-index: 0;
}
</code>```

But what css shall I use for the sidebar? Because I do not know the height of the menubar (and I do not want set it explicitly, but let the browser choose). How to attach the sidebar to the bottom of the menu bar?

```<code>.fixed-left {
  position: fixed;
  left: 0;
  z-index: 0;
  .... (how to set it fixed to the bottom of the menubar?)
}
</code>```

Thanks!

答:
Modify some css in .fixed-left

```<code>.fixed-left {
  position: fixed;
  top: 0; // set it equal as the height of fixed-top
  bottom: 0; // so that it will stick to bottom
  left: 0;
  z-index: 0;
  overflow-y: auto; // it will have the scroll if it has more content
  width: 250px; // set as per your requirement
}
</code>```

Body:
I want to create a fixed sidebar and fixed menu bar and a content page like this example with bootstrap:

For the menu bar, I use the following css (which works)

.fixed-top {
  position: fixed;
  top: 0;
  right: 0;
  left: 0;
  z-index: 0;
}

But what css shall I use for the sidebar? Because I do not know the height of the menubar (and I do not want set it explicitly, but let the browser choose). How to attach the sidebar to the bottom of the menu bar?

.fixed-left {
  position: fixed;
  left: 0;
  z-index: 0;
  .... (how to set it fixed to the bottom of the menubar?)
}

Thanks!

Body:
Modify some css in .fixed-left

.fixed-left {
  position: fixed;
  top: 0; // set it equal as the height of fixed-top
  bottom: 0; // so that it will stick to bottom
  left: 0;
  z-index: 0;
  overflow-y: auto; // it will have the scroll if it has more content
  width: 250px; // set as per your requirement
}


问:
I want to rewrite URI in VirtualService for from regex to regex
I want to run the following API. While I want to run the following script. But I am not able to get the expected output.

```<code> - match:
      uri:
        regex: \/test\/pune/\/(.+)\/bk
   rewrite:
      uri: \/pune/\/(.+)\/bk
    route:
    - destination:
        host: yerwada
        port:
          number: 8080
</code>```

But I am getting following output -

{"level":50,"time":1581684841254,"pid":18,"hostname":"test-ob-scheduled-payments-7cfb6779b8-x6f9b","err":{"type":"Error","message":"Parse
  Error","stack":"Error: Parse
  Error","bytesParsed":4,"code":"HPE_INVALID_URL","rawPacket":{"type":"Buffer","data":[71,69,84,32,92,47,99,100,115,45,97,117,92,47,118,49,92,47,98]}},"v":1}

答: HttpRewrite cannot use regex, it can only accept string values.</p>

Body:
I want to run the following API. While I want to run the following script. But I am not able to get the expected output.

 - match:
      uri:
        regex: \/test\/pune/\/(.+)\/bk
   rewrite:
      uri: \/pune/\/(.+)\/bk
    route:
    - destination:
        host: yerwada
        port:
          number: 8080

But I am getting following output -

{"level":50,"time":1581684841254,"pid":18,"hostname":"test-ob-scheduled-payments-7cfb6779b8-x6f9b","err":{"type":"Error","message":"Parse
  Error","stack":"Error: Parse
  Error","bytesParsed":4,"code":"HPE_INVALID_URL","rawPacket":{"type":"Buffer","data":[71,69,84,32,92,47,99,100,115,45,97,117,92,47,118,49,92,47,98]}},"v":1}


问:
How to get CSS Selector from DOMElement PHP Symfony
In Chrome I can inspect an Element -> right click -> copy -> copy Xpath (or selector).

Now, using PHP Symfony I find an Element like this, lets assume it returns 1 DOMElement node:

```<code>$node = $crawler->filterXPath("//*[text()='Super dee question']");
</code>```

Now, how can I receive the CSS selector as if this $node were a node on Google Chrome, and I did the steps above: right click and inspect $node on chrome page -> copy -> copy Xpath. Obviously I'm not looking for an Xpath that contains 'Super Dee', but something more like

```<code>//*[@id="product_addtocart_form"]/div[2]/h1
</code>```

EDIT: It appears that I can do DOMNode::getNodePath ( void ), however when using Chrome it usually can identify the nearest @id and use that, which is much more accurate than DOMNode::getNodePath ( void ) which looks something like:

```<code>/html/body/div[2]/div/div[1]/div[2]/div[2]/div[3]/div[1]/form/div[2]/h1
</code>```

答:
You can use CSS attributes selector like this

```<code>$housingText = trim($crawler->filter('[id="household_housing"] option:selected')->text());
</code>```

For more info https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors

Body:
In Chrome I can inspect an Element -> right click -> copy -> copy Xpath (or selector).

Now, using PHP Symfony I find an Element like this, lets assume it returns 1 DOMElement node:

$node = $crawler->filterXPath("//*[text()='Super dee question']");

Now, how can I receive the CSS selector as if this $node were a node on Google Chrome, and I did the steps above: right click and inspect $node on chrome page -> copy -> copy Xpath. Obviously I'm not looking for an Xpath that contains 'Super Dee', but something more like

//*[@id="product_addtocart_form"]/div[2]/h1

EDIT: It appears that I can do DOMNode::getNodePath ( void ), however when using Chrome it usually can identify the nearest @id and use that, which is much more accurate than DOMNode::getNodePath ( void ) which looks something like:

/html/body/div[2]/div/div[1]/div[2]/div[2]/div[3]/div[1]/form/div[2]/h1

Body:
You can use CSS attributes selector like this

$housingText = trim($crawler->filter('[id="household_housing"] option:selected')->text());

For more info https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors


问:
How to include matching values when using sort_values + head()
I have a df:

```<code>       Date Symbol Person
0   2019 Q3      A    Bob
1   2019 Q3      A    Jon
2   2019 Q3      B    Rob
3   2019 Q3      B    Ron
4   2019 Q3      C    Jay
5   2019 Q3      C    Ray
6   2019 Q3      D    Fay
7   2019 Q2      A    Bob
8   2019 Q2      A    Jon
9   2019 Q2      B    Rob
10  2019 Q2      B    Ron
11  2019 Q2      C    Jay
12  2019 Q2      C    Ray
13  2019 Q2      D    Fay
14  2019 Q2      D    Bre
15  2019 Q2      E    Jon
16  2019 Q2      F    Ron
</code>```

Where I am trying to find the top two Symbols per quarter by count. But as you can see, sometimes there are more than two Symbols with the same count value for a given Date (e.g., symbols A, B, and C in 2019 Q3, and symbols A, B, C and D in 2019 Q2.

When I do:

```<code>df['Count'] = df.groupby(['Date', 'Symbol'])['Person'].transform('nunique')
df = df[['Date', 'Symbol', 'Count']]
df.drop_duplicates(subset=None, keep="first", inplace=True)
df = df.sort_values('Count', ascending=False).groupby('Date').head(2).sort_index()
</code>```

My output only includes the first two:

```<code>   Date Symbol  Count
2019 Q3      A      2
2019 Q3      B      2
2019 Q2      A      2
2019 Q2      B      2
</code>```

But how can I get it so that all the tied counts instances are included too, so that it looks like:

```<code>   Date Symbol  Count
2019 Q3      A      2
2019 Q3      B      2
2019 Q3      C      2
2019 Q2      A      2
2019 Q2      B      2
2019 Q2      C      2
2019 Q2      D      2
</code>```

答:
This worked for me: </p>

```<code>    new_df = pd.DataFrame()
    for q in df.Date.unique():
        f = df.loc[df.Date == q]
        f = f.groupby(['Date', 'Symbol']).size().nlargest(n,keep='all').to_frame().reset_index()
        f.columns = ['Date', 'Symbol', 'Count']
        new_df = pd.concat([new_df, f])
</code>```

Body:
I have a df:

       Date Symbol Person
0   2019 Q3      A    Bob
1   2019 Q3      A    Jon
2   2019 Q3      B    Rob
3   2019 Q3      B    Ron
4   2019 Q3      C    Jay
5   2019 Q3      C    Ray
6   2019 Q3      D    Fay
7   2019 Q2      A    Bob
8   2019 Q2      A    Jon
9   2019 Q2      B    Rob
10  2019 Q2      B    Ron
11  2019 Q2      C    Jay
12  2019 Q2      C    Ray
13  2019 Q2      D    Fay
14  2019 Q2      D    Bre
15  2019 Q2      E    Jon
16  2019 Q2      F    Ron

Where I am trying to find the top two Symbols per quarter by count. But as you can see, sometimes there are more than two Symbols with the same count value for a given Date (e.g., symbols A, B, and C in 2019 Q3, and symbols A, B, C and D in 2019 Q2.

When I do:

df['Count'] = df.groupby(['Date', 'Symbol'])['Person'].transform('nunique')
df = df[['Date', 'Symbol', 'Count']]
df.drop_duplicates(subset=None, keep="first", inplace=True)
df = df.sort_values('Count', ascending=False).groupby('Date').head(2).sort_index()

My output only includes the first two:

   Date Symbol  Count
2019 Q3      A      2
2019 Q3      B      2
2019 Q2      A      2
2019 Q2      B      2

But how can I get it so that all the tied counts instances are included too, so that it looks like:

   Date Symbol  Count
2019 Q3      A      2
2019 Q3      B      2
2019 Q3      C      2
2019 Q2      A      2
2019 Q2      B      2
2019 Q2      C      2
2019 Q2      D      2

Body:
This worked for me:

    new_df = pd.DataFrame()
    for q in df.Date.unique():
        f = df.loc[df.Date == q]
        f = f.groupby(['Date', 'Symbol']).size().nlargest(n,keep='all').to_frame().reset_index()
        f.columns = ['Date', 'Symbol', 'Count']
        new_df = pd.concat([new_df, f])


问:
Error: An uncaught Exception was encountered
I receive this error:

An uncaught Exception was encountered Type: ArgumentCountError

Message: Too few arguments to function
  Home::cadastroOrcamentoCliente(), 0 passed in
  C:\xampp\htdocs\sistema_financas_old\system\core\CodeIgniter.php on
  line 532 and exactly 6 expected

Filename:
  C:\xampp\htdocs\sistema_financas_old\application\controllers\Home.php

Line Number: 1116

Backtrace:

File: C:\xampp\htdocs\sistema_financas_old\index.php Line: 315
  Function: require_once

This is my code:

```<code>//Inicio de desenvolvimento new window client.
    //New Página para gerar pedido de cliente.
    function cadastroOrcamentoCliente($cpfcnpj=null, $tipo_pessoa=null, $dados = null, $id_pf, $id_cliente, $id_cadastro) {
        $tipo_login = $this->session->userdata('tipo_login');
        if ($tipo_login == '1' || $tipo_login == '4' || $tipo_login == '5') {
            $dadosPessoa['tipo_pessoa'] = null;
            $dadosOrcamento['str'] = $this->load->view('admin/compras/popup_cadastro', $dadosPessoa, true);
            if ($tipo_pessoa == 1) {
                $dadosOrcamento['cpf'] = $cpfcnpj;
                $dadosOrcamento['cnpj'] = null;
            } else if ($tipo_pessoa == 2) {
                $dadosOrcamento['cpf'] = null;
                $dadosOrcamento['cnpj'] = $cpfcnpj;
            } else {
                $dadosOrcamento['cpf'] = $cpfcnpj;
                $dadosOrcamento['cnpj'] = $cpfcnpj;
            }

            if ($this->alteracao->editEndereco($id_cadastro) && $this->alteracao->editPessoaFisica($id_pf) &&
                $this->alteracao->editCliente($id_cliente) && $this->alteracao->editCadastroComum($id_cadastro) && $this->alteracao->editarDadosBancarios($id_cadastro)) {
            $data_cad = date("d/m/Y");
            $hora_cad = date("H:i:s");
            $this->alteracao->cadastroHistorico('Dados do cliente editados', $id_cadastro, $data_cad, $hora_cad);
            $this->alteracao->mensagemAlerta("Dados alterados com sucesso!", 1, "home/cadastros", $id_cadastro);

            $dadosOrcamento['orcamento'] = $this->compras_m->buscarOrcamentoAtual($this->session->userdata('id_orcamento'));
            $this->load->view('admin/head');
            $dadosBarra['dadosB'] = $this->financeiro->listaContas();
            $this->load->view('admin/barraSuperior', $dadosBarra);
            $dadosLogo['logo'] = $this->adm->retornaLogo();
            $this->load->view('admin/menu', $dadosLogo);
            $this->load->view('admin/vendas/cadastro_orcamento_cliente', $dadosOrcamento);
            $this->load->view('admin/footer');
        } else {
            $dados['mensagem'] = null;
            $this->paginas($dados);
        }
    }
    }
</code>```

im calling here

```<code> <form method="post" action="<?php echo site_url('pedido/cadastroOrcamentoVendaCliente') ?>">
</code>```

just create a new screen and need additional to the project

答:
If you are posting fields to the cadastroOrcamentoCliente you shouldn't define a parameter count. POST fields are not treated as function parameters, which is why you're getting the error (you're declaring that the function must receive 6 parameters exactly, but it's getting none)

just declare the function as function cadastroOrcamentoCliente() and then handle the post'ed fields via $this->input->post('fieldname') (after validating everything with the form validation helper)

Body:
I receive this error:

An uncaught Exception was encountered Type: ArgumentCountError

Message: Too few arguments to function
  Home::cadastroOrcamentoCliente(), 0 passed in
  C:\xampp\htdocs\sistema_financas_old\system\core\CodeIgniter.php on
  line 532 and exactly 6 expected

Filename:
  C:\xampp\htdocs\sistema_financas_old\application\controllers\Home.php

Line Number: 1116

Backtrace:

File: C:\xampp\htdocs\sistema_financas_old\index.php Line: 315
  Function: require_once

This is my code:

//Inicio de desenvolvimento new window client.
    //New Página para gerar pedido de cliente.
    function cadastroOrcamentoCliente($cpfcnpj=null, $tipo_pessoa=null, $dados = null, $id_pf, $id_cliente, $id_cadastro) {
        $tipo_login = $this->session->userdata('tipo_login');
        if ($tipo_login == '1' || $tipo_login == '4' || $tipo_login == '5') {
            $dadosPessoa['tipo_pessoa'] = null;
            $dadosOrcamento['str'] = $this->load->view('admin/compras/popup_cadastro', $dadosPessoa, true);
            if ($tipo_pessoa == 1) {
                $dadosOrcamento['cpf'] = $cpfcnpj;
                $dadosOrcamento['cnpj'] = null;
            } else if ($tipo_pessoa == 2) {
                $dadosOrcamento['cpf'] = null;
                $dadosOrcamento['cnpj'] = $cpfcnpj;
            } else {
                $dadosOrcamento['cpf'] = $cpfcnpj;
                $dadosOrcamento['cnpj'] = $cpfcnpj;
            }

            if ($this->alteracao->editEndereco($id_cadastro) && $this->alteracao->editPessoaFisica($id_pf) &&
                $this->alteracao->editCliente($id_cliente) && $this->alteracao->editCadastroComum($id_cadastro) && $this->alteracao->editarDadosBancarios($id_cadastro)) {
            $data_cad = date("d/m/Y");
            $hora_cad = date("H:i:s");
            $this->alteracao->cadastroHistorico('Dados do cliente editados', $id_cadastro, $data_cad, $hora_cad);
            $this->alteracao->mensagemAlerta("Dados alterados com sucesso!", 1, "home/cadastros", $id_cadastro);

            $dadosOrcamento['orcamento'] = $this->compras_m->buscarOrcamentoAtual($this->session->userdata('id_orcamento'));
            $this->load->view('admin/head');
            $dadosBarra['dadosB'] = $this->financeiro->listaContas();
            $this->load->view('admin/barraSuperior', $dadosBarra);
            $dadosLogo['logo'] = $this->adm->retornaLogo();
            $this->load->view('admin/menu', $dadosLogo);
            $this->load->view('admin/vendas/cadastro_orcamento_cliente', $dadosOrcamento);
            $this->load->view('admin/footer');
        } else {
            $dados['mensagem'] = null;
            $this->paginas($dados);
        }
    }
    }

im calling here

 <form method="post" action="<?php echo site_url('pedido/cadastroOrcamentoVendaCliente') ?>">

just create a new screen and need additional to the project


问:
Spark application that save file as .txt.gz in SFTP
I have Spark(Scala) application that save specific dataframe in SFTP as .txt file. The file that the application generated some times reached 20GB; which is something that can't be downloaded by consumers. I am thinking that I can zip the file such that we reduce the size of the file ( specially it is a text file that we expect a good compression ratio).

Is there any reference or library that I need to work with (import) in Spark that can give me a compressed file?

Thanks in advance.

答:
So I went through different approaches trying to have the .txt.gz file saved in the SFTP. Some Googling I found this which is a Java code that compress a text file into .gz, I just rewrite this code in Scala and everything went perfect.

```<code>def zipFile(fileName1: String): Int = {
val gzpFile: String =  fileNameDotTxt + ".gz"

val SOURCE_FILE: String = pathToFileNameDotTxt
val buffer: Array[Byte] = Array.ofDim[Byte](1024)
try {
  val gzos: GZIPOutputStream = new GZIPOutputStream(new FileOutputStream(gzpFile))
  val in: FileInputStream = new FileInputStream(SOURCE_FILE)
  var len: Int = 0
  while ({ len = in.read(buffer); len } > 0) gzos.write(buffer, 0, len)
  in.close()
  gzos.finish()
  gzos.close()

} catch {
  case ex: IOException =>
    ex.printStackTrace()

}
</code>```

}

We need to import

```<code>import java.io.FileInputStream
import java.io.FileOutputStream
import java.util.zip.GZIPOutputStream
</code>```

Hope this will makes some helps for others.

Body:
So I went through different approaches trying to have the .txt.gz file saved in the SFTP. Some Googling I found this which is a Java code that compress a text file into .gz, I just rewrite this code in Scala and everything went perfect.

def zipFile(fileName1: String): Int = {
val gzpFile: String =  fileNameDotTxt + ".gz"

val SOURCE_FILE: String = pathToFileNameDotTxt
val buffer: Array[Byte] = Array.ofDim[Byte](1024)
try {
  val gzos: GZIPOutputStream = new GZIPOutputStream(new FileOutputStream(gzpFile))
  val in: FileInputStream = new FileInputStream(SOURCE_FILE)
  var len: Int = 0
  while ({ len = in.read(buffer); len } > 0) gzos.write(buffer, 0, len)
  in.close()
  gzos.finish()
  gzos.close()

} catch {
  case ex: IOException =>
    ex.printStackTrace()

}

}

We need to import

import java.io.FileInputStream
import java.io.FileOutputStream
import java.util.zip.GZIPOutputStream

Hope this will makes some helps for others.


问:
Remove println() for release version iOS Swift
I would like to globally ignore all println() calls in my Swift code if I am not in a Debug build. I can't find any robust step by step instructions for this and would appreciate guidance. is there a way to do this globally, or do I need to surround every println() with #IF DEBUG/#ENDIF statements?

答:
Even simpler: take advantage of the fact that asserts are removed from release builds and only from there call the print. This removes all log calls (yes, even the calls to Log.da) as they are empty when building for release.

But I also heard that prints are removed for release builds, but not been able to find it in writing. So for now, I am using something like this Log below. I have a more meaty version on GitHub with emojis (for readability) and log topics (for consistency):

https://github.com/Gatada/JBits/blob/master/Project/Utility/Log.swift

```<code>public enum Log {

    /// A date formatter used to create the timestamp in the log.
    ///
    /// This formatter is only created if it is actually used, reducing the
    /// overhead to zero.
    static var formatter: DateFormatter?

    // MARK: - API

    /// Call to print message in debug area.
    ///
    /// Asserts are removed in release builds, which make
    /// the function body empty, which caused all calls to
    /// be removed as well.
    ///
    /// Result is zero overhead for release builds.
    public static func da(_ message: String) {
        assert(debugAreaPrint(message))
    }

    // MARK: - Helpers

    /// The function that actually does the printing. It returns `true` to
    /// prevent the assert from kicking in on debug builds.
    private static func debugAreaPrint(_ message: String) -> Bool {
        print("\(timestamp) - \(message)")
        return true
    }

    /// Creates a timestamp used as part of the temporary logging in the debug area.
    static private var timestamp: String {

        if formatter == nil {
            formatter = DateFormatter()
            formatter!.dateFormat = "HH:mm:ss.SSS"
        }

        let date = Date()
        return formatter!.string(from: date)
    }
}
</code>```

In code:

```<code>Log.da("This is only handled in a debug build.")
</code>```

Seen in the Xcode debug area only when running a debug build:

13:36:15.047 - This is only handled in a debug build.

ContentLicense: CC BY-SA 3.0

Body:
Even simpler: take advantage of the fact that asserts are removed from release builds and only from there call the print. This removes all log calls (yes, even the calls to Log.da) as they are empty when building for release.

But I also heard that prints are removed for release builds, but not been able to find it in writing. So for now, I am using something like this Log below. I have a more meaty version on GitHub with emojis (for readability) and log topics (for consistency):

https://github.com/Gatada/JBits/blob/master/Project/Utility/Log.swift

public enum Log {

    /// A date formatter used to create the timestamp in the log.
    ///
    /// This formatter is only created if it is actually used, reducing the
    /// overhead to zero.
    static var formatter: DateFormatter?

    // MARK: - API

    /// Call to print message in debug area.
    ///
    /// Asserts are removed in release builds, which make
    /// the function body empty, which caused all calls to
    /// be removed as well.
    ///
    /// Result is zero overhead for release builds.
    public static func da(_ message: String) {
        assert(debugAreaPrint(message))
    }

    // MARK: - Helpers

    /// The function that actually does the printing. It returns `true` to
    /// prevent the assert from kicking in on debug builds.
    private static func debugAreaPrint(_ message: String) -> Bool {
        print("\(timestamp) - \(message)")
        return true
    }

    /// Creates a timestamp used as part of the temporary logging in the debug area.
    static private var timestamp: String {

        if formatter == nil {
            formatter = DateFormatter()
            formatter!.dateFormat = "HH:mm:ss.SSS"
        }

        let date = Date()
        return formatter!.string(from: date)
    }
}

In code:

Log.da("This is only handled in a debug build.")

Seen in the Xcode debug area only when running a debug build:

13:36:15.047 - This is only handled in a debug build.


问:
Cannot find/click any elements on Apple Pay view in UITest
I've been able to successfully run ApplePay in my UITests, but once the PKPaymentAuthorizationViewController is displayed, none of the elements on that view are locatable and any attempt to select elements on the underlying application view result in an error "..... is not frontmost".

Has anyone else encountered this problem and/or have any idea how to work around it?

答:
It is a bit tricky, but here is how you can do this:

```<code>// create passbook app
let applePay = XCUIApplication(bundleIdentifier: "com.apple.PassbookUIService")

// wait for an auth controller to appear
_ = applePay.wait(for: .runningForeground, timeout: 5)

// tap pay button
applePay.buttons["Pay with Passcode"].tap()
</code>```

After that authorization will succeed and you'll get apple pay data.

But there is "one more thing" - data will be empty on simulator, so if you try to serialize it, you'll get an error. So I used data mock for simulator:

```<code>#if targetEnvironment(simulator)
     print("WARNING! SIMULATING APPLE PAY!")
     let payObject = [String: Any]()
#else
     let payObject = try JSONSerialization.jsonObject(with: encryptedData, options: [])
#endif
// send payObject to server
</code>```

Body:
It is a bit tricky, but here is how you can do this:

// create passbook app
let applePay = XCUIApplication(bundleIdentifier: "com.apple.PassbookUIService")

// wait for an auth controller to appear
_ = applePay.wait(for: .runningForeground, timeout: 5)

// tap pay button
applePay.buttons["Pay with Passcode"].tap()

After that authorization will succeed and you'll get apple pay data.

But there is "one more thing" - data will be empty on simulator, so if you try to serialize it, you'll get an error. So I used data mock for simulator:

#if targetEnvironment(simulator)
     print("WARNING! SIMULATING APPLE PAY!")
     let payObject = [String: Any]()
#else
     let payObject = try JSONSerialization.jsonObject(with: encryptedData, options: [])
#endif
// send payObject to server


问:
Can anyone please tell me how is Kernel Programming done in Linux, as Windows DDK in Windows
I am aware of windows kernel but new to linux kernel. I just need to know how its done in linux, i.e. the program development.</p>

答:
Linux does not have a stable kernel API. This is by design, so you should generally avoid writing kernel code if you can; it is unlikely to remain source-compatible indefinitely, and will definitely NOT be binary-compatible, even between minor releases.

This is less-or-more true for vendor kernels; Redhat etc DO maintain source & binary kernel compatibility between major revisions.

More work is gradually being done in the kernel to reduce the amount of kernel-code required to carry out various tasks, such as driver development (for example, USB drivers can typically be done in userspace with libusb), filesystem development (FUSE) and network filtering (NFQUEUE). However, there are still some cases where you need to; in particular, block devices still need to be in the kernel to be able to be usefully used for boot devices and swap.


问:
Address generation for bitcoin with Python error
I am trying to understand bitcoin with python and trying to create my own vanity address generator.

Below is a snippet of the while loop. I keep getting an error after the loop runs about 10 times. Any help would be highly appreciated. i have searched the forum and have found answers.

But they don't work. IE. i changed the

```<code>intermed = hashlib.sha256(string).digest()
</code>```

a few times modifying the code but still the same result.

```<code>Traceback (most recent call last):
  File "main.py", line 38, in <module>
    compressed_address_base58check = bitcoin.pubkey_to_address(hex_compressed_public_key)
  File "/home/runner/.local/share/virtualenvs/python3/lib/python3.7/site-packages/bitcoin/mai
n.py", line 452, in pubkey_to_address
    return bin_to_b58check(bin_hash160(pubkey), magicbyte)  File "/home/runner/.local/share/virtualenvs/python3/lib/python3.7/site-packages/bitcoin/mai
n.py", line 334, in bin_hash160
    intermed = hashlib.sha256(string).digest()
TypeError: Unicode-objects must be encoded before hashing
</code>```

```<code>while True:
  pk = binascii.hexlify(os.urandom(32)).decode('utf-8').upper()
  privkey = f"{pk:0>64}"
  pub = privtopub(privkey)   # Get pub addr from priv key
  addr = pubtoaddr(pub)   # Get the 1Btc... address
  decoded_private_key = bitcoin.decode_privkey(privkey, 'hex')
  wif_encoded_private_key = bitcoin.encode_privkey(decoded_private_key, 'wif')
  # Add suffix '01' to indicate a compressed private Key
  compressed_private_key = privkey + '01'
  # generate a WIF format from the compressed private key (WIF-compressed)
  wif_compressed_private_key = bitcoin.encode_privkey(bitcoin.decode_privkey(compressed_private_key, 'hex'), 'wif')
  # Multiply de EC generator G with the priveate key to get a public key point
  pubkey = bitcoin.fast_multiply(bitcoin.G, decoded_private_key)
  # Encode as hex, prefix 04
  hex_encoded_public_key = bitcoin.encode_pubkey(pubkey, 'hex')
  # Compress public key, adjust prefix depending on whether y is even or odd
  (public_key_x, public_key_y) = pubkey
  if public_key_y % 2 == 0:
    compressed_prefix = '02'
  else:
    compressed_prefix = '03'
  hex_compressed_public_key = compressed_prefix + bitcoin.encode(public_key_x, 16)
  print ('Compressed Public Key: ' + hex_compressed_public_key)
  # Generate compressedd bitcoin address from compressed public key

  compressed_address_base58check = bitcoin.pubkey_to_address(hex_compressed_public_key)
  print ("private key:           " + privkey )
  print ("uncompressed address:     "+ addr )
  print ('Compressed address:       ' + bitcoin.pubkey_to_address(hex_compressed_public_key))
  C_address = bitcoin.pubkey_to_address(hex_compressed_public_key)
  U_address = addr
</code>```

答:
You have to encode your hex_compressed_public_key to generate the address.

```<code>compressed_address_base58check = bitcoin.pubkey_to_address(hex_compressed_public_key.encode('utf-8'))
</code>```

Body:
I am trying to understand bitcoin with python and trying to create my own vanity address generator.

Below is a snippet of the while loop. I keep getting an error after the loop runs about 10 times. Any help would be highly appreciated. i have searched the forum and have found answers.

But they don't work. IE. i changed the

intermed = hashlib.sha256(string).digest()

a few times modifying the code but still the same result.

Traceback (most recent call last):
  File "main.py", line 38, in <module>
    compressed_address_base58check = bitcoin.pubkey_to_address(hex_compressed_public_key)
  File "/home/runner/.local/share/virtualenvs/python3/lib/python3.7/site-packages/bitcoin/mai
n.py", line 452, in pubkey_to_address
    return bin_to_b58check(bin_hash160(pubkey), magicbyte)  File "/home/runner/.local/share/virtualenvs/python3/lib/python3.7/site-packages/bitcoin/mai
n.py", line 334, in bin_hash160
    intermed = hashlib.sha256(string).digest()
TypeError: Unicode-objects must be encoded before hashing

while True:
  pk = binascii.hexlify(os.urandom(32)).decode('utf-8').upper()
  privkey = f"{pk:0>64}"
  pub = privtopub(privkey)   # Get pub addr from priv key
  addr = pubtoaddr(pub)   # Get the 1Btc... address
  decoded_private_key = bitcoin.decode_privkey(privkey, 'hex')
  wif_encoded_private_key = bitcoin.encode_privkey(decoded_private_key, 'wif')
  # Add suffix '01' to indicate a compressed private Key
  compressed_private_key = privkey + '01'
  # generate a WIF format from the compressed private key (WIF-compressed)
  wif_compressed_private_key = bitcoin.encode_privkey(bitcoin.decode_privkey(compressed_private_key, 'hex'), 'wif')
  # Multiply de EC generator G with the priveate key to get a public key point
  pubkey = bitcoin.fast_multiply(bitcoin.G, decoded_private_key)
  # Encode as hex, prefix 04
  hex_encoded_public_key = bitcoin.encode_pubkey(pubkey, 'hex')
  # Compress public key, adjust prefix depending on whether y is even or odd
  (public_key_x, public_key_y) = pubkey
  if public_key_y % 2 == 0:
    compressed_prefix = '02'
  else:
    compressed_prefix = '03'
  hex_compressed_public_key = compressed_prefix + bitcoin.encode(public_key_x, 16)
  print ('Compressed Public Key: ' + hex_compressed_public_key)
  # Generate compressedd bitcoin address from compressed public key

  compressed_address_base58check = bitcoin.pubkey_to_address(hex_compressed_public_key)
  print ("private key:           " + privkey )
  print ("uncompressed address:     "+ addr )
  print ('Compressed address:       ' + bitcoin.pubkey_to_address(hex_compressed_public_key))
  C_address = bitcoin.pubkey_to_address(hex_compressed_public_key)
  U_address = addr

Body:
You have to encode your hex_compressed_public_key to generate the address.

compressed_address_base58check = bitcoin.pubkey_to_address(hex_compressed_public_key.encode('utf-8'))


问:
Count all possible combinations no matter the column order
I have a dataset which looks like

```<code>df <- data.frame(rbind(c("A","B","D",NA,NA,NA,3),
c("B","A","D","C",NA,NA,1),
c("B","C","E","A","D",NA,5),
c("A","B",NA,NA,NA,NA,4),
c("A","B","C","D","E","F",2)))

    X1      X2       X3        X4       X5        X6    N
    A        B        D        NA       NA        NA    3
    B        A        D        C        NA        NA    1
    B        C        E        A         D        NA    5
    A        B        NA       NA       NA        NA    4
    A        B        C        D         E         F    2
</code>```

Where the column N is the number of times that combination happens.

and I want like to have a cumulative sum by unordered columns (no matter on which column the letter is located) such that:

```<code>     X1      X2       X3        X4       X5        X6     N
    A       NA        NA       NA        NA        NA     15
    B       NA        NA       NA        NA        NA     15
    C       NA        NA       NA        NA        NA     8
    D       NA        NA       NA        NA        NA     11
    E       NA        NA       NA        NA        NA     7
    F       NA        NA       NA        NA        NA     2
    A        B        NA       NA        NA        NA     15
    A        B        C        NA        NA        NA     8
    A        B        C        D         NA        NA     8
    A        B        C        D         E         NA     7
    A        B        C        D         E         F      1
    B        C        NA       NA        NA        NA     8
    ....
</code>```

So the idea is to have all possible combinations and the frequency but taking into account that the order of appearance in Column is not relevant.

答:
Here's one approach that generates a list of the combinations of the values by row adds it to the original dataframe, unnests and tallies N by group.</p>

```<code>library(dplyr)
library(tidyr)

df %>%
  mutate(comblist = apply(.[1:6], 1, function(x) {
    x <- sort(na.omit(x))
    unlist(sapply(seq_along(x), function(y)
      list(combn(x, y,
        FUN = function(l)
          list(toString(l))
      ))))
  })) %>%
  select(comblist, N) %>%
  unnest(comblist) %>%
  group_by(comblist) %>%
  summarise(x = sum(N))

# A tibble: 63 x 2
   comblist             N
   <chr>            <dbl>
 1 A                   15
 2 A, B                15
 3 A, B, C              8
 4 A, B, C, D           8
 5 A, B, C, D, E        7
 6 A, B, C, D, E, F     2
 7 A, B, C, D, F        2
 8 A, B, C, E           7
 9 A, B, C, E, F        2
10 A, B, C, F           2
# ... with 53 more rows
</code>```

Body:
I have a dataset which looks like

df <- data.frame(rbind(c("A","B","D",NA,NA,NA,3),
c("B","A","D","C",NA,NA,1),
c("B","C","E","A","D",NA,5),
c("A","B",NA,NA,NA,NA,4),
c("A","B","C","D","E","F",2)))

    X1      X2       X3        X4       X5        X6    N
    A        B        D        NA       NA        NA    3
    B        A        D        C        NA        NA    1
    B        C        E        A         D        NA    5
    A        B        NA       NA       NA        NA    4
    A        B        C        D         E         F    2

Where the column N is the number of times that combination happens.

and I want like to have a cumulative sum by unordered columns (no matter on which column the letter is located) such that:

     X1      X2       X3        X4       X5        X6     N
    A       NA        NA       NA        NA        NA     15
    B       NA        NA       NA        NA        NA     15
    C       NA        NA       NA        NA        NA     8
    D       NA        NA       NA        NA        NA     11
    E       NA        NA       NA        NA        NA     7
    F       NA        NA       NA        NA        NA     2
    A        B        NA       NA        NA        NA     15
    A        B        C        NA        NA        NA     8
    A        B        C        D         NA        NA     8
    A        B        C        D         E         NA     7
    A        B        C        D         E         F      1
    B        C        NA       NA        NA        NA     8
    ....

So the idea is to have all possible combinations and the frequency but taking into account that the order of appearance in Column is not relevant.

Body:
Here's one approach that generates a list of the combinations of the values by row adds it to the original dataframe, unnests and tallies N by group.

library(dplyr)
library(tidyr)

df %>%
  mutate(comblist = apply(.[1:6], 1, function(x) {
    x <- sort(na.omit(x))
    unlist(sapply(seq_along(x), function(y)
      list(combn(x, y,
        FUN = function(l)
          list(toString(l))
      ))))
  })) %>%
  select(comblist, N) %>%
  unnest(comblist) %>%
  group_by(comblist) %>%
  summarise(x = sum(N))

# A tibble: 63 x 2
   comblist             N
   <chr>            <dbl>
 1 A                   15
 2 A, B                15
 3 A, B, C              8
 4 A, B, C, D           8
 5 A, B, C, D, E        7
 6 A, B, C, D, E, F     2
 7 A, B, C, D, F        2
 8 A, B, C, E           7
 9 A, B, C, E, F        2
10 A, B, C, F           2
# ... with 53 more rows


问:
Why do we need API automation?
As a initial phase of development we are need to perform API but why API automation is required after the product gone live. Is there any specific reason.

Because functional automation should be sufficient to track the functionality of the web site.

How does functional testing differ from API testing?

答: API testing is usually done when the UI is not ready. Moreover, The response time is faster than when compared with Functional testing using UI. It also helps one understand the response in various scenarios. One doesn't have to depend on any technology, the API URI is enough to check the functionality</p>

Title: Why do we need API automation?


Title: R - How to change elements in a matrix starting from a specific point

Body:
I have a data frame M, which looks like:

 [,1]      [,2]      [,3]       [,4]     [,5]
 [1,] 0.4212778 0.6874073 0.1551896 Cluster_1
 [2,] 0.6874073 0.5610995 0.1779030 Cluster_1
 [3,] 0.1551896 0.1779030 0.9515304 Cluster_1
 [4,] 0.4675764 0.5407295 0.7942978 Cluster_1_A
 [5,] 0.4675764 0.5407295 0.7942978 Cluster_1
 [6,] 0.4675764 0.5407295 0.7942978 Cluster_1
 [7,] 0.4675764 0.5407295 0.7942978 Cluster_2
 [8,] 0.4675764 0.5407295 0.7942978 Cluster_2_A
 [9,] 0.4675764 0.5407295 0.7942978 Cluster_2
[10,] 0.4675764 0.5407295 0.7942978 Cluster_2
[11,] 0.4675764 0.5407295 0.7942978 Cluster_2_1_A
[12,] 0.4675764 0.5407295 0.7942978 Cluster_2
[13,] 0.4675764 0.5407295 0.7942978 Cluster_2
[14,] 0.4675764 0.5407295 0.7942978 Cluster_3
[15,] 0.4675764 0.5407295 0.7942978 Cluster_3
[15,] 0.4675764 0.5407295 0.7942978 Cluster_3
[16,] 0.4675764 0.5407295 0.7942978 Cluster_4
[17,] 0.4675764 0.5407295 0.7942978 Cluster_4

I want to assign the same name of the elements of the matrix (column 5) in the range starting from the element with "_A" flag until the next name change.
In this case:

from M[4,5] until element M[6,5]

from M[8,5] until element M[10,5]

from M[11,5] until element M[13,5]

The result I want is the following:

 [,1]      [,2]      [,3]       [,4]     [,5]
 [1,] 0.4212778 0.6874073 0.1551896 Cluster_1
 [2,] 0.6874073 0.5610995 0.1779030 Cluster_1
 [3,] 0.1551896 0.1779030 0.9515304 Cluster_1
 [4,] 0.4675764 0.5407295 0.7942978 Cluster_1_A
 [5,] 0.4675764 0.5407295 0.7942978 Cluster_1_A
 [6,] 0.4675764 0.5407295 0.7942978 Cluster_1_A
 [7,] 0.4675764 0.5407295 0.7942978 Cluster_2
 [8,] 0.4675764 0.5407295 0.7942978 Cluster_2_A
 [9,] 0.4675764 0.5407295 0.7942978 Cluster_2_A
[10,] 0.4675764 0.5407295 0.7942978 Cluster_2_A
[11,] 0.4675764 0.5407295 0.7942978 Cluster_2_1_A
[12,] 0.4675764 0.5407295 0.7942978 Cluster_2_1_A
[13,] 0.4675764 0.5407295 0.7942978 Cluster_2_1_A
[14,] 0.4675764 0.5407295 0.7942978 Cluster_3
[15,] 0.4675764 0.5407295 0.7942978 Cluster_3
[15,] 0.4675764 0.5407295 0.7942978 Cluster_3
[16,] 0.4675764 0.5407295 0.7942978 Cluster_4
[17,] 0.4675764 0.5407295 0.7942978 Cluster_4

How can I do that quickly, also avoiding a for loop (which I'm able to code)? I've seen many similar posts, but no one gave me what I want. Thank you!

Body:
You can try the base R solution below, which applied ave + gsub

M <- within(M,V5 <- ave(V5,
                          gsub("(Cluster_\\d+).*","\\1",V5),
                          FUN = function(x) ave(x,
                                                cumsum(grepl("_A",x)),
                                                FUN = function(q) head(q,1))))

such that

> M
      V1        V2        V3        V4            V5
1   [1,] 0.4212778 0.6874073 0.1551896     Cluster_1
2   [2,] 0.6874073 0.5610995 0.1779030     Cluster_1
3   [3,] 0.1551896 0.1779030 0.9515304     Cluster_1
4   [4,] 0.4675764 0.5407295 0.7942978   Cluster_1_A
5   [5,] 0.4675764 0.5407295 0.7942978   Cluster_1_A
6   [6,] 0.4675764 0.5407295 0.7942978   Cluster_1_A
7   [7,] 0.4675764 0.5407295 0.7942978     Cluster_2
8   [8,] 0.4675764 0.5407295 0.7942978   Cluster_2_A
9   [9,] 0.4675764 0.5407295 0.7942978   Cluster_2_A
10 [10,] 0.4675764 0.5407295 0.7942978   Cluster_2_A
11 [11,] 0.4675764 0.5407295 0.7942978 Cluster_2_1_A
12 [12,] 0.4675764 0.5407295 0.7942978 Cluster_2_1_A
13 [13,] 0.4675764 0.5407295 0.7942978 Cluster_2_1_A
14 [14,] 0.4675764 0.5407295 0.7942978     Cluster_3
15 [15,] 0.4675764 0.5407295 0.7942978     Cluster_3
16 [15,] 0.4675764 0.5407295 0.7942978     Cluster_3
17 [16,] 0.4675764 0.5407295 0.7942978     Cluster_4
18 [17,] 0.4675764 0.5407295 0.7942978     Cluster_4

DATA

M <- structure(list(V1 = c("[1,]", "[2,]", "[3,]", "[4,]", "[5,]",
"[6,]", "[7,]", "[8,]", "[9,]", "[10,]", "[11,]", "[12,]", "[13,]",
"[14,]", "[15,]", "[15,]", "[16,]", "[17,]"), V2 = c(0.4212778,
0.6874073, 0.1551896, 0.4675764, 0.4675764, 0.4675764, 0.4675764,
0.4675764, 0.4675764, 0.4675764, 0.4675764, 0.4675764, 0.4675764,
0.4675764, 0.4675764, 0.4675764, 0.4675764, 0.4675764), V3 = c(0.6874073,
0.5610995, 0.177903, 0.5407295, 0.5407295, 0.5407295, 0.5407295,
0.5407295, 0.5407295, 0.5407295, 0.5407295, 0.5407295, 0.5407295,
0.5407295, 0.5407295, 0.5407295, 0.5407295, 0.5407295), V4 = c(0.1551896,
0.177903, 0.9515304, 0.7942978, 0.7942978, 0.7942978, 0.7942978,
0.7942978, 0.7942978, 0.7942978, 0.7942978, 0.7942978, 0.7942978,
0.7942978, 0.7942978, 0.7942978, 0.7942978, 0.7942978), V5 = c("Cluster_1",
"Cluster_1", "Cluster_1", "Cluster_1_A", "Cluster_1", "Cluster_1",
"Cluster_2", "Cluster_2_A", "Cluster_2", "Cluster_2", "Cluster_2_1_A",
"Cluster_2", "Cluster_2", "Cluster_3", "Cluster_3", "Cluster_3",
"Cluster_4", "Cluster_4")), class = "data.frame", row.names = c(NA,
-18L))


问:
Joomla modules not showing on custom template
So I recently created a custom template and put in the modules and uploaded it to my server. When I load the page, it shows the template layout, but when ever I create a module to insert in the module positions, the content in those modules doesn't appear on my pages. I can's seem to find where the error is coming from. Can Someone help me?

Php

```<code><?php defined( '_JEXEC' ) or die( 'Restricted access' ); ?>
<!doctype HTML public "-//W3C//DTD HTML 5.0 Transitional//EN" >
<html xmlns="http://www.w3.org/1999/xhtml"
   xml:lang="<?php echo $this->language; ?>" lang="<?php echo $this->language; ?>" >
  <head>

    <jdoc:include type="head" />

    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
        integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

    <!-- custom css -->
    <link rel="stylesheet" href="<?php echo $this->baseurl ?>/templates/<?php echo $this->template ?>/css/style.css">

    <title>Site</title>
</head>

<body>
    <!-- navbar area -->
    <div class="nav-area">
        <!-- top details -->

        <!-- navbar menu -->
        <nav class="navbar navbar-expand-lg navbar-light bg-light w-100">
            <div class="container">
                <a class="navbar-brand" href=".">Brand</a>
                <button class="navbar-toggler" type="button" data-toggle="collapse"
                    data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false"
                    aria-label="Toggle navigation">
                    <span class="navbar-toggler-icon"></span>
                </button>

                <div class="collapse navbar-collapse" id="navbarSupportedContent">
                    <jdoc:include type="module" name="menu" />
                </div>
                <button class="btn btn-orange btn-lg">Request a Qoute</button>
            </div>
        </nav>
    </div>

    <!-- component -->
    <div class="component-area">
        <div class="container">
            <jdoc:include type="component" />
        </div>
    </div>

    <!-- call to action -->
    <div class="call">
        <jdoc:include type="module" name="call2action" />
    </div>

    <!-- what drives us -->
    <div class="drive">
        <jdoc:include type="module" name="drive" />
    </div>

    <!-- our experience -->
    <div class="experience">
        <jdoc:include type="module" name="experience" />
    </div>

    <!-- solutions we offer -->
    <div class="solutions">
        <jdoc:include type="module" name="solutions" />
    </div>

    <!-- call out -->
    <div class="callout">
        <jdoc:include type="module" name="call-out" />
    </div>

    <!-- contact area -->
    <div class="contact">
        <jdoc:include type="module" name="contact" />
    </div>

    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"
        integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous">
    </script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"
        integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous">
    </script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"
        integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous">
    </script>

    <script type="text/javascript">
        $.noConflict();
        jQuery(document).ready(function ($) {
            // Code that uses jQuery's $ can follow here.

            var s = $(".nav-area");
            var pos = s.position();
            $(window).on('scroll', function () {
                var windowpos = $(window).scrollTop() > 1;
                if (windowpos > pos.top) {
                    s.addClass("fixed");
                } else {
                    s.removeClass("fixed");
                }
            });
        });
    </script>
</body>

</html>
</code>```

templateDetails

```<code><?xml version="1.0" encoding="utf-8"?>
<extension version="3.9" type="template">
    <name>Site</name>
    <creationDate>2020-02-06</creationDate>
    <author>Me</author>
    <authorEmail>site@site.co</authorEmail>
    <authorUrl>site.co</authorUrl>
    <copyright>Site</copyright>
    <license>GNU/GPL</license>
    <version>1.1.2</version>
    <description>Site</description>
    <files>
        <filename>index.html</filename>
        <filename>index.php</filename>
        <filename>templateDetails.xml</filename>
        <folder>css</folder>
        <folder>img</folder>
    </files>
    <positions>
        <position>menu</position>
        <position>call2action</position>
        <position>drive</position>
        <position>experience</position>
        <position>solutions</position>
        <position>call-out</position>
        <position>contact</position>
    </positions>
     <config>
        <fields name="params">
            <fieldset name="general" label="General">
                <field name="copyright" type="text" label="Copyright Info" description="Enter your Copyright Information" />
            </fieldset>
        </fields>
    </config>
</extension>
</code>```

答: The error was in my jdoc type. instead of <jdoc:include type="module" name="menu" />, its supposed to be```. It was missing an 's'

Body:
So I recently created a custom template and put in the modules and uploaded it to my server. When I load the page, it shows the template layout, but when ever I create a module to insert in the module positions, the content in those modules doesn't appear on my pages. I can's seem to find where the error is coming from. Can Someone help me?

Php

<?php defined( '_JEXEC' ) or die( 'Restricted access' ); ?>
<!doctype HTML public "-//W3C//DTD HTML 5.0 Transitional//EN" >
<html xmlns="http://www.w3.org/1999/xhtml"
   xml:lang="<?php echo $this->language; ?>" lang="<?php echo $this->language; ?>" >

    <jdoc:include type="head" />

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
        integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

    <link rel="stylesheet" href="<?php echo $this->baseurl ?>/templates/<?php echo $this->template ?>/css/style.css">

    <title>Site</title>

                Brand
                <button class="navbar-toggler" type="button" data-toggle="collapse"
                    data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false"
                    aria-label="Toggle navigation">

                </button>

                    <jdoc:include type="module" name="menu" />

                <button class="btn btn-orange btn-lg">Request a Qoute</button>

            <jdoc:include type="component" />

        <jdoc:include type="module" name="call2action" />

        <jdoc:include type="module" name="drive" />

        <jdoc:include type="module" name="experience" />

        <jdoc:include type="module" name="solutions" />

        <jdoc:include type="module" name="call-out" />

        <jdoc:include type="module" name="contact" />

templateDetails

<?xml version="1.0" encoding="utf-8"?>
<extension version="3.9" type="template">
    <name>Site</name>
    <creationDate>2020-02-06</creationDate>
    <author>Me</author>
    <authorEmail>site@site.co</authorEmail>
    <authorUrl>site.co</authorUrl>
    <copyright>Site</copyright>
    <license>GNU/GPL</license>
    <version>1.1.2</version>
    <description>Site</description>
    <files>
        <filename>index.html</filename>
        <filename>index.php</filename>
        <filename>templateDetails.xml</filename>
        <folder>css</folder>
        <folder>img</folder>
    </files>
    <positions>
        <position>menu</position>
        <position>call2action</position>
        <position>drive</position>
        <position>experience</position>
        <position>solutions</position>
        <position>call-out</position>
        <position>contact</position>
    </positions>
     <config>
        <fields name="params">
            <fieldset name="general" label="General">
                <field name="copyright" type="text" label="Copyright Info" description="Enter your Copyright Information" />
            </fieldset>
        </fields>
    </config>
</extension>


问:
Text is not correctly typed in on Chrome/Ubuntu
I am running Selenium tests on Chrome browser which on Linux machine with following details -

```<code>Linux version - Ubuntu 18.04.3 LTS
Chrome Version - 79.0.3945.79
Linux Chromedriver - 79.0.3945.36 (https://chromedriver.storage.googleapis.com/index.html?path=79.0.3945.36/)
</code>```

In some of the text input fields like following code snippet, I'm typing in like - http://www.example.com/pqr/xyz using sendKeys() method

```<code><input type="text" id="drvUrl" name="Driver URL" placeholder="JDBC URL for the source database system" required="" class="k-textbox eq-widget k-invalid" aria-invalid="true">
</code>```

But url is typed without special characters like httpwwwexamplecompqrxyz. All special characters are removed.

I've got work-around where first I type in url using JavascriptExecutor but that is not ideal way to automate it.

Is there better workaround for this? Also I could not find similar bug on Selenium WebDriver, in that case, just wanted to confirm before logging bug there.

答:
if it has attribute called value, you can try to do as below.

driver.findElement(By.xpath(xpath)).setAttribute("value", "your value");

How to set "value" to input web element using selenium?

Cheers!

Body:
I am running Selenium tests on Chrome browser which on Linux machine with following details -

Linux version - Ubuntu 18.04.3 LTS
Chrome Version - 79.0.3945.79
Linux Chromedriver - 79.0.3945.36 (https://chromedriver.storage.googleapis.com/index.html?path=79.0.3945.36/)

In some of the text input fields like following code snippet, I'm typing in like - http://www.example.com/pqr/xyz using sendKeys() method

<input type="text" id="drvUrl" name="Driver URL" placeholder="JDBC URL for the source database system" required="" class="k-textbox eq-widget k-invalid" aria-invalid="true">

But url is typed without special characters like httpwwwexamplecompqrxyz. All special characters are removed.

I've got work-around where first I type in url using JavascriptExecutor but that is not ideal way to automate it.

Is there better workaround for this? Also I could not find similar bug on Selenium WebDriver, in that case, just wanted to confirm before logging bug there.


问:
XCTest Single Asynchronous SetUp With Semaphores
I am working on testing an API through Alamofire. I need to make a single call to the server to prepare it for the integration test. Once that is done, I am ready to start running tests.

The usual override setUp() is run for every test, so I do not want to do that.

I have therefore chosen to override the class setUp() as described here: https://developer.apple.com/reference/xctest/xctestcase

That's all well and good, but now, I no longer can use the standard waitForExpectations. (In the class override setUp()) I get several compiler errors that tell me that I am no longer calling the same waitForExpectations because I am in a class method, not a test case.

To try to get around this, I wanted to use a semaphore like so:

```<code>class ServiceLayerTests: XCTestCase {
    static var apiService: APIService = APIService()
    let sessionManager = SessionManager(serverTrustPolicyManager: ServerTrustPolicyManager(policies: ["http://localhost:3000/": .disableEvaluation]))
    static var companyManger: UserWebResource?
    static var companyManagerID = -1
    override class func setUp() {
        apiService.baseURL = "http://localhost:3000/"
        beginIntegrationTests()
    }

    class func beginIntegrationTests() {
        var semaphore = DispatchSemaphore(value: 0)
        apiService.beginIntegrationTests(completion: {resource, error in
            if let resource = resource {
                if let manager = resource as? UserWebResource {
                    companyManger = manager
                    companyManagerID = manager.id
                    semaphore.signal()

                }
            }
        })
        _ = semaphore.wait(timeout: DispatchTime.distantFuture)
  }
}
</code>```

This does not work. Under the hood, there is an alamo fire call to the server and it responds with the user to use for the integration tests. I do see the server spinning, so I know that the actual communication is happening, but I never get into the completion closure.

I suspect I am not understanding how Swift does semaphores and that I have created a deadlock somehow. If somebody has a better solution, I'd be more than happy to hear it.

答:
You can create the expectation as a lazy var that executes your one-time set up and fulfills on completion.

At the beginning of your per-test setUp() function you can wait for that expectation.

None of your tests will run until it is fulfilled, and the initial setup will run only once.

```<code>class WaitForSetup_Tests: XCTestCase {

    lazy var initialSetupFinished: XCTestExpectation = {
        let initialSetupFinished = expectation(description: "initial setup finished")

        initialSetupTask() { // your setup task that executes this closure on completion
            initialSetupFinished.fulfill()
            return
        }

        return initialSetupFinished
    }()

    override func setUp() {
        wait(for: [initialSignOutFinished], timeout: 2.0)
        // do your per-test setup here
    }
}
</code>```

Note: This solution avoids using the override class function setUp() class method, because I couldn't figure out how to use the expectations except for in an instance.

Body:
I am working on testing an API through Alamofire. I need to make a single call to the server to prepare it for the integration test. Once that is done, I am ready to start running tests.

The usual override setUp() is run for every test, so I do not want to do that.

I have therefore chosen to override the class setUp() as described here: https://developer.apple.com/reference/xctest/xctestcase

That's all well and good, but now, I no longer can use the standard waitForExpectations. (In the class override setUp()) I get several compiler errors that tell me that I am no longer calling the same waitForExpectations because I am in a class method, not a test case.

To try to get around this, I wanted to use a semaphore like so:

class ServiceLayerTests: XCTestCase {
    static var apiService: APIService = APIService()
    let sessionManager = SessionManager(serverTrustPolicyManager: ServerTrustPolicyManager(policies: ["http://localhost:3000/": .disableEvaluation]))
    static var companyManger: UserWebResource?
    static var companyManagerID = -1
    override class func setUp() {
        apiService.baseURL = "http://localhost:3000/"
        beginIntegrationTests()
    }

    class func beginIntegrationTests() {
        var semaphore = DispatchSemaphore(value: 0)
        apiService.beginIntegrationTests(completion: {resource, error in
            if let resource = resource {
                if let manager = resource as? UserWebResource {
                    companyManger = manager
                    companyManagerID = manager.id
                    semaphore.signal()

                }
            }
        })
        _ = semaphore.wait(timeout: DispatchTime.distantFuture)
  }
}

This does not work. Under the hood, there is an alamo fire call to the server and it responds with the user to use for the integration tests. I do see the server spinning, so I know that the actual communication is happening, but I never get into the completion closure.

I suspect I am not understanding how Swift does semaphores and that I have created a deadlock somehow. If somebody has a better solution, I'd be more than happy to hear it.

Body:
You can create the expectation as a lazy var that executes your one-time set up and fulfills on completion.

At the beginning of your per-test setUp() function you can wait for that expectation.

None of your tests will run until it is fulfilled, and the initial setup will run only once.

class WaitForSetup_Tests: XCTestCase {

    lazy var initialSetupFinished: XCTestExpectation = {
        let initialSetupFinished = expectation(description: "initial setup finished")

        initialSetupTask() { // your setup task that executes this closure on completion
            initialSetupFinished.fulfill()
            return
        }

        return initialSetupFinished
    }()

    override func setUp() {
        wait(for: [initialSignOutFinished], timeout: 2.0)
        // do your per-test setup here
    }
}

Note: This solution avoids using the override class function setUp() class method, because I couldn't figure out how to use the expectations except for in an instance.


问:
Replacing multiple words in a string sentence C#
Hello guys, I don't need the answer but I would look to know and find out what I'm doing wrong. As a beginner I got a very "easy" assignment in my studies. I need to create a string and inside this string I need to replace some words by other words without using the for loop as so: ( also I want to print it but I got no clue where to put Console.WriteLine and google searching for 1 hour didn't work or asking a colleage.

/* Excersice: use with stringbuilder
             * cat becomes littlecat
             * dog becomes littledog
             * mouse becomes littlemouse
             * words the must be replace by a
             * do not use a loop*/

```<code>
using System;
using System.Collections.Generic;
using System.Text;

namespace Opgavens_leerpad_3_oefening
{
    class Program
    {
        static string Main(string[] args)
        {
            StringBuilder sb = new StringBuilder();

            string dogCat = new string("Can the cat find the mouse without waking the dog.");

            static string replacethisstring(string dogCat);
            {
                hondKat = dogCat.Replace("cat", "littlecat");
                hondKat = dogCat.Replace("dog", "littldog");
                hondKat = dogCat.Replace("mouse", "littlemouse");
                hondKat = dogCat.Replace("the", "a");
                return dogCat;
            }
        }
    }
}

</code>```

Error CS5001: Program does not contain a static "Main" method suitable for an entry point ( I don't get this doesn't almost any program starts with this static Main args? )

Error CS8112: replacethisstring(string)' is a local function and must therefore always have a body. ( I just gave it a body right? I opened the { and close it } and put a replace with return. )

答:
The method declaration ends with ; that’s the reason for CS8112

The Main method has to return void (or ‘int’ )you’ve modified it to string, that’s the reason for CS5001

If you want the program to print the output on the console use:

```<code>using System;

....

 Console.WriteLine(output)
</code>```

Body:
Hello guys, I don't need the answer but I would look to know and find out what I'm doing wrong. As a beginner I got a very "easy" assignment in my studies. I need to create a string and inside this string I need to replace some words by other words without using the for loop as so: ( also I want to print it but I got no clue where to put Console.WriteLine and google searching for 1 hour didn't work or asking a colleage.

/* Excersice: use with stringbuilder
             * cat becomes littlecat
             * dog becomes littledog
             * mouse becomes littlemouse
             * words the must be replace by a
             * do not use a loop*/

using System;
using System.Collections.Generic;
using System.Text;

namespace Opgavens_leerpad_3_oefening
{
    class Program
    {
        static string Main(string[] args)
        {
            StringBuilder sb = new StringBuilder();

            string dogCat = new string("Can the cat find the mouse without waking the dog.");

            static string replacethisstring(string dogCat);
            {
                hondKat = dogCat.Replace("cat", "littlecat");
                hondKat = dogCat.Replace("dog", "littldog");
                hondKat = dogCat.Replace("mouse", "littlemouse");
                hondKat = dogCat.Replace("the", "a");
                return dogCat;
            }
        }
    }
}

Error CS5001: Program does not contain a static "Main" method suitable for an entry point ( I don't get this doesn't almost any program starts with this static Main args? )

Error CS8112: replacethisstring(string)' is a local function and must therefore always have a body. ( I just gave it a body right? I opened the { and close it } and put a replace with return. )

Body:
The method declaration ends with ; that’s the reason for CS8112

The Main method has to return void (or ‘int’ )you’ve modified it to string, that’s the reason for CS5001

If you want the program to print the output on the console use:

using System;

....

 Console.WriteLine(output)


问:
Fetching the result based on sourcetype
I have written a query to fetch the all java exception count wise in splunk. But this query fetch across all sourcetype.

```<code>java.*.*Exception NOT warn  | rex "(?<rexexption>java*.*Exception)"| stats count by rexexption | table count,rexexption | sort count | reverse
</code>```

Now I want all these exceptions per sourcetype wise.

答:
Go to you splunk home\main page and click on data summary.
There you can see source , sourcetype and other fields. just select one sourcetype which you want to go for and edit your query.

Source => path where logs are stored

sourcetype => log files

if you know your sourcetype name then edit your search :

```<code>sourcetype = java_*log*.txt java.*.*Exception NOT warn  | rex "(?<rexexption>java*.*Exception)"| stats count by rexexption | table count,rexexption | sort count | reverse
</code>```

Title: Fetching the result based on sourcetype

Body:
I have written a query to fetch the all java exception count wise in splunk. But this query fetch across all sourcetype.

java.*.*Exception NOT warn  | rex "(?<rexexption>java*.*Exception)"| stats count by rexexption | table count,rexexption | sort count | reverse

Now I want all these exceptions per sourcetype wise.

Body:
Go to you splunk home\main page and click on data summary.
There you can see source , sourcetype and other fields. just select one sourcetype which you want to go for and edit your query.

Source => path where logs are stored

sourcetype => log files

if you know your sourcetype name then edit your search :

sourcetype = java_*log*.txt java.*.*Exception NOT warn  | rex "(?<rexexption>java*.*Exception)"| stats count by rexexption | table count,rexexption | sort count | reverse