问:
Error starting SCDF plugin in Ambari
I installed SCDF using Ambari, but I cannot seem to successfully start Spring Cloud Dataflow server. I am getting the following output from the log:

```<code>03:07:30.592 [main] ERROR org.springframework.boot.SpringApplication - Application startup failed
java.lang.IllegalStateException: Failed to load property source from location 'file:/etc/scdf/conf//servers.yml'
    at org.springframework.boot.context.config.ConfigFileApplicationListener$Loader.loadIntoGroup(ConfigFileApplicationListener.java:465)
    at org.springframework.boot.context.config.ConfigFileApplicationListener$Loader.load(ConfigFileApplicationListener.java:432)
    at org.springframework.boot.context.config.ConfigFileApplicationListener$Loader.load(ConfigFileApplicationListener.java:371)
    at org.springframework.boot.context.config.ConfigFileApplicationListener.addPropertySources(ConfigFileApplicationListener.java:214)
    at org.springframework.boot.context.config.ConfigFileApplicationListener.postProcessEnvironment(ConfigFileApplicationListener.java:184)
    at org.springframework.boot.context.config.ConfigFileApplicationListener.onApplicationEnvironmentPreparedEvent(ConfigFileApplicationListener.java:171)
    at org.springframework.boot.context.config.ConfigFileApplicationListener.onApplicationEvent(ConfigFileApplicationListener.java:157)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:167)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:139)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:122)
    at org.springframework.boot.context.event.EventPublishingRunListener.environmentPrepared(EventPublishingRunListener.java:74)
    at org.springframework.boot.SpringApplicationRunListeners.environmentPrepared(SpringApplicationRunListeners.java:54)
    at org.springframework.boot.SpringApplication.prepareEnvironment(SpringApplication.java:325)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:296)
    at org.springframework.boot.builder.SpringApplicationBuilder.run(SpringApplicationBuilder.java:134)
    at org.springframework.cloud.bootstrap.BootstrapApplicationListener.bootstrapServiceContext(BootstrapApplicationListener.java:175)
    at org.springframework.cloud.bootstrap.BootstrapApplicationListener.onApplicationEvent(BootstrapApplicationListener.java:98)
    at org.springframework.cloud.bootstrap.BootstrapApplicationListener.onApplicationEvent(BootstrapApplicationListener.java:64)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:167)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:139)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:122)
    at org.springframework.boot.context.event.EventPublishingRunListener.environmentPrepared(EventPublishingRunListener.java:74)
    at org.springframework.boot.SpringApplicationRunListeners.environmentPrepared(SpringApplicationRunListeners.java:54)
    at org.springframework.boot.SpringApplication.prepareEnvironment(SpringApplication.java:325)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:296)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107)
    at org.springframework.cloud.dataflow.server.yarn.YarnDataFlowServer.main(YarnDataFlowServer.java:34)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:48)
    at org.springframework.boot.loader.Launcher.launch(Launcher.java:87)
    at org.springframework.boot.loader.Launcher.launch(Launcher.java:50)
    at org.springframework.boot.loader.JarLauncher.main(JarLauncher.java:51)
Caused by: org.yaml.snakeyaml.parser.ParserException: while parsing a block mapping
 in 'reader', line 51, column 5:
        fsUri: hdfs://hdp.kgarza.com:8020
        ^
expected <block end>, but found Scalar
 in 'reader', line 57, column 46:
     ... cationClasspath: {{hadoop_home}}/conf,{{hadoop_home}}/*,{{hadoop ...
                                         ^

    at org.yaml.snakeyaml.parser.ParserImpl$ParseBlockMappingKey.produce(ParserImpl.java:569)
    at org.yaml.snakeyaml.parser.ParserImpl.peekEvent(ParserImpl.java:157)
    at org.yaml.snakeyaml.parser.ParserImpl.checkEvent(ParserImpl.java:147)
    at org.yaml.snakeyaml.composer.Composer.composeMappingNode(Composer.java:224)
    at org.yaml.snakeyaml.composer.Composer.composeNode(Composer.java:155)
    at org.yaml.snakeyaml.composer.Composer.composeValueNode(Composer.java:246)
    at org.yaml.snakeyaml.composer.Composer.composeMappingChildren(Composer.java:237)
    at org.yaml.snakeyaml.composer.Composer.composeMappingNode(Composer.java:225)
    at org.yaml.snakeyaml.composer.Composer.composeNode(Composer.java:155)
    at org.yaml.snakeyaml.composer.Composer.composeValueNode(Composer.java:246)
    at org.yaml.snakeyaml.composer.Composer.composeMappingChildren(Composer.java:237)
    at org.yaml.snakeyaml.composer.Composer.composeMappingNode(Composer.java:225)
    at org.yaml.snakeyaml.composer.Composer.composeNode(Composer.java:155)
    at org.yaml.snakeyaml.composer.Composer.composeDocument(Composer.java:122)
    at org.yaml.snakeyaml.composer.Composer.getNode(Composer.java:84)
    at org.yaml.snakeyaml.constructor.BaseConstructor.getData(BaseConstructor.java:104)
    at org.yaml.snakeyaml.Yaml$1.next(Yaml.java:471)
    at org.springframework.beans.factory.config.YamlProcessor.process(YamlProcessor.java:160)
    at org.springframework.beans.factory.config.YamlProcessor.process(YamlProcessor.java:138)
    at org.springframework.boot.env.YamlPropertySourceLoader$Processor.process(YamlPropertySourceLoader.java:101)
    at org.springframework.boot.env.YamlPropertySourceLoader.load(YamlPropertySourceLoader.java:58)
    at org.springframework.boot.env.PropertySourcesLoader.load(PropertySourcesLoader.java:127)
    at org.springframework.boot.context.config.ConfigFileApplicationListener$Loader.doLoadIntoGroup(ConfigFileApplicationListener.java:479)
    at org.springframework.boot.context.config.ConfigFileApplicationListener$Loader.loadIntoGroup(ConfigFileApplicationListener.java:462)
    ... 35 common frames omitted
</code>```

Here is my servers.yml configuration:

```<code># Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License.  You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

---
spring:
  cloud:
    stream:
      kafka:
        binder:
          brokers: 192.168.1.43:6667
          zkNodes: 192.168.1.43:2181

---
spring:
  datasource:
    url: jdbc:h2:tcp://hdp.kgarza.com:19092/dataflow
    username: sa
    password:
    driverClassName: org.h2.Driver

---
spring:
  cloud:
    dataflow:
      metrics:
        collector:
          uri: http://hdp.kgarza.com:18080
    stream:
      bindings:
        applicationMetrics:
          destination: metrics
---
dataflow:
  uri: http://hdp.kgarza.com:9393
spring:
  hadoop:
    fsUri: hdfs://hdp.kgarza.com:8020
    resourceManagerAddress: hdp.kgarza.com:8050
    resourceManagerHost: hdp.kgarza.com
    resourceManagerPort: 8050
    resourceManagerSchedulerAddress: hdp.kgarza.com:8030
    jobHistoryAddress: hdp.kgarza.com:10020
    yarnApplicationClasspath: {{hadoop_home}}/conf,{{hadoop_home}}/*,{{hadoop_home}}/lib/*,/usr/hdp/current/hadoop-hdfs-client/*,/usr/hdp/current/hadoop-hdfs-client/lib/*,/usr/hdp/current/hadoop-yarn-client/*,/usr/hdp/current/hadoop-yarn-client/lib/*,/usr/hdp/current/ext/hadoop/*
    config:
      yarn.resourcemanager.scheduler.address: hdp.kgarza.com:8030
      mapreduce.application.framework.path: /hdp/apps/2.6.0.3-8/mapreduce/mapreduce.tar.gz#mr-framework
      mapreduce.application.classpath: $PWD/mr-framework/hadoop/share/hadoop/mapreduce/*:$PWD/mr-framework/hadoop/share/hadoop/mapreduce/lib/*:$PWD/mr-framework/hadoop/share/hadoop/common/*:$PWD/mr-framework/hadoop/share/hadoop/common/lib/*:$PWD/mr-framework/hadoop/share/hadoop/yarn/*:$PWD/mr-framework/hadoop/share/hadoop/yarn/lib/*:$PWD/mr-framework/hadoop/share/hadoop/hdfs/*:$PWD/mr-framework/hadoop/share/hadoop/hdfs/lib/*:$PWD/mr-framework/hadoop/share/hadoop/tools/lib/*:/usr/hdp/2.6.0.3-8/hadoop/lib/hadoop-lzo-0.6.0.2.6.0.3-8.jar:/etc/hadoop/conf/secure:/usr/hdp/current/ext/hadoop/*

---
dataflow.server.port : 9393
deployer.yarn.app.baseDir : '/dataflow'
h2.server.port : 19092
maven.remoteRepositories.springRepo.url : 'https://repo.spring.io/libs-snapshot'
metrics.collector.binder : 'kafka-10'
metrics.collector.channel : 'metrics'
metrics.collector.enabled : true
metrics.collector.server.port : 18080
spring.cloud.deployer.yarn.app.streamappmaster.javaOpts : '-Xms512m -Xmx512m'
spring.cloud.deployer.yarn.app.streamappmaster.memory : 1024
spring.cloud.deployer.yarn.app.streamcontainer.javaOpts : '-Xms512m -Xmx512m'
spring.cloud.deployer.yarn.app.streamcontainer.memory : 1024
spring.cloud.deployer.yarn.app.taskappmaster.javaOpts : '-Xms512m -Xmx512m'
spring.cloud.deployer.yarn.app.taskappmaster.memory : 1024
spring.cloud.deployer.yarn.app.taskcontainer.javaOpts : '-Xms512m -Xmx512m'
spring.cloud.deployer.yarn.app.taskcontainer.memory : 1024
spring.cloud.stream.kafka.binder.brokers : '192.168.1.43:6667'
spring.cloud.stream.kafka.binder.zkNodes : '192.168.1.43:2181'
spring.rabbitmq.password : 'guest'
spring.rabbitmq.username : 'guest'
</code>```

It seems like the problem is related with the configuration in the servers.yml on line 51 according to the logs, but I cannot see what it is that is wrong.

edit:
Upon further review it seems that there is an error in the servers.yml in the line
    yarnApplicationClasspath: {{hadoop_home}}/conf,{{hadoop_home}}/,{{hadoop_home}}/lib/,/usr/hdp/current/hadoop-hdfs-client/,/usr/hdp/current/hadoop-hdfs-client/lib/,/usr/hdp/current/hadoop-yarn-client/,/usr/hdp/current/hadoop-yarn-client/lib/,/usr/hdp/current/ext/hadoop/*

I edited the file to replace the {{hadoop_home}} variable, but it seems that it gets overridden everytime I restart the scdf server from ambari.

答:
Indeed yarnApplicationClasspath: {{hadoop_home}} looks to be wrong.

Source for that is yarnApplicationClasspath: {{yarn_app_classpath}} and value is coming from yarn_app_classpath = config['configurations']['yarn-site']['yarn.application.classpath'].

Could you check what you actually have in yarn-site configs under ambari's yarn service?

i.e I have something like

```<code><property>
  <name>yarn.application.classpath</name>
  <value>$HADOOP_CONF_DIR,/usr/hdp/current/hadoop-client/*,/usr/hdp/current/hadoop-client/lib/*,/usr/hdp/current/hadoop-hdfs-client/*,/usr/hdp/current/hadoop-hdfs-client/lib/*,/usr/hdp/current/hadoop-yarn-client/*,/usr/hdp/current/hadoop-yarn-client/lib/*</value>
</property>
</code>```

Title: Error starting SCDF plugin in Ambari

Body:
I installed SCDF using Ambari, but I cannot seem to successfully start Spring Cloud Dataflow server. I am getting the following output from the log:

03:07:30.592 [main] ERROR org.springframework.boot.SpringApplication - Application startup failed
java.lang.IllegalStateException: Failed to load property source from location 'file:/etc/scdf/conf//servers.yml'
    at org.springframework.boot.context.config.ConfigFileApplicationListener$Loader.loadIntoGroup(ConfigFileApplicationListener.java:465)
    at org.springframework.boot.context.config.ConfigFileApplicationListener$Loader.load(ConfigFileApplicationListener.java:432)
    at org.springframework.boot.context.config.ConfigFileApplicationListener$Loader.load(ConfigFileApplicationListener.java:371)
    at org.springframework.boot.context.config.ConfigFileApplicationListener.addPropertySources(ConfigFileApplicationListener.java:214)
    at org.springframework.boot.context.config.ConfigFileApplicationListener.postProcessEnvironment(ConfigFileApplicationListener.java:184)
    at org.springframework.boot.context.config.ConfigFileApplicationListener.onApplicationEnvironmentPreparedEvent(ConfigFileApplicationListener.java:171)
    at org.springframework.boot.context.config.ConfigFileApplicationListener.onApplicationEvent(ConfigFileApplicationListener.java:157)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:167)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:139)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:122)
    at org.springframework.boot.context.event.EventPublishingRunListener.environmentPrepared(EventPublishingRunListener.java:74)
    at org.springframework.boot.SpringApplicationRunListeners.environmentPrepared(SpringApplicationRunListeners.java:54)
    at org.springframework.boot.SpringApplication.prepareEnvironment(SpringApplication.java:325)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:296)
    at org.springframework.boot.builder.SpringApplicationBuilder.run(SpringApplicationBuilder.java:134)
    at org.springframework.cloud.bootstrap.BootstrapApplicationListener.bootstrapServiceContext(BootstrapApplicationListener.java:175)
    at org.springframework.cloud.bootstrap.BootstrapApplicationListener.onApplicationEvent(BootstrapApplicationListener.java:98)
    at org.springframework.cloud.bootstrap.BootstrapApplicationListener.onApplicationEvent(BootstrapApplicationListener.java:64)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:167)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:139)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:122)
    at org.springframework.boot.context.event.EventPublishingRunListener.environmentPrepared(EventPublishingRunListener.java:74)
    at org.springframework.boot.SpringApplicationRunListeners.environmentPrepared(SpringApplicationRunListeners.java:54)
    at org.springframework.boot.SpringApplication.prepareEnvironment(SpringApplication.java:325)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:296)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107)
    at org.springframework.cloud.dataflow.server.yarn.YarnDataFlowServer.main(YarnDataFlowServer.java:34)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:48)
    at org.springframework.boot.loader.Launcher.launch(Launcher.java:87)
    at org.springframework.boot.loader.Launcher.launch(Launcher.java:50)
    at org.springframework.boot.loader.JarLauncher.main(JarLauncher.java:51)
Caused by: org.yaml.snakeyaml.parser.ParserException: while parsing a block mapping
 in 'reader', line 51, column 5:
        fsUri: hdfs://hdp.kgarza.com:8020
        ^
expected <block end>, but found Scalar
 in 'reader', line 57, column 46:
     ... cationClasspath: {{hadoop_home}}/conf,{{hadoop_home}}/*,{{hadoop ...
                                         ^

    at org.yaml.snakeyaml.parser.ParserImpl$ParseBlockMappingKey.produce(ParserImpl.java:569)
    at org.yaml.snakeyaml.parser.ParserImpl.peekEvent(ParserImpl.java:157)
    at org.yaml.snakeyaml.parser.ParserImpl.checkEvent(ParserImpl.java:147)
    at org.yaml.snakeyaml.composer.Composer.composeMappingNode(Composer.java:224)
    at org.yaml.snakeyaml.composer.Composer.composeNode(Composer.java:155)
    at org.yaml.snakeyaml.composer.Composer.composeValueNode(Composer.java:246)
    at org.yaml.snakeyaml.composer.Composer.composeMappingChildren(Composer.java:237)
    at org.yaml.snakeyaml.composer.Composer.composeMappingNode(Composer.java:225)
    at org.yaml.snakeyaml.composer.Composer.composeNode(Composer.java:155)
    at org.yaml.snakeyaml.composer.Composer.composeValueNode(Composer.java:246)
    at org.yaml.snakeyaml.composer.Composer.composeMappingChildren(Composer.java:237)
    at org.yaml.snakeyaml.composer.Composer.composeMappingNode(Composer.java:225)
    at org.yaml.snakeyaml.composer.Composer.composeNode(Composer.java:155)
    at org.yaml.snakeyaml.composer.Composer.composeDocument(Composer.java:122)
    at org.yaml.snakeyaml.composer.Composer.getNode(Composer.java:84)
    at org.yaml.snakeyaml.constructor.BaseConstructor.getData(BaseConstructor.java:104)
    at org.yaml.snakeyaml.Yaml$1.next(Yaml.java:471)
    at org.springframework.beans.factory.config.YamlProcessor.process(YamlProcessor.java:160)
    at org.springframework.beans.factory.config.YamlProcessor.process(YamlProcessor.java:138)
    at org.springframework.boot.env.YamlPropertySourceLoader$Processor.process(YamlPropertySourceLoader.java:101)
    at org.springframework.boot.env.YamlPropertySourceLoader.load(YamlPropertySourceLoader.java:58)
    at org.springframework.boot.env.PropertySourcesLoader.load(PropertySourcesLoader.java:127)
    at org.springframework.boot.context.config.ConfigFileApplicationListener$Loader.doLoadIntoGroup(ConfigFileApplicationListener.java:479)
    at org.springframework.boot.context.config.ConfigFileApplicationListener$Loader.loadIntoGroup(ConfigFileApplicationListener.java:462)
    ... 35 common frames omitted

Here is my servers.yml configuration:

# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License.  You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

---
spring:
  cloud:
    stream:
      kafka:
        binder:
          brokers: 192.168.1.43:6667
          zkNodes: 192.168.1.43:2181

---
spring:
  datasource:
    url: jdbc:h2:tcp://hdp.kgarza.com:19092/dataflow
    username: sa
    password:
    driverClassName: org.h2.Driver

---
spring:
  cloud:
    dataflow:
      metrics:
        collector:
          uri: http://hdp.kgarza.com:18080
    stream:
      bindings:
        applicationMetrics:
          destination: metrics
---
dataflow:
  uri: http://hdp.kgarza.com:9393
spring:
  hadoop:
    fsUri: hdfs://hdp.kgarza.com:8020
    resourceManagerAddress: hdp.kgarza.com:8050
    resourceManagerHost: hdp.kgarza.com
    resourceManagerPort: 8050
    resourceManagerSchedulerAddress: hdp.kgarza.com:8030
    jobHistoryAddress: hdp.kgarza.com:10020
    yarnApplicationClasspath: {{hadoop_home}}/conf,{{hadoop_home}}/*,{{hadoop_home}}/lib/*,/usr/hdp/current/hadoop-hdfs-client/*,/usr/hdp/current/hadoop-hdfs-client/lib/*,/usr/hdp/current/hadoop-yarn-client/*,/usr/hdp/current/hadoop-yarn-client/lib/*,/usr/hdp/current/ext/hadoop/*
    config:
      yarn.resourcemanager.scheduler.address: hdp.kgarza.com:8030
      mapreduce.application.framework.path: /hdp/apps/2.6.0.3-8/mapreduce/mapreduce.tar.gz#mr-framework
      mapreduce.application.classpath: $PWD/mr-framework/hadoop/share/hadoop/mapreduce/*:$PWD/mr-framework/hadoop/share/hadoop/mapreduce/lib/*:$PWD/mr-framework/hadoop/share/hadoop/common/*:$PWD/mr-framework/hadoop/share/hadoop/common/lib/*:$PWD/mr-framework/hadoop/share/hadoop/yarn/*:$PWD/mr-framework/hadoop/share/hadoop/yarn/lib/*:$PWD/mr-framework/hadoop/share/hadoop/hdfs/*:$PWD/mr-framework/hadoop/share/hadoop/hdfs/lib/*:$PWD/mr-framework/hadoop/share/hadoop/tools/lib/*:/usr/hdp/2.6.0.3-8/hadoop/lib/hadoop-lzo-0.6.0.2.6.0.3-8.jar:/etc/hadoop/conf/secure:/usr/hdp/current/ext/hadoop/*

---
dataflow.server.port : 9393
deployer.yarn.app.baseDir : '/dataflow'
h2.server.port : 19092
maven.remoteRepositories.springRepo.url : 'https://repo.spring.io/libs-snapshot'
metrics.collector.binder : 'kafka-10'
metrics.collector.channel : 'metrics'
metrics.collector.enabled : true
metrics.collector.server.port : 18080
spring.cloud.deployer.yarn.app.streamappmaster.javaOpts : '-Xms512m -Xmx512m'
spring.cloud.deployer.yarn.app.streamappmaster.memory : 1024
spring.cloud.deployer.yarn.app.streamcontainer.javaOpts : '-Xms512m -Xmx512m'
spring.cloud.deployer.yarn.app.streamcontainer.memory : 1024
spring.cloud.deployer.yarn.app.taskappmaster.javaOpts : '-Xms512m -Xmx512m'
spring.cloud.deployer.yarn.app.taskappmaster.memory : 1024
spring.cloud.deployer.yarn.app.taskcontainer.javaOpts : '-Xms512m -Xmx512m'
spring.cloud.deployer.yarn.app.taskcontainer.memory : 1024
spring.cloud.stream.kafka.binder.brokers : '192.168.1.43:6667'
spring.cloud.stream.kafka.binder.zkNodes : '192.168.1.43:2181'
spring.rabbitmq.password : 'guest'
spring.rabbitmq.username : 'guest'

It seems like the problem is related with the configuration in the servers.yml on line 51 according to the logs, but I cannot see what it is that is wrong.

edit:
Upon further review it seems that there is an error in the servers.yml in the line
    yarnApplicationClasspath: {{hadoop_home}}/conf,{{hadoop_home}}/,{{hadoop_home}}/lib/,/usr/hdp/current/hadoop-hdfs-client/,/usr/hdp/current/hadoop-hdfs-client/lib/,/usr/hdp/current/hadoop-yarn-client/,/usr/hdp/current/hadoop-yarn-client/lib/,/usr/hdp/current/ext/hadoop/*

I edited the file to replace the {{hadoop_home}} variable, but it seems that it gets overridden everytime I restart the scdf server from ambari.

Body:
Indeed yarnApplicationClasspath: {{hadoop_home}} looks to be wrong.

Source for that is yarnApplicationClasspath: {{yarn_app_classpath}} and value is coming from yarn_app_classpath = config['configurations']['yarn-site']['yarn.application.classpath'].

Could you check what you actually have in yarn-site configs under ambari's yarn service?

i.e I have something like

<property>
  <name>yarn.application.classpath</name>
  <value>$HADOOP_CONF_DIR,/usr/hdp/current/hadoop-client/*,/usr/hdp/current/hadoop-client/lib/*,/usr/hdp/current/hadoop-hdfs-client/*,/usr/hdp/current/hadoop-hdfs-client/lib/*,/usr/hdp/current/hadoop-yarn-client/*,/usr/hdp/current/hadoop-yarn-client/lib/*</value>
</property>


来源: stackexchange

问:
Check seperate text file whether username already exists or not (Python Registration Programm)
I programmed a python file that allows you to register (Name, Password, EMail (with Confirmation EMail sent to you with a code)) and after you are registered your data is being saved in a seperate text file now I want python to check when you enter your username whether the username already exists or not.

There is this names.txt file and it is just
1Line: Username
2Line: Password
3Line: email adress
when you register a new enter code here unt it will show the same below the first account in the txt file.
But I want python to check this text file now during your registration whether you can use this username because its not used so far, or if the username already exists and you have to take another one.

```<code>import smtplib
import random
random.seed()

registrated=False

print("")
print("Namen Kriterien:")
print("-Mindestens 1 Buchstabe")
print("-Mindestens 4 Zeichen lang, maximal 20!")
print("-'Thats it!'")
print("")

fehler=1
while fehler==1:
    try:
        print("")
        name=input("Geben Sie Ihren Nutzernamen ein (4-20 Zeichen): ")
        if len(name) > 20 or len(name) < 4:
            print("Dein Name entspricht nicht den Kriterien!")
        else:
            print("")
            print("Dein Name ist:",name)
            print("")
            fehler2=1
            while fehler2==1:
                try:
                    q1=input("Ist das richtig? (YES | NO): ")
                    q1.upper()
                    if q1=="YES":
                        print("")
                        fehler2=0
                        fehler=0
                    elif q1=="NO":
                        print("")
                        fehler2=0

                    else:
                        print("")
                        print("ERROR")
                        print("")
                        fehler2=1
                except:
                    print("")
                    print("ERROR")
                    print("")
                    fehler2=1

    except:
        print("Versuche es nochmal!")
        fehler=1

print("Herzlichen Glückwunsch, dein Name ist",name)
fehler1=1
while fehler1==1:
    try:
        print("")
        pw=input("Bitte gib dein Passwort ein (selbe Kriterien wie der Name): ")
        if len(pw) > 20 or len(name) < 4:
            print("Das Passwort entsprcht nicht den Kriterien!")
        else:
            pw1=input("Bitte bestätige dein Passwort: ")
            if pw1==pw:
                fehler1=0
            else:
                print("")
                print("DEIN PASSWORT WAR FALSCH, BITTE WIEDERHOLEN!")
                print("")
                fehler1=1
    except:
        print("Versuche es nochmal!")
        fehler1=1
#Mail
import smtplib
import random
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
random.seed()

while 1:
    print("")
    email=input("Please enter your email adress: ")
    email1=input("Please confirm your email adress: ")
    if email == email1:
        break
    else:
        print("Something went wrongt, try again!")

email_user='register.confirmation.mnstudio@gmail.com'
email_pw='mnstudiophytonnht1102'
code=random.randint(10000,99999)
body='Hi there, thanks for using mnstudio programs, your code is: '+str(code)
subject='Registration to Mnstudio!'
msg = MIMEMultipart()
msg['From'] = email_user
msg['To'] = email
msg['subject'] = subject
msg.attach(MIMEText(body,'plain'))
text = msg.as_string()

server= smtplib.SMTP('smtp.gmail.com',587)
server.starttls()
server.login(email_user,email_pw)

fh=1
fhh=1
while fh==1:
    try:
        server.sendmail(email_user,email,text)
        print("")
        print("DONE EMAIL SENT")
        print("")
        print("We sent you an email with the confirmation code, please check spam as well if you cant find it!")
        print("")
        fh=0
    except:
        fhh=1
        print("")
        print("SOMETHING WENT WRONG WE'LL TRY AGAIN")
        print("")
        while fhh==1:
            try:
                print(email)
                q=input("Is the email correct? (YES | NO): ")
                print("")
                q.upper()
                if q=="YES":
                    fhh=0
                    fh=1
                elif q=="NO":
                    fhh=1
                    email=input("Please enter your email again: ")
                    email1=input("Please confirm email: ")
                    if email==email1:
                        print("")
                        print("Thanks we'll try to send an email to,",email)
                        print("")
                        fhh=0
                        fh=1
                    else:
                        print("ERROR TRY AGAIN")
                        fhh=1
                        fh=1
                else:
                    fhh=1
                    print("ANSWER WITH (YES | NO)")
            except:
                print("ANSWER WITH (YES | NO)")
        fh=1

server.quit()

while True:
    codeconfirm=int(input("Bitte geben Sie den Code ein: "))
    print("")
    if codeconfirm==code:
        registrated=True
        print("CODE CORRECT")
        print("")
        break
    else:
        print("Code war falsch bitte noch einmal eingeben !")

#
if registrated:
    dateihandler = open('names.txt', mode='a')

    dateihandler.write("\n"+str(name))
    dateihandler.write("\n"+str(pw))
    dateihandler.write("\n"+str(email))
    dateihandler.write("\n")

print("Danke du bist jetzt registriert! ")
input("")
</code>```

答: If you load the file and load usernames in a simple list you can check if new username exists or not in the list with simple is ... in ... but is not very clean solution, but if you are doing some exercise or something like this is a good first step, but I repeat, I think that your solution to the problem that I imagine that you have is not good in a real scenario.

ContentLicense: CC BY-SA 3.0

Body:
I programmed a python file that allows you to register (Name, Password, EMail (with Confirmation EMail sent to you with a code)) and after you are registered your data is being saved in a seperate text file now I want python to check when you enter your username whether the username already exists or not.

There is this names.txt file and it is just
1Line: Username
2Line: Password
3Line: email adress
when you register a new enter code here unt it will show the same below the first account in the txt file.
But I want python to check this text file now during your registration whether you can use this username because its not used so far, or if the username already exists and you have to take another one.

import smtplib
import random
random.seed()

registrated=False

print("")
print("Namen Kriterien:")
print("-Mindestens 1 Buchstabe")
print("-Mindestens 4 Zeichen lang, maximal 20!")
print("-'Thats it!'")
print("")

fehler=1
while fehler==1:
    try:
        print("")
        name=input("Geben Sie Ihren Nutzernamen ein (4-20 Zeichen): ")
        if len(name) > 20 or len(name) < 4:
            print("Dein Name entspricht nicht den Kriterien!")
        else:
            print("")
            print("Dein Name ist:",name)
            print("")
            fehler2=1
            while fehler2==1:
                try:
                    q1=input("Ist das richtig? (YES | NO): ")
                    q1.upper()
                    if q1=="YES":
                        print("")
                        fehler2=0
                        fehler=0
                    elif q1=="NO":
                        print("")
                        fehler2=0

                    else:
                        print("")
                        print("ERROR")
                        print("")
                        fehler2=1
                except:
                    print("")
                    print("ERROR")
                    print("")
                    fehler2=1

    except:
        print("Versuche es nochmal!")
        fehler=1

print("Herzlichen Glückwunsch, dein Name ist",name)
fehler1=1
while fehler1==1:
    try:
        print("")
        pw=input("Bitte gib dein Passwort ein (selbe Kriterien wie der Name): ")
        if len(pw) > 20 or len(name) < 4:
            print("Das Passwort entsprcht nicht den Kriterien!")
        else:
            pw1=input("Bitte bestätige dein Passwort: ")
            if pw1==pw:
                fehler1=0
            else:
                print("")
                print("DEIN PASSWORT WAR FALSCH, BITTE WIEDERHOLEN!")
                print("")
                fehler1=1
    except:
        print("Versuche es nochmal!")
        fehler1=1
#Mail
import smtplib
import random
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
random.seed()

while 1:
    print("")
    email=input("Please enter your email adress: ")
    email1=input("Please confirm your email adress: ")
    if email == email1:
        break
    else:
        print("Something went wrongt, try again!")

email_user='register.confirmation.mnstudio@gmail.com'
email_pw='mnstudiophytonnht1102'
code=random.randint(10000,99999)
body='Hi there, thanks for using mnstudio programs, your code is: '+str(code)
subject='Registration to Mnstudio!'
msg = MIMEMultipart()
msg['From'] = email_user
msg['To'] = email
msg['subject'] = subject
msg.attach(MIMEText(body,'plain'))
text = msg.as_string()

server= smtplib.SMTP('smtp.gmail.com',587)
server.starttls()
server.login(email_user,email_pw)

fh=1
fhh=1
while fh==1:
    try:
        server.sendmail(email_user,email,text)
        print("")
        print("DONE EMAIL SENT")
        print("")
        print("We sent you an email with the confirmation code, please check spam as well if you cant find it!")
        print("")
        fh=0
    except:
        fhh=1
        print("")
        print("SOMETHING WENT WRONG WE'LL TRY AGAIN")
        print("")
        while fhh==1:
            try:
                print(email)
                q=input("Is the email correct? (YES | NO): ")
                print("")
                q.upper()
                if q=="YES":
                    fhh=0
                    fh=1
                elif q=="NO":
                    fhh=1
                    email=input("Please enter your email again: ")
                    email1=input("Please confirm email: ")
                    if email==email1:
                        print("")
                        print("Thanks we'll try to send an email to,",email)
                        print("")
                        fhh=0
                        fh=1
                    else:
                        print("ERROR TRY AGAIN")
                        fhh=1
                        fh=1
                else:
                    fhh=1
                    print("ANSWER WITH (YES | NO)")
            except:
                print("ANSWER WITH (YES | NO)")
        fh=1

server.quit()

while True:
    codeconfirm=int(input("Bitte geben Sie den Code ein: "))
    print("")
    if codeconfirm==code:
        registrated=True
        print("CODE CORRECT")
        print("")
        break
    else:
        print("Code war falsch bitte noch einmal eingeben !")

#
if registrated:
    dateihandler = open('names.txt', mode='a')

    dateihandler.write("\n"+str(name))
    dateihandler.write("\n"+str(pw))
    dateihandler.write("\n"+str(email))
    dateihandler.write("\n")

print("Danke du bist jetzt registriert! ")
input("")


问:
Where is the error? "SystemError: new style getargs format but argument is not a tuple"
I am doing an image processing Lane Detection project. Im getting this error within my code. Im hoping someone can help me figure out how to fix this error.

Here is the function:

```<code>def draw_lane_lines(image, lines, color = [255,0,0], thickness=20):
  line_image=np.zeros_like(image)
  for line in lines:
    if line is not None:
    cv2.line(*(line_image, [line], color, thickness))
</code>```

The name of the error is: SystemError: new style getargs format but argument is not a tuple.

The error seems to be in the last line of the code.

答:
You are correct in the origin of the problem; it's the cv2.line function.
Take a look at this:
https://pythonprogramming.net/drawing-writing-python-opencv-tutorial/

I think your color needs to be a tuple (255,0,0) instead of a list [255,0,0].

Edit: You'll likely have the same problem with your line arg...I think it needs to be a tuple as well.

Body:
I am doing an image processing Lane Detection project. Im getting this error within my code. Im hoping someone can help me figure out how to fix this error.

Here is the function:

def draw_lane_lines(image, lines, color = [255,0,0], thickness=20):
  line_image=np.zeros_like(image)
  for line in lines:
    if line is not None:
    cv2.line(*(line_image, [line], color, thickness))

The name of the error is: SystemError: new style getargs format but argument is not a tuple.

The error seems to be in the last line of the code.


问:
Prevent Renaming of Google Forms File Upload
I have a Google Form that uses the File Upload feature that is mentioned on the below site,
https://sites.google.com/site/scriptsexamples/home/announcements/google-forms-file-upload-feature

I am wondering 2 things:

Is there a way to prevent the renaming of the uploaded file. (IE: original_file_name - Name of Uploader)

Concerning the below quote:

If a respondent decides to upload a file directly from his Drive, a
  copy will be made and the form owner will become owner of the copy.

Is it possible to identify the original file and remove it so that it does not junk up the uploaders root Drive folder.

```<code>function getCurrentResponses() {
  var form = FormApp.openById('formID');
  var formResponses = form.getResponses();
  var numResponses = formResponses.length;
  var lastResponse = formResponses[numResponses - 1];
  var lastResponseItem = lastResponse.getItemResponses();
  var emailAddress = lastResponseItem[0].getResponse();
  Logger.log('emailAddress: ' + emailAddress);
  var zone = lastResponseItem[1].getResponse();
  Logger.log('zone: ' + zone);
  var projectName = lastResponseItem[2].getResponse();
  Logger.log('projectName: ' + projectName);
  var igeURL = lastResponseItem[3].getResponse();
  Logger.log('igeURL: ' + igeURL);

//Creating folder for submitted project
  var DriveFolder = DriveApp.getFolderById("destinationFolder");
  var folderName = projectName;
  //create the folder
  var folderpath = DriveFolder.createFolder(folderName).addEditor(emailAddress).getId();
//get the path to the folder
  var pathtoemail = "https://drive.google.com/drive/folders/"+folderpath;
  var file = DriveApp.getFileById(igeURL);
  file.getParents().next().removeFile(file);
  DriveApp.getFolderById(folderpath).addFile(file);
  var fileName = file.getName();

  //Create the message and subject of the email
var message = 'Thank you for submitting. Here is the link to your drive folder. Please use this folder to upload and receive related documentation. ' +pathtoemail ;  //a custom message, feel free to change anything inside the quotes

var subject = "Form Related Documentation." ;
//send the email
     MailApp.sendEmail(emailAddress, subject, message, {
  // cc: 'email@email.com'         // optional cc

 });

/*
 * Convert Excel file to Sheets
 * https://gist.github.com/azadisaryev/ab57e95096203edc2741
 * Retrieved 06/08/2017
*/

  var xlsId = igeURL; // ID of Excel file to convert
  var xlsFile = DriveApp.getFileById(xlsId); // File instance of Excel file
  var xlsBlob = xlsFile.getBlob(); // Blob source of Excel file for conversion
  var xlsFilename = xlsFile.getName(); // File name to give to converted file; defaults to same as source file
  var destFolders = folderpath; // array of IDs of Drive folders to put converted file in; empty array = root folder
  Logger.log("destFolders: " + destFolders);
  var ss = convertExcel2Sheets(xlsBlob, xlsFilename, destFolders);
  var ssID = ss.getId();
  Logger.log(ss.getId());
  var convertFile = DriveApp.getFileById(ssID);
  convertFile.getParents().next().removeFile(convertFile);
  DriveApp.getFolderById(folderpath).addFile(convertFile);

}

/**
 * Convert Excel file to Sheets
 * https://gist.github.com/azadisaryev/ab57e95096203edc2741
 * Retrieved 06/08/2017
 * @param {Blob} excelFile The Excel file blob data; Required
 * @param {String} filename File name on uploading drive; Required
 * @param {Array} arrParents Array of folder ids to put converted file in; Optional, will default to Drive root folder
 * @return {Spreadsheet} Converted Google Spreadsheet instance
 **/
function convertExcel2Sheets(excelFile, filename, arrParents) {

  var parents  = arrParents || []; // check if optional arrParents argument was provided, default to empty array if not
  if ( !parents.isArray ) parents = []; // make sure parents is an array, reset to empty array if not
  Logger.log("arrParents: " + arrParents);

  // Parameters for Drive API Simple Upload request (see https://developers.google.com/drive/web/manage-uploads#simple)
  var uploadParams = {
    method:'post',
    contentType: 'application/vnd.ms-excel', // works for both .xls and .xlsx files
    contentLength: excelFile.getBytes().length,
    headers: {'Authorization': 'Bearer ' + ScriptApp.getOAuthToken()},
    payload: excelFile.getBytes()
  };

  // Upload file to Drive root folder and convert to Sheets
  var uploadResponse = UrlFetchApp.fetch('https://www.googleapis.com/upload/drive/v2/files/?uploadType=media&convert=true', uploadParams);

  // Parse upload&convert response data (need this to be able to get id of converted sheet)
  var fileDataResponse = JSON.parse(uploadResponse.getContentText());

  // Create payload (body) data for updating converted file's name and parent folder(s)
  var payloadData = {
    title: filename,
    parents: []
  };
  if ( parents.length ) { // Add provided parent folder(s) id(s) to payloadData, if any
    for ( var i=0; i<parents.length; i++ ) {
      try {
        var folder = DriveApp.getFolderById(parents[i]); // check that this folder id exists in drive and user can write to it
        payloadData.parents.push({id: parents[i]});
      }
      catch(e){} // fail silently if no such folder id exists in Drive
    }
  }
  // Parameters for Drive API File Update request (see https://developers.google.com/drive/v2/reference/files/update)
  var updateParams = {
    method:'put',
    headers: {'Authorization': 'Bearer ' + ScriptApp.getOAuthToken()},
    contentType: 'application/json',
    payload: JSON.stringify(payloadData)
  };

  // Update metadata (filename and parent folder(s)) of converted sheet
  UrlFetchApp.fetch('https://www.googleapis.com/drive/v2/files/'+fileDataResponse.id, updateParams);

  return SpreadsheetApp.openById(fileDataResponse.id);
}
</code>```

答:
I change your code a little bit so the name of the file is changed to its ID.

function changenametoid() {
var form = FormApp.openById('formID');
var formResponses = form.getResponses();
var numResponses = formResponses.length;
var lastResponse = formResponses[numResponses - 1];
var lastResponseItem = lastResponse.getItemResponses();
var submittedID = lastResponseItem[0].getResponse();
var file = DriveApp.getFileById(submittedID);
var oldFileName = file.getName();
var indexOldFileName = oldFileName.indexOf("-");
var newFileName = submittedID;
var indexOldFileExt = oldFileName.lastIndexOf(".");
var newFileExt = oldFileName.slice(indexOldFileExt);
var modName = newFileName + newFileExt;
file.setName(modName);
}```

Body:
I have a Google Form that uses the File Upload feature that is mentioned on the below site,
https://sites.google.com/site/scriptsexamples/home/announcements/google-forms-file-upload-feature

I am wondering 2 things:

Is there a way to prevent the renaming of the uploaded file. (IE: original_file_name - Name of Uploader)

Concerning the below quote:

If a respondent decides to upload a file directly from his Drive, a
  copy will be made and the form owner will become owner of the copy.

Is it possible to identify the original file and remove it so that it does not junk up the uploaders root Drive folder.

function getCurrentResponses() {
  var form = FormApp.openById('formID');
  var formResponses = form.getResponses();
  var numResponses = formResponses.length;
  var lastResponse = formResponses[numResponses - 1];
  var lastResponseItem = lastResponse.getItemResponses();
  var emailAddress = lastResponseItem[0].getResponse();
  Logger.log('emailAddress: ' + emailAddress);
  var zone = lastResponseItem[1].getResponse();
  Logger.log('zone: ' + zone);
  var projectName = lastResponseItem[2].getResponse();
  Logger.log('projectName: ' + projectName);
  var igeURL = lastResponseItem[3].getResponse();
  Logger.log('igeURL: ' + igeURL);

//Creating folder for submitted project
  var DriveFolder = DriveApp.getFolderById("destinationFolder");
  var folderName = projectName;
  //create the folder
  var folderpath = DriveFolder.createFolder(folderName).addEditor(emailAddress).getId();
//get the path to the folder
  var pathtoemail = "https://drive.google.com/drive/folders/"+folderpath;
  var file = DriveApp.getFileById(igeURL);
  file.getParents().next().removeFile(file);
  DriveApp.getFolderById(folderpath).addFile(file);
  var fileName = file.getName();

  //Create the message and subject of the email
var message = 'Thank you for submitting. Here is the link to your drive folder. Please use this folder to upload and receive related documentation. ' +pathtoemail ;  //a custom message, feel free to change anything inside the quotes

var subject = "Form Related Documentation." ;
//send the email
     MailApp.sendEmail(emailAddress, subject, message, {
  // cc: 'email@email.com'         // optional cc

 });

/*
 * Convert Excel file to Sheets
 * https://gist.github.com/azadisaryev/ab57e95096203edc2741
 * Retrieved 06/08/2017
*/

  var xlsId = igeURL; // ID of Excel file to convert
  var xlsFile = DriveApp.getFileById(xlsId); // File instance of Excel file
  var xlsBlob = xlsFile.getBlob(); // Blob source of Excel file for conversion
  var xlsFilename = xlsFile.getName(); // File name to give to converted file; defaults to same as source file
  var destFolders = folderpath; // array of IDs of Drive folders to put converted file in; empty array = root folder
  Logger.log("destFolders: " + destFolders);
  var ss = convertExcel2Sheets(xlsBlob, xlsFilename, destFolders);
  var ssID = ss.getId();
  Logger.log(ss.getId());
  var convertFile = DriveApp.getFileById(ssID);
  convertFile.getParents().next().removeFile(convertFile);
  DriveApp.getFolderById(folderpath).addFile(convertFile);

}

/**
 * Convert Excel file to Sheets
 * https://gist.github.com/azadisaryev/ab57e95096203edc2741
 * Retrieved 06/08/2017
 * @param {Blob} excelFile The Excel file blob data; Required
 * @param {String} filename File name on uploading drive; Required
 * @param {Array} arrParents Array of folder ids to put converted file in; Optional, will default to Drive root folder
 * @return {Spreadsheet} Converted Google Spreadsheet instance
 **/
function convertExcel2Sheets(excelFile, filename, arrParents) {

  var parents  = arrParents || []; // check if optional arrParents argument was provided, default to empty array if not
  if ( !parents.isArray ) parents = []; // make sure parents is an array, reset to empty array if not
  Logger.log("arrParents: " + arrParents);

  // Parameters for Drive API Simple Upload request (see https://developers.google.com/drive/web/manage-uploads#simple)
  var uploadParams = {
    method:'post',
    contentType: 'application/vnd.ms-excel', // works for both .xls and .xlsx files
    contentLength: excelFile.getBytes().length,
    headers: {'Authorization': 'Bearer ' + ScriptApp.getOAuthToken()},
    payload: excelFile.getBytes()
  };

  // Upload file to Drive root folder and convert to Sheets
  var uploadResponse = UrlFetchApp.fetch('https://www.googleapis.com/upload/drive/v2/files/?uploadType=media&convert=true', uploadParams);

  // Parse upload&convert response data (need this to be able to get id of converted sheet)
  var fileDataResponse = JSON.parse(uploadResponse.getContentText());

  // Create payload (body) data for updating converted file's name and parent folder(s)
  var payloadData = {
    title: filename,
    parents: []
  };
  if ( parents.length ) { // Add provided parent folder(s) id(s) to payloadData, if any
    for ( var i=0; i<parents.length; i++ ) {
      try {
        var folder = DriveApp.getFolderById(parents[i]); // check that this folder id exists in drive and user can write to it
        payloadData.parents.push({id: parents[i]});
      }
      catch(e){} // fail silently if no such folder id exists in Drive
    }
  }
  // Parameters for Drive API File Update request (see https://developers.google.com/drive/v2/reference/files/update)
  var updateParams = {
    method:'put',
    headers: {'Authorization': 'Bearer ' + ScriptApp.getOAuthToken()},
    contentType: 'application/json',
    payload: JSON.stringify(payloadData)
  };

  // Update metadata (filename and parent folder(s)) of converted sheet
  UrlFetchApp.fetch('https://www.googleapis.com/drive/v2/files/'+fileDataResponse.id, updateParams);

  return SpreadsheetApp.openById(fileDataResponse.id);
}


问:
How to update a JSONB object with a parent in postgresql
I have a database with a table foo containing a column id and a column data with the following data:

```<code>{
   "startDate":"2017-07-04",
   "endDate":"2017-07-10",
   "notDelegated":false,
   "sold":false,
   "disableRanking":false,
   "type":"PERIOD"
}
</code>```

I would like to update this data with a parent rangeData and extract the type property like this:

```<code>{
   "rangeData": {
       "startDate":"2017-07-04",
       "endDate":"2017-07-10",
       "notDelegated":false,
       "sold":false,
       "disableRanking":false
   },
   "type":"PERIOD"
}
</code>```

I tried a lot of things with JSON operators in vain.

Thank you for your answers.

答:
Use the function jsonb_build_object() and delete operator:

```<code>update foo
set data = jsonb_build_object('rangeData', data- 'type', 'type', data->'type');
</code>```

In the above function call you are creating a json object with two elements:

```<code>key          value
-------------------------
'rangeData'  data- 'type'   json object 'data' from which the key 'type' was removed
'type'       data->'type'   value of 'type' element of json object 'data'
</code>```

SqlFiddle

Body:
I have a database with a table foo containing a column id and a column data with the following data:

{
   "startDate":"2017-07-04",
   "endDate":"2017-07-10",
   "notDelegated":false,
   "sold":false,
   "disableRanking":false,
   "type":"PERIOD"
}

I would like to update this data with a parent rangeData and extract the type property like this:

{
   "rangeData": {
       "startDate":"2017-07-04",
       "endDate":"2017-07-10",
       "notDelegated":false,
       "sold":false,
       "disableRanking":false
   },
   "type":"PERIOD"
}

I tried a lot of things with JSON operators in vain.

Thank you for your answers.

Body:
Use the function jsonb_build_object() and delete operator:

update foo
set data = jsonb_build_object('rangeData', data- 'type', 'type', data->'type');

In the above function call you are creating a json object with two elements:

key          value
-------------------------
'rangeData'  data- 'type'   json object 'data' from which the key 'type' was removed
'type'       data->'type'   value of 'type' element of json object 'data'

SqlFiddle


问:
List Classes inside jar dynamically
Alright, so I have this jar file
and I'd like to retrieve all the classes inside that jar.

I've seen some other questions, but, most of them require the class name or package name.

I'd like something that doesn't need this. Maybe a method that asks for the file path "example.jar", and then it returns a list with the various class names.

By the way, I don't really now if class name is the correct term, what i need is something like this "com.name.name1".

I would use the Strings retrieved from the jar with Reflection.
The result would be loading a jar dynamically without the need of any classnames.

答:
A jar file is basically just a zip file. You can open it with ZipInputStream and scan the contents. Any files whose name ends with ".class" should be a class, and you can fairly easily reconstruct the package name etc.

Alternatively, if you want more information about the classes, you should probably use a library (like this one) that handles class parsing for you - it's relatively complex.

Title: List Classes inside jar dynamically


问:
Between dynamic dates
So part of my query, I would like to filter the results to show just the ones between a set date range, however, that date range is dynamic, based on an event.

For example:

```<code>WHERE date d
   BETWEEN '2017-01-01'         -- just a sample fixed date
   AND DATEADD(D, CONTACT_DATE, -1) -- to show a day before Contact Date
</code>```

Basically just trying see if there was another CONTACT_DATE this year, excluding the day of the actual contact.

I know there could be other ways to do this, but I was wondering if I can tweak a query with the current logic.

ERROR:

Argument data type datetime is invalid for argument 2 of dateadd
  function.

答:
It should be:</p>

```<code>DATEADD(D, -1, CONTACT_DATE)
</code>```

Title: Between dynamic dates

Body:
So part of my query, I would like to filter the results to show just the ones between a set date range, however, that date range is dynamic, based on an event.

For example:

WHERE date d
   BETWEEN '2017-01-01'         -- just a sample fixed date
   AND DATEADD(D, CONTACT_DATE, -1) -- to show a day before Contact Date

Basically just trying see if there was another CONTACT_DATE this year, excluding the day of the actual contact.

I know there could be other ways to do this, but I was wondering if I can tweak a query with the current logic.

ERROR:

Argument data type datetime is invalid for argument 2 of dateadd
  function.

Body:
It should be:

DATEADD(D, -1, CONTACT_DATE)


问:
C# Date Converter Program
This will be a noobish question but I am currently working on a program that will take in a user input in the format of DD/MM/YYYY and the output it in the format 1st of May 2017, for example.

But whenever the use string.substring (UserInput.substring in my case) it does not separate the values correctly. For example, when I input the date as 21/05/2001 it displays 215 2001. I have no idea why this is happening.

Im sorry as this is very noobish but I am new to using .substring and I'm sure the problem will seem obvious when someone points it out xD

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DateProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            /// Define Varibles

            string UserIntput;
            int Day;
            int Month;
            int year;

            ///Gathering UserInput

            Console.Write("Please enter the date in the format dd/mm/yyyy");
            UserIntput = Console.ReadLine();

            ///Validations

            try
            {
                while(UserIntput.Substring(2,1) != "/" || UserIntput.Substring(5,1) != "/" || UserIntput.Length != 10)
                {
                    Console.WriteLine("Invalid Input");
                    Console.Write("Please enter the date in the format dd/mm/yyyy");
                    UserIntput = Console.ReadLine();

                }

            }
            catch
            {
                Console.WriteLine("Invalid Input");
            }

            /// Defining to Variables

            Day = Convert.ToInt32(UserIntput.Substring(0, 2));

            Month = Convert.ToInt32(UserIntput.Substring(3, 2));

            year = Convert.ToInt32(UserIntput.Substring(6, 4));

            Console.WriteLine(Day + "" + Month + " " + year);
            Console.ReadLine();
        }
    }
}
</code>```

答:
Pass your user input string in to a System.Convert.ToDateTime method:

```<code>DateTime dt = Convert.ToDateTime(UserIntput);
</code>```

Then, if you would like to change the format of how it is presented, use one of the DateTime.ToString() overloads to convert it to the format you want. (Search for ToString() on this page)

It might look something like this:

```<code>dt.ToString("MM-dd-yyyy", System.Globalization.CultureInfo.InvariantCulture);
</code>```

You'll also want to review this page: Custom Date and Time Format Strings

Title: C# Date Converter Program

Body:
This will be a noobish question but I am currently working on a program that will take in a user input in the format of DD/MM/YYYY and the output it in the format 1st of May 2017, for example.

But whenever the use string.substring (UserInput.substring in my case) it does not separate the values correctly. For example, when I input the date as 21/05/2001 it displays 215 2001. I have no idea why this is happening.

Im sorry as this is very noobish but I am new to using .substring and I'm sure the problem will seem obvious when someone points it out xD

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DateProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            /// Define Varibles

            string UserIntput;
            int Day;
            int Month;
            int year;

            ///Gathering UserInput

            Console.Write("Please enter the date in the format dd/mm/yyyy");
            UserIntput = Console.ReadLine();

            ///Validations

            try
            {
                while(UserIntput.Substring(2,1) != "/" || UserIntput.Substring(5,1) != "/" || UserIntput.Length != 10)
                {
                    Console.WriteLine("Invalid Input");
                    Console.Write("Please enter the date in the format dd/mm/yyyy");
                    UserIntput = Console.ReadLine();

                }

            }
            catch
            {
                Console.WriteLine("Invalid Input");
            }

            /// Defining to Variables

            Day = Convert.ToInt32(UserIntput.Substring(0, 2));

            Month = Convert.ToInt32(UserIntput.Substring(3, 2));

            year = Convert.ToInt32(UserIntput.Substring(6, 4));

            Console.WriteLine(Day + "" + Month + " " + year);
            Console.ReadLine();
        }
    }
}

Body:
Pass your user input string in to a System.Convert.ToDateTime method:

DateTime dt = Convert.ToDateTime(UserIntput);

Then, if you would like to change the format of how it is presented, use one of the DateTime.ToString() overloads to convert it to the format you want. (Search for ToString() on this page)

It might look something like this:

dt.ToString("MM-dd-yyyy", System.Globalization.CultureInfo.InvariantCulture);

You'll also want to review this page: Custom Date and Time Format Strings


问:
How to generate a random int in C?
Is there a function to generate a random int number in C?  Or will I have to use a third party library?</p>

答:
On modern x86_64 CPUs you can use the hardware random number generator via _rdrand64_step()

Example code:

```<code>#include <immintrin.h>

uint64_t randVal;
if(!_rdrand64_step(&randVal)) {
  // Report an error here: random number generation has failed!
}
// If no error occured, randVal contains a random 64-bit number
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to generate a random int in C?

Body:
On modern x86_64 CPUs you can use the hardware random number generator via <a href="https://software.intel.com/sites/landingpage/IntrinsicsGuide/#expand=5212,1794,594,533,533,3146,5223,5218,5213,5226,5224,4642,3170,3170,3170,2670,4708,5068,5661,740,740,5459,5495,568,594,3889,390,3567,3576,3923,5553,2381,4929,201,406,694,4602,5003,5098,555,5089,4648,4642,5105,4893,555,5159,5340,5340,5340,307,1481,3625,415,1481,5720,325,318,280,1725,435,2399,5483,5513,3250,443,576,579,4070,441,439,5532,5534,397,391,579,395,397,551,30,4953,4677,2399,4247,4247&techs=AVX,AVX2,FMA,Other&text=random" rel="nofollow noreferrer">_rdrand64_step()

Example code:

#include <immintrin.h>

uint64_t randVal;
if(!_rdrand64_step(&randVal)) {
  // Report an error here: random number generation has failed!
}
// If no error occured, randVal contains a random 64-bit number


问:
cannot connect to Minikube on MacOS
I installed minikube as instructed here https://github.com/kubernetes/minikube/releases
and started with with a simple minikube start command.

But the next step, which is as simple as kubectl get pods --all-namespaces fails with

Unable to connect to the server: dial tcp 192.168.99.100:8443: i/o timeout

What did I miss?

答:
You need to just restart minikube. Sometimes I have this problem when my computer has been off for a while. I don't think you need to reinstall anything.

First verify you are in the correct context

$ kubectl config current-context
minikube

Check Minikube status (status should show "Running", mine below showed "Saved")

$ minikube status
minikube: Saved
cluster:
kubectl:

Restart minikube

$ minikube start
Starting local Kubernetes v1.8.0 cluster...
Starting VM...
Getting VM IP address...
Moving files into cluster...
Setting up certs...
Connecting to cluster...
Setting up kubeconfig...
Starting cluster components...
Kubectl is now configured to use the cluster.

Verify it is running (This is what you should see)

$ minikube status
minikube: Running
cluster: Running
kubectl: Correctly Configured: pointing to minikube-vm at 192.168.99.100

Title: cannot connect to Minikube on MacOS


问:
Use of GetGuiResources
Is it a good idea to use GetGuiResources(GetCurrentProcess(), GR_GDIOBJECTS) at the start of WinMain, and before the last return to detect GDI leaks or, more specifically, objects I forgot to release?
Also I'm currently wondering why the first call in my program returns 4 when there's no window yet.

答: The code with this MSDN magazine article provided a slick way to troubleshoot GDI handle leaks.  Unfortunately, the source code no longer seems to be available...</p>

OwnerDisplayName: Zub

Title: Use of GetGuiResources

OwnerDisplayName: nobugz

ContentLicense: CC BY-SA 2.5


问:
Textarea Calculations
I'm trying to have three textareas. The first two are addends and the last is the sum. What's supposed to happen is if your math equation is correct, a paragraph will say true.

Else, it'll say false. However, the paragraph doesn't say anything when I try.
Here's my code:

```<code><textarea id="x"></textarea>
<textarea id="y"></textarea>
<textarea id="z"></textarea>
<script>
    var x = document.getElementById('x').innerHTML;
  var y = document.getElementById('y').innerHTML;
  var z = x + y;
  var p = document.getElementById('p');
</script>
<button oclick="if (z = document.getElementById('z').innerHTML) {p.innerHTML = true} else {p.innerHTML = false}">Calculate</button>
<br>
<p id="p"></p>
</code>```

答:
first of all, I suggest you to use input here instead of
Second thing is, I would suggest you to use function when you use 'onclick'

Here's the result:

```<code><html>
<body>
<input type='number' placeholder='x: (input number please)' id="x" />
<input type='number' placeholder='y: (input number please)' id="y" />
<input type='number' placeholder='z: (input number please)' id="z" />
<br />
<button onclick="CheckByFormula()">Calculate</button>
<br />
<p>Check result: z=x+y ?</p>
<p id="p"></p>
<script type='text/javascript'>
  function CheckByFormula(){
    var x = parseInt(document.getElementById('x').value);
  var y = parseInt(document.getElementById('y').value);
  var z = x + y;
  //alert('having these params:\n x='+x+' y='+y+' z='+z);
  var p = document.getElementById('p');
  z1 = parseInt(document.getElementById('z').value);
  alert('z1='+z1+' z='+z);
    if(z1 == z){
        document.getElementById('p').innerHTML = 'true'
    }
    else {
        document.getElementById('p').innerHTML = 'false';
    }
  }
</script>

</body>
</html>
</code>```

https://jsfiddle.net/14pm7ypz/2/

Title: Textarea Calculations

Body:
I'm trying to have three textareas. The first two are addends and the last is the sum. What's supposed to happen is if your math equation is correct, a paragraph will say true.

Else, it'll say false. However, the paragraph doesn't say anything when I try.
Here's my code:

<textarea id="x"></textarea>
<textarea id="y"></textarea>
<textarea id="z"></textarea>

<button oclick="if (z = document.getElementById('z').innerHTML) {p.innerHTML = true} else {p.innerHTML = false}">Calculate</button>

Body:
first of all, I suggest you to use input here instead of
Second thing is, I would suggest you to use function when you use 'onclick'

Here's the result:

<html>
<body>
<input type='number' placeholder='x: (input number please)' id="x" />
<input type='number' placeholder='y: (input number please)' id="y" />
<input type='number' placeholder='z: (input number please)' id="z" />
<br />
<button onclick="CheckByFormula()">Calculate</button>
<br />
<p>Check result: z=x+y ?</p>
<p id="p"></p>
<script type='text/javascript'>
  function CheckByFormula(){
    var x = parseInt(document.getElementById('x').value);
  var y = parseInt(document.getElementById('y').value);
  var z = x + y;
  //alert('having these params:\n x='+x+' y='+y+' z='+z);
  var p = document.getElementById('p');
  z1 = parseInt(document.getElementById('z').value);
  alert('z1='+z1+' z='+z);
    if(z1 == z){
        document.getElementById('p').innerHTML = 'true'
    }
    else {
        document.getElementById('p').innerHTML = 'false';
    }
  }
</script>

</body>
</html>

https://jsfiddle.net/14pm7ypz/2/


答:
You mixed the parameters.
The syntax is this:

```<code>DATEADD (datepart , number , date )
</code>```

You should change it to this:

```<code>DATEADD(D, -1, CONTACT_DATE)
</code>```

See here the docs:
https://msdn.microsoft.com/de-de/library/ms186819(v=sql.120).aspx

Title: Between dynamic dates

Body:
You mixed the parameters.
The syntax is this:

DATEADD (datepart , number , date )

You should change it to this:

DATEADD(D, -1, CONTACT_DATE)

See here the docs:
https://msdn.microsoft.com/de-de/library/ms186819(v=sql.120).aspx


问:
How to upload apk to crashlytics using Curl?
I'm trying to upload an APK to crashlytics with fastlane but i have some error that i cant resolve.
Also the official solution (doc) it is not good for me because the apk is already builded.

Is there a solution using curl?

答: Mike from Fabric here. We don't have a solution for uploading the APK via curl. However, you can upload built APKs through the Android Studio plugin. From command line,  we only support using Fastlane or uploads from the build flow in Ant, Maven or Gradle. </p>


答:
Use ParseExact like this:

```<code>using System;

public class Program
{
    public static void Main()
    {
        DateTime? dt = null;

        do
        {
            Console.WriteLine("Input date: (dd/MM/yyyy)");
            var input = Console.ReadLine();

            try
            {
                dt = DateTime.ParseExact(input, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture);
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        } while (!dt.HasValue);

        Console.WriteLine(dt.Value.ToString("F"));

        var myDate = dt.Value;

        // access the single fields from the parsed object
        Console.WriteLine(myDate.Day);
        Console.WriteLine(myDate.Month);
        Console.WriteLine(myDate.DayOfWeek);
        Console.WriteLine(myDate.Year);
    }
}
</code>```

See https://dotnetfiddle.net/TeYSF7

In addition to the "custom" link for DateTime-Formatting (see BobbyA's answer), consider these which come by default: standard-date-and-time-format-strings

Using string.Split(..) - although why if DateTime comes with valid ways to parse.

```<code>var parts = "22/12/2012".Split(new []{'/'}, StringSplitOptions.RemoveEmptyEntries);

if (parts.Length == 3)
{
    var day = int.Parse(parts[0]); // will crash if not an int - use .TryParse(...) or handle error
    var month = int.Parse(parts[1]); // will crash if not an int
    var year = int.Parse(parts[2]); // will crash if not an int

    var date = new DateTime(day,month,year)) // will crash if f.e. 45.24.788
}
else
{
    // invalid input
}
</code>```

Title: C# Date Converter Program

Body:
Use ParseExact like this:

using System;

public class Program
{
    public static void Main()
    {
        DateTime? dt = null;

        do
        {
            Console.WriteLine("Input date: (dd/MM/yyyy)");
            var input = Console.ReadLine();

            try
            {
                dt = DateTime.ParseExact(input, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture);
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        } while (!dt.HasValue);

        Console.WriteLine(dt.Value.ToString("F"));

        var myDate = dt.Value;

        // access the single fields from the parsed object
        Console.WriteLine(myDate.Day);
        Console.WriteLine(myDate.Month);
        Console.WriteLine(myDate.DayOfWeek);
        Console.WriteLine(myDate.Year);
    }
}

See https://dotnetfiddle.net/TeYSF7

In addition to the "custom" link for DateTime-Formatting (see BobbyA's answer), consider these which come by default: standard-date-and-time-format-strings

Using string.Split(..) - although why if DateTime comes with valid ways to parse.

var parts = "22/12/2012".Split(new []{'/'}, StringSplitOptions.RemoveEmptyEntries);

if (parts.Length == 3)
{
    var day = int.Parse(parts[0]); // will crash if not an int - use .TryParse(...) or handle error
    var month = int.Parse(parts[1]); // will crash if not an int
    var year = int.Parse(parts[2]); // will crash if not an int

    var date = new DateTime(day,month,year)) // will crash if f.e. 45.24.788
}
else
{
    // invalid input
}


问:
Unable to listObjects from GCS bucket
I am trying to listObjects from GCS bucket using latest aws-sdk java library.

Refer code snippet here

```<code>ClientConfiguration clientConfiguration = new ClientConfiguration();
  // Solution is update the Signer Version.
  clientConfiguration.setSignerOverride("S3SignerType");

  AWSCredentials awsCredentials = new BasicAWSCredentials("XXX","XXX");
  AmazonS3 amazonS3Client = AmazonS3ClientBuilder.standard()
    .withCredentials(new  AWSStaticCredentialsProvider(awsCredentials))
    .withClientConfiguration(clientConfiguration)
    .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration("https://storage.googleapis.com","Multi-Regional")).build();

  String bucketName = "bucket_name";

  // List Objects
  amazonS3Client.listObject(bucketName);
</code>```

But receiving invalid arguments.Refer Error and DEBUG logs
Also I am able to do with getObjects and putObjects with above amazonS3Client.
Any ideas?

```<code>2017-11-13 17:54:15,360 [main] DEBUG com.amazonaws.request - Sending Request: GET https://bucket_name.storage.googleapis.com / Parameters: ({"encoding-type":["url"]}Headers: (User-Agent: aws-sdk-java/1.11.158 Linux/4.10.0-38-generic Java_HotSpot(TM)_64-Bit_Server_VM/25.131-b11/1.8.0_131, amz-sdk-invocation-id: 121cd76e-1374-4e5d-9e68-be22ee2ad17a, Content-Type: application/octet-stream, )
2017-11-13 17:54:16,316 [main] DEBUG com.amazonaws.request - Received error response: com.amazonaws.services.s3.model.AmazonS3Exception: Invalid argument. (Service: Amazon S3; Status Code: 400; Error Code: InvalidArgument; Request ID: null), S3 Extended Request ID: null
Exception in thread "main" com.amazonaws.services.s3.model.AmazonS3Exception: Invalid argument. (Service: Amazon S3; Status Code: 400; Error Code: InvalidArgument; Request ID: null), S3 Extended Request ID: null
        at com.amazonaws.http.AmazonHttpClient$RequestExecutor.handleErrorResponse(AmazonHttpClient.java:1588)
        at
</code>```

答:
S3 has a parameter to its object list call called "encodingtype" that, when set to "url", encodes characters that can't be rendered natively in XML 1.0 using URL encoding. The client library appears to be using that flag. I don't believe that GCS's XML API supports that parameter, and so the call will fail with an InvalidArgument error.

You can probably avoid this by using a ListObjectRequest and calling setEncodingType(null), although I haven't tried.

Title: Unable to listObjects from GCS bucket

Body:
I am trying to listObjects from GCS bucket using latest aws-sdk java library.

Refer code snippet here

ClientConfiguration clientConfiguration = new ClientConfiguration();
  // Solution is update the Signer Version.
  clientConfiguration.setSignerOverride("S3SignerType");

  AWSCredentials awsCredentials = new BasicAWSCredentials("XXX","XXX");
  AmazonS3 amazonS3Client = AmazonS3ClientBuilder.standard()
    .withCredentials(new  AWSStaticCredentialsProvider(awsCredentials))
    .withClientConfiguration(clientConfiguration)
    .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration("https://storage.googleapis.com","Multi-Regional")).build();

  String bucketName = "bucket_name";

  // List Objects
  amazonS3Client.listObject(bucketName);

But receiving invalid arguments.Refer Error and DEBUG logs
Also I am able to do with getObjects and putObjects with above amazonS3Client.
Any ideas?

2017-11-13 17:54:15,360 [main] DEBUG com.amazonaws.request - Sending Request: GET https://bucket_name.storage.googleapis.com / Parameters: ({"encoding-type":["url"]}Headers: (User-Agent: aws-sdk-java/1.11.158 Linux/4.10.0-38-generic Java_HotSpot(TM)_64-Bit_Server_VM/25.131-b11/1.8.0_131, amz-sdk-invocation-id: 121cd76e-1374-4e5d-9e68-be22ee2ad17a, Content-Type: application/octet-stream, )
2017-11-13 17:54:16,316 [main] DEBUG com.amazonaws.request - Received error response: com.amazonaws.services.s3.model.AmazonS3Exception: Invalid argument. (Service: Amazon S3; Status Code: 400; Error Code: InvalidArgument; Request ID: null), S3 Extended Request ID: null
Exception in thread "main" com.amazonaws.services.s3.model.AmazonS3Exception: Invalid argument. (Service: Amazon S3; Status Code: 400; Error Code: InvalidArgument; Request ID: null), S3 Extended Request ID: null
        at com.amazonaws.http.AmazonHttpClient$RequestExecutor.handleErrorResponse(AmazonHttpClient.java:1588)
        at


问:
How to remove beginning-digits only in R
I have some strings with digits and alpha characters in them. Some of the digits are important, but the ones at the beginning of the string (and only these) are unimportant. This is due to a peculiarity in how email addresses are stored. So the best example is:

x<-'12345johndoe23@gmail.com'
Should be transformed to johndoe23@gmail.com

unfortunately there are no spaces. I have tried gsub('[[:digit:]]+', '', x) but this removes all numbers, not just the beginning-ones

Edit: I have found some solutions in other languages: Python: Remove numbers at the beginning of a string

答:
You can do this:</p>

```<code>x<-'12345johndoe23@gmail.com'
gsub('^[[:digit:]]+', '', x) #added ^ as begin of string
</code>```

Body:
You can do this:

x<-'12345johndoe23@gmail.com'
gsub('^[[:digit:]]+', '', x) #added ^ as begin of string


问:
Randomly select unique row from dataframe in Pandas
Say I have a dataframe of the form where rn is the row index

```<code>       A1  |  A2 |  A3
      -----------------
r1     x   |  0  |  t
r2     y   |  1  |  u
r3     z   |  1  |  v
r4     x   |  2  |  w
r5     z   |  2  |  v
r6     x   |  2  |  w
</code>```

If I wanted to subset this dataframe such that the column A2 has only unique values, I'd use df.drop_duplicates('A2'). However, that'd keep only the first row of the unique value and delete the rest. For this example, only r2 and r4 will be in the subset.

What I want is that any of the rows with duplicate values are selected randomly rather than the first row. So for this example, for A2 == 1, r2 or r3 is selected randomly or for A2 == 2 any of r4, r5 or r6 is selected randomly. How would I go about implementing this?

答:
Shuffle the DataFrame first and then drop the duplicates:

```<code>df.sample(frac=1).drop_duplicates(subset='A2')
</code>```

If the order of the rows is important you can use sort_index as @cᴏʟᴅsᴘᴇᴇᴅ suggested:

```<code>df.sample(frac=1).drop_duplicates(subset='A2').sort_index()
</code>```

Body:
Say I have a dataframe of the form where rn is the row index

       A1  |  A2 |  A3
      -----------------
r1     x   |  0  |  t
r2     y   |  1  |  u
r3     z   |  1  |  v
r4     x   |  2  |  w
r5     z   |  2  |  v
r6     x   |  2  |  w

If I wanted to subset this dataframe such that the column A2 has only unique values, I'd use df.drop_duplicates('A2'). However, that'd keep only the first row of the unique value and delete the rest. For this example, only r2 and r4 will be in the subset.

What I want is that any of the rows with duplicate values are selected randomly rather than the first row. So for this example, for A2 == 1, r2 or r3 is selected randomly or for A2 == 2 any of r4, r5 or r6 is selected randomly. How would I go about implementing this?

Body:
Shuffle the DataFrame first and then drop the duplicates:

df.sample(frac=1).drop_duplicates(subset='A2')

If the order of the rows is important you can use sort_index as @cᴏʟᴅsᴘᴇᴇᴅ suggested:

df.sample(frac=1).drop_duplicates(subset='A2').sort_index()


问:
Google BigQuery: Table join with REPEATED RECORD values
I have a table like this:

```<code>Row field1  field2  field3.a    field3.b
1   value1  1       id1         key5
                    id2         key6
2   value2  2       id3         key7
                    id4         key8
</code>```

The first 2 columns are standard fields, the third column is a REPEATED RECORD field.

I have 2 additional tables

```<code>Row  id     value
1    id1    my-valueA
2    id2    my-valueB
3    id3    my-valueC
4    id4    my-valueD
</code>```

and

```<code>Row id      value
1   key5    my-valueE
2   key6    my-valueF
3   key7    my-valueG
4   key8    my-valueH
</code>```

Which map the a id/key from the first table (I used the term key and id to avoid confusion, but at the end the concept is the same) with a given value

Here is a full statement to reproduce the structure

```<code>#standardSQL
WITH my_table AS (
  SELECT "value1" as field1, 1 as field2, [STRUCT("id1" as a, "key5" as b),STRUCT("id2" as a, "key6" as b)] as field3
  UNION ALL
  SELECT "value2" as field2, 2 as field2, [STRUCT("id3" as a, "key7" as b),STRUCT("id4" as a, "key8" as b)] as field3
),

ids_table AS (
  SELECT "id1" as id, "my-valueA" as value
  UNION ALL
  SELECT "id2" as id, "my-valueB" as value
  UNION ALL
  SELECT "id3" as id, "my-valueC" as value
  UNION ALL
  SELECT "id4" as id, "my-valueD" as value
),

keys_table AS (
  SELECT "key5" as id, "my-valueE" as value
  UNION ALL
  SELECT "key6" as id, "my-valueF" as value
  UNION ALL
  SELECT "key7" as id, "my-valueG" as value
  UNION ALL
  SELECT "key8" as id, "my-valueH" as value
)

-- SELECT * FROM my_table
-- SELECT * FROM ids_table
-- SELECT * FROM keys_table
</code>```

My goal is to replace the key/id values from the first tables with the value given by the 2 other tables, like a classic join on id.

Here is the expected output

```<code>Row field1  field2  t2_value    t3_value
1   value1  1       my-valueA   my-valueE
                    my-valueB   my-valueF
2   value2  2       my-valueC   my-valueG
                    my-valueD   my-valueH
</code>```

At first I thought about using UNNEST operator to obtain flat lines, so a simple JOIN can be made to resolve the value and after that rejoin the array with the replaced values.

```<code>SELECT my_table.* EXCEPT(field3),
  t2.value as t2_value,
  t3.value as t3_value
FROM my_table CROSS JOIN UNNEST(my_table.field3) AS t1
  LEFT JOIN ids_table AS t2 ON t1.a = t2.id
  LEFT JOIN keys_table as t3 ON t1.b = t3.id
</code>```

With this statement the values are properly replace from the id to the value, but now I'm unable to reproduce the RECORD REPEATED structure of before

答:
Below is for BigQuery Standard SQL   </p>

<pre class="lang-sql prettyprint-override"><code>#standardSQL
WITH my_table AS (
  SELECT "value1" AS field1, 1 AS field2, [STRUCT("id1" AS a, "key5" AS b),STRUCT("id2" AS a, "key6" AS b)] AS field3 UNION ALL
  SELECT "value2" AS field2, 2 AS field2, [STRUCT("id3" AS a, "key7" AS b),STRUCT("id4" AS a, "key8" AS b)] AS field3
), ids_table AS (
  SELECT "id1" AS id, "my-valueA" AS value UNION ALL
  SELECT "id2" AS id, "my-valueB" AS value UNION ALL
  SELECT "id3" AS id, "my-valueC" AS value UNION ALL
  SELECT "id4" AS id, "my-valueD" AS value
),keys_table AS (
  SELECT "key5" AS id, "my-valueE" AS value UNION ALL
  SELECT "key6" AS id, "my-valueF" AS value UNION ALL
  SELECT "key7" AS id, "my-valueG" AS value UNION ALL
  SELECT "key8" AS id, "my-valueH" AS value
)
SELECT
  field1, field2,
  (
    SELECT ARRAY_AGG(STRUCT<a_value STRING, b_value STRING>(t2.value, t3.value))
    FROM UNNEST(field3) t1
      LEFT JOIN ids_table AS t2 ON t1.a = t2.id
      LEFT JOIN keys_table AS t3 ON t1.b = t3.id
  ) AS field3
FROM my_table
</code>```

<p>with below output    </p>

<pre class="lang-sql prettyprint-override"><code>field1  field2  field3.a_value  field3.b_value
value1  1       my-valueA       my-valueE
                my-valueB       my-valueF
value2  2       my-valueC       my-valueG
                my-valueD       my-valueH
</code>```

Body:
I have a table like this:

Row field1  field2  field3.a    field3.b
1   value1  1       id1         key5
                    id2         key6
2   value2  2       id3         key7
                    id4         key8

The first 2 columns are standard fields, the third column is a REPEATED RECORD field.

I have 2 additional tables

Row  id     value
1    id1    my-valueA
2    id2    my-valueB
3    id3    my-valueC
4    id4    my-valueD

and

Row id      value
1   key5    my-valueE
2   key6    my-valueF
3   key7    my-valueG
4   key8    my-valueH

Which map the a id/key from the first table (I used the term key and id to avoid confusion, but at the end the concept is the same) with a given value

Here is a full statement to reproduce the structure

#standardSQL
WITH my_table AS (
  SELECT "value1" as field1, 1 as field2, [STRUCT("id1" as a, "key5" as b),STRUCT("id2" as a, "key6" as b)] as field3
  UNION ALL
  SELECT "value2" as field2, 2 as field2, [STRUCT("id3" as a, "key7" as b),STRUCT("id4" as a, "key8" as b)] as field3
),

ids_table AS (
  SELECT "id1" as id, "my-valueA" as value
  UNION ALL
  SELECT "id2" as id, "my-valueB" as value
  UNION ALL
  SELECT "id3" as id, "my-valueC" as value
  UNION ALL
  SELECT "id4" as id, "my-valueD" as value
),

keys_table AS (
  SELECT "key5" as id, "my-valueE" as value
  UNION ALL
  SELECT "key6" as id, "my-valueF" as value
  UNION ALL
  SELECT "key7" as id, "my-valueG" as value
  UNION ALL
  SELECT "key8" as id, "my-valueH" as value
)

-- SELECT * FROM my_table
-- SELECT * FROM ids_table
-- SELECT * FROM keys_table

My goal is to replace the key/id values from the first tables with the value given by the 2 other tables, like a classic join on id.

Here is the expected output

Row field1  field2  t2_value    t3_value
1   value1  1       my-valueA   my-valueE
                    my-valueB   my-valueF
2   value2  2       my-valueC   my-valueG
                    my-valueD   my-valueH

At first I thought about using UNNEST operator to obtain flat lines, so a simple JOIN can be made to resolve the value and after that rejoin the array with the replaced values.

SELECT my_table.* EXCEPT(field3),
  t2.value as t2_value,
  t3.value as t3_value
FROM my_table CROSS JOIN UNNEST(my_table.field3) AS t1
  LEFT JOIN ids_table AS t2 ON t1.a = t2.id
  LEFT JOIN keys_table as t3 ON t1.b = t3.id

With this statement the values are properly replace from the id to the value, but now I'm unable to reproduce the RECORD REPEATED structure of before

Body:
Below is for BigQuery Standard SQL

#standardSQL
WITH my_table AS (
  SELECT "value1" AS field1, 1 AS field2, [STRUCT("id1" AS a, "key5" AS b),STRUCT("id2" AS a, "key6" AS b)] AS field3 UNION ALL
  SELECT "value2" AS field2, 2 AS field2, [STRUCT("id3" AS a, "key7" AS b),STRUCT("id4" AS a, "key8" AS b)] AS field3
), ids_table AS (
  SELECT "id1" AS id, "my-valueA" AS value UNION ALL
  SELECT "id2" AS id, "my-valueB" AS value UNION ALL
  SELECT "id3" AS id, "my-valueC" AS value UNION ALL
  SELECT "id4" AS id, "my-valueD" AS value
),keys_table AS (
  SELECT "key5" AS id, "my-valueE" AS value UNION ALL
  SELECT "key6" AS id, "my-valueF" AS value UNION ALL
  SELECT "key7" AS id, "my-valueG" AS value UNION ALL
  SELECT "key8" AS id, "my-valueH" AS value
)
SELECT
  field1, field2,
  (
    SELECT ARRAY_AGG(STRUCT<a_value STRING, b_value STRING>(t2.value, t3.value))
    FROM UNNEST(field3) t1
      LEFT JOIN ids_table AS t2 ON t1.a = t2.id
      LEFT JOIN keys_table AS t3 ON t1.b = t3.id
  ) AS field3
FROM my_table

with below output

field1  field2  field3.a_value  field3.b_value
value1  1       my-valueA       my-valueE
                my-valueB       my-valueF
value2  2       my-valueC       my-valueG
                my-valueD       my-valueH


答:
Not sure how that library formats colour, but normally it is in rounded brackets (255,36,239) which is probably the error about the tuple. Secondly, do not use an equals (=) when defining parameters.
This:

```<code>color = [255,0,0]
</code>```

Should be changed to:

```<code>colour = (255,0,0)
, color, thickness..
</code>```

Also change thickness in the same way.

Title: Where is the error? "SystemError: new style getargs format but argument is not a tuple"

Body:
I am doing an image processing Lane Detection project. Im getting this error within my code. Im hoping someone can help me figure out how to fix this error.

Here is the function:

def draw_lane_lines(image, lines, color = [255,0,0], thickness=20):
  line_image=np.zeros_like(image)
  for line in lines:
    if line is not None:
    cv2.line(*(line_image, [line], color, thickness))

The name of the error is: SystemError: new style getargs format but argument is not a tuple.

The error seems to be in the last line of the code.

Body:
Not sure how that library formats colour, but normally it is in rounded brackets (255,36,239) which is probably the error about the tuple. Secondly, do not use an equals (=) when defining parameters.
This:

color = [255,0,0]

Should be changed to:

colour = (255,0,0)
, color, thickness..

Also change thickness in the same way.


问:
Filter Not Filtering Records
I'm trying to find records in $scope.employeesthat do not have a matching record in $scope.allEmployeeGroups, but the filter is not Filtering records, even though I know for sure that there should only be a few unmatched, it returns all of the records.  For each record, the indexOf == -1 when I know that it should not.  I can't figure out what I am doing wrong.  Here is my code:

```<code>    function getNonGroupEmployees() {
    var arr = $scope.employees.filter(function (item) {
        return $scope.allEmployeeGroups.indexOf(item.EmployeeId) === -1;
    })
    return arr;
}
</code>```

Employee Object:

```<code>public System.Guid EmployeeId { get; set; }
    public Nullable<System.Guid> SiteId { get; set; }
    public string SiteName { get; set; }
    public string DisplayName { get; set; }
    public string FirstName { get; set; }
    public string MiddleName { get; set; }
    public string LastName { get; set; }
    public string Suffix { get; set; }
    public string Alias { get; set; }
    public Nullable<System.DateTime> DOB { get; set; }
    public string SsnLastFour { get; set; }
    public string Email { get; set; }
    public string UserName { get; set; }
    public string Password { get; set; }
    public bool IsActive { get; set; }
    public bool IsLoginEnabled { get; set; }
    public Nullable<System.DateTime> LastLogin { get; set; }
    public Nullable<System.Guid> SignatureTypeId { get; set; }
    public string SignatureType { get; set; }
    public string NumberHome { get; set; }
    public string NumberCell { get; set; }
    public bool IsSuperUser { get; set; }
    public bool IsDeleted { get; set; }
    public System.DateTime Created { get; set; }
    public System.DateTime LastModified { get; set; }
    public Nullable<System.Guid> ModifiedByEmployeeId { get; set; }
    public string ApiKey { get; set; }
</code>```

Group Object:

```<code>            public Guid EmployeeGroupId { get; set; }
        public Guid SiteId { get; set; }
        public Guid EmployeeId { get; set; }
        public Guid SiteGroupId { get; set; }
        public bool IsDeleted { get; set; }
        public DateTime Created { get; set; }
        public DateTime LastModified { get; set; }
        public Guid? ModifiedByEmployeeId { get; set; }
        public string SiteName { get; set; }
        public string EmployeeName { get; set; }
        public string SiteGroupName { get; set; }
        public string ModifiedByEmployeeName { get; set; }
</code>```

Any assistance is greatly appreciated.

答:
Thanks to answer found Here, here is what eventually worked:</p>

```<code>    function getNonGroupEmployees() {
    var result = $scope.employees.filter(function (o1) {
        return !$scope.allEmployeeGroups.some(function (o2) {
            return o1.EmployeeId === o2.EmployeeId;          // assumes unique id
        });
    })
    return result;
}
</code>```

Title: Filter Not Filtering Records

Body:
I'm trying to find records in $scope.employeesthat do not have a matching record in $scope.allEmployeeGroups, but the filter is not Filtering records, even though I know for sure that there should only be a few unmatched, it returns all of the records.  For each record, the indexOf == -1 when I know that it should not.  I can't figure out what I am doing wrong.  Here is my code:

    function getNonGroupEmployees() {
    var arr = $scope.employees.filter(function (item) {
        return $scope.allEmployeeGroups.indexOf(item.EmployeeId) === -1;
    })
    return arr;
}

Employee Object:

public System.Guid EmployeeId { get; set; }
    public Nullable<System.Guid> SiteId { get; set; }
    public string SiteName { get; set; }
    public string DisplayName { get; set; }
    public string FirstName { get; set; }
    public string MiddleName { get; set; }
    public string LastName { get; set; }
    public string Suffix { get; set; }
    public string Alias { get; set; }
    public Nullable<System.DateTime> DOB { get; set; }
    public string SsnLastFour { get; set; }
    public string Email { get; set; }
    public string UserName { get; set; }
    public string Password { get; set; }
    public bool IsActive { get; set; }
    public bool IsLoginEnabled { get; set; }
    public Nullable<System.DateTime> LastLogin { get; set; }
    public Nullable<System.Guid> SignatureTypeId { get; set; }
    public string SignatureType { get; set; }
    public string NumberHome { get; set; }
    public string NumberCell { get; set; }
    public bool IsSuperUser { get; set; }
    public bool IsDeleted { get; set; }
    public System.DateTime Created { get; set; }
    public System.DateTime LastModified { get; set; }
    public Nullable<System.Guid> ModifiedByEmployeeId { get; set; }
    public string ApiKey { get; set; }

Group Object:

            public Guid EmployeeGroupId { get; set; }
        public Guid SiteId { get; set; }
        public Guid EmployeeId { get; set; }
        public Guid SiteGroupId { get; set; }
        public bool IsDeleted { get; set; }
        public DateTime Created { get; set; }
        public DateTime LastModified { get; set; }
        public Guid? ModifiedByEmployeeId { get; set; }
        public string SiteName { get; set; }
        public string EmployeeName { get; set; }
        public string SiteGroupName { get; set; }
        public string ModifiedByEmployeeName { get; set; }

Any assistance is greatly appreciated.

Body:
Thanks to answer found Here, here is what eventually worked:

    function getNonGroupEmployees() {
    var result = $scope.employees.filter(function (o1) {
        return !$scope.allEmployeeGroups.some(function (o2) {
            return o1.EmployeeId === o2.EmployeeId;          // assumes unique id
        });
    })
    return result;
}


问:
I do not have PATH_INFO in $ _SERVER
I use WampServer Version 2.2 on Windows 7, Apache version 2.2.22 and PHP version 5.3.13.

I try to use $this->url = $_SERVER['PATH_INFO']; in the Request file,
I received this error:

Notice: Undefined index: PATH_INFO in C:\wamp\www\site\core\Request.php on line 8

I tried to configure the httpd.conf file to add AcceptPathInfo On
For PHP in php.ini so I added cgi.fix_pathinfo = 1 but this did not fix the problem.

How can I fix this?

答:
You can use this instead of $_SERVER['PATH_INFO'] (it's work for me)

$_SERVER['PATH_INFO'] is original version of 'PATH_INFO' before processed by PHP.

```<code>$_SERVER['ORIG_PATH_INFO']
</code>```

OR:

```<code>$Path_Info = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : (isset($_SERVER['ORIG_PATH_INFO']) ? $_SERVER['ORIG_PATH_INFO'] : '');
</code>```

Title: I do not have PATH_INFO in $ _SERVER

Body:
You can use this instead of $_SERVER['PATH_INFO'] (it's work for me)

$_SERVER['PATH_INFO'] is original version of 'PATH_INFO' before processed by PHP.

$_SERVER['ORIG_PATH_INFO']

OR:

$Path_Info = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : (isset($_SERVER['ORIG_PATH_INFO']) ? $_SERVER['ORIG_PATH_INFO'] : '');


问:
How can I assign a Task to a Guest user?
I am attempting to assign a Task using the Podio API to a guest user.
I can do this easily through the Podio Web Interface (I do it all the time) but why can't I do this with the API?
Here is my basic code:

```<code>$resp_profiles[] = array(
  'type' => 'profile',
  'id' => 4346424);

 PodioTask::create(array(
    'text' => $subTitle,
    'description' => $subTitle,
    'private' => false,
    'due_on' => $task_due_date->format('Y-m-d H:i:s'),
    'responsible' => $resp_profiles,
  ));
</code>```

Here is the error I get:

```<code>Fatal error: Uncaught PodioForbiddenError:
"Must be at least light on user 4346424 to perform this operation"
Request URL: http://api.podio.com/task/
Stack Trace:
#0 /home/avcorp/vhosts/pubvps/vendor/podio/podio-php/lib/Podio.php(352): Podio::request('POST', '/task/', Array, Array)
#1 /home/avcorp/vhosts/pubvps/vendor/podio/podio-php/models/PodioTask.php(78): Podio::post('/task/', Array)
#2 /home/avcorp/vhosts/pubvps/podio_rmticket/rmticket_util.php(309): PodioTask::create(Array)
#3 /home/avcorp/vhosts/pubvps/podio_rmticket/rmticket_util.php(152): rmtCreateTask(Object(AvcPodioItem), 'Carpet Cleaning', 10, 3)
#4 /home/avcorp/vhosts/pubvps/podio_rmticket/poll/rmticket_poll.php(54): test_task_creation()
#5 {main} thrown in /home/avcorp/vhosts/pubvps/vendor/podio/podio-php/lib/Podio.php on line 319
</code>```

答:
From Podio help page: https://help.podio.com/hc/en-us/articles/201019898-Member-roles-in-workspaces

Guests are users that have been invited to selected items using the
  share item tool. They can edit and comment these specific items, but
  cannot see anything else within the workspace, such as the full list
  of members, other information in the app, or other apps in the same
  workspace.

Have you tried changing role to 'Light' ?
That will also explain error message: Must be at least light on user 4346424 to perform this operation

You cannot assign a task to guest user profile even from frontend. It might be a bit confusing because you can assign task to user using mail user identifier, but that is restricted to Podio highly trusted partners only.

Body:
I am attempting to assign a Task using the Podio API to a guest user.
I can do this easily through the Podio Web Interface (I do it all the time) but why can't I do this with the API?
Here is my basic code:

$resp_profiles[] = array(
  'type' => 'profile',
  'id' => 4346424);

 PodioTask::create(array(
    'text' => $subTitle,
    'description' => $subTitle,
    'private' => false,
    'due_on' => $task_due_date->format('Y-m-d H:i:s'),
    'responsible' => $resp_profiles,
  ));

Here is the error I get:

Fatal error: Uncaught PodioForbiddenError:
"Must be at least light on user 4346424 to perform this operation"
Request URL: http://api.podio.com/task/
Stack Trace:
#0 /home/avcorp/vhosts/pubvps/vendor/podio/podio-php/lib/Podio.php(352): Podio::request('POST', '/task/', Array, Array)
#1 /home/avcorp/vhosts/pubvps/vendor/podio/podio-php/models/PodioTask.php(78): Podio::post('/task/', Array)
#2 /home/avcorp/vhosts/pubvps/podio_rmticket/rmticket_util.php(309): PodioTask::create(Array)
#3 /home/avcorp/vhosts/pubvps/podio_rmticket/rmticket_util.php(152): rmtCreateTask(Object(AvcPodioItem), 'Carpet Cleaning', 10, 3)
#4 /home/avcorp/vhosts/pubvps/podio_rmticket/poll/rmticket_poll.php(54): test_task_creation()
#5 {main} thrown in /home/avcorp/vhosts/pubvps/vendor/podio/podio-php/lib/Podio.php on line 319


问:
SSIS transformation (almost like a pivot)
I have the following data coming in to SSIS

```<code>Set   Value
---   -------
1     One
1     Two
1     Three
2     Four
2     Five
2     Six
</code>```

I want to transform it to read

```<code>Set   ValueList
---   -------
1     One, Two, Three
2     Four, Five, Six
</code>```

How do I do this in SSIS?

答:
There is a pivot task in the data flow transformations. You could try it, but I'll warn you that we have been less than hapy with it's implementation.

Alternatively, you could use the dataflow to put the data into a staging table, and pivot using SQL or do the pivot in the SQL you use to create the incoming data source. If you want to do it in SQl code, this might help:

```<code>select 1 as Item
into #test
union select 2
union select 3
union select 4
union select 5

select STUFF((SELECT  ', ' + cast(Item as nvarchar)
        FROM #test
        FOR XML PATH('')), 1, 1, '')
</code>```

Body:
I have the following data coming in to SSIS

Set   Value
---   -------
1     One
1     Two
1     Three
2     Four
2     Five
2     Six

I want to transform it to read

Set   ValueList
---   -------
1     One, Two, Three
2     Four, Five, Six

How do I do this in SSIS?

Body:
There is a pivot task in the data flow transformations. You could try it, but I'll warn you that we have been less than hapy with it's implementation.

Alternatively, you could use the dataflow to put the data into a staging table, and pivot using SQL or do the pivot in the SQL you use to create the incoming data source. If you want to do it in SQl code, this might help:

select 1 as Item
into #test
union select 2
union select 3
union select 4
union select 5

select STUFF((SELECT  ', ' + cast(Item as nvarchar)
        FROM #test
        FOR XML PATH('')), 1, 1, '')