问:
perl extract values from a http request
I have a perl rest API. When http request receives to my program I want to extract values in above mentioned request.

I used following code to take a dump

```<code>warn "\n\n  request : " . MyCT::Util::dumper($self->resp);
</code>```

Following result could find in the log file.
How can I extract "standalone" from this result?

```<code>Tue Feb 18 05:20:26 2020] [warn] [21783] [MyCT]

request : $VAR1 = bless( {
  'outputSent' => 0,
  'headersSent' => 0,
  'autoFlush' => 0,
  'req' => bless( do{\(my $o = 196025568)}, 'MyCT::Base::Request' ),
  '_cookies' => {
    'sessionKey' => '1762839:c480474dd4f4623035e8f35b445e1aad:c9920499157cf9c2a7972f773d08b972:standalone'
  },
  'contents' => [],
  'active' => 1
}, 'MyCT::Base::Response' );
</code>```

答:
One normally doesn't access an object variable directly, instead using the provided accessors provided by the object's class.

Seeing as you didn't provide information about the class, we are left with only the fragile, error-prone alternative.

```<code>my $session_key = $self->resp->{_cookies}{sessionKey};
</code>```

One you have the session key, it's just a question of splitting on : and getting the fourth field.

```<code>( split(/:/, $sesion_key) )[3]
</code>```

Title: perl extract values from a http request

Body:
I have a perl rest API. When http request receives to my program I want to extract values in above mentioned request.

I used following code to take a dump

warn "\n\n  request : " . MyCT::Util::dumper($self->resp);

Following result could find in the log file.
How can I extract "standalone" from this result?

Tue Feb 18 05:20:26 2020] [warn] [21783] [MyCT]

request : $VAR1 = bless( {
  'outputSent' => 0,
  'headersSent' => 0,
  'autoFlush' => 0,
  'req' => bless( do{\(my $o = 196025568)}, 'MyCT::Base::Request' ),
  '_cookies' => {
    'sessionKey' => '1762839:c480474dd4f4623035e8f35b445e1aad:c9920499157cf9c2a7972f773d08b972:standalone'
  },
  'contents' => [],
  'active' => 1
}, 'MyCT::Base::Response' );

Body:
One normally doesn't access an object variable directly, instead using the provided accessors provided by the object's class.

Seeing as you didn't provide information about the class, we are left with only the fragile, error-prone alternative.

my $session_key = $self->resp->{_cookies}{sessionKey};

One you have the session key, it's just a question of splitting on : and getting the fourth field.

( split(/:/, $sesion_key) )[3]


来源: stackexchange

问:
Spring boot cannot start with aws starter dependency
I have checked on other posts but version seems to play a role and my spring boot version is

```<code>'2.1.8.RELEASE'
</code>```

Spring boot does not start with the dependency
I have tried several options to get the application to start but get no success.
I only want to make use of S3 and RDS and maybe EC2.

Any help is much appreciated. Thanks.

```<code>implementation 'org.springframework.cloud:spring-cloud-starter-aws'
</code>```

and the configuration of

```<code>cloud.aws.region.static=us-east-1
cloud.aws.credentials.accessKey=key
cloud.aws.credentials.secretKey=secret

cloud.aws.region.auto=true

# Disable auto cloud formation
cloud.aws.stack.auto=false
</code>```

Keep getting the error:

```<code>2019-09-20 01:25:24.740  WARN 18552 --- [  restartedMain] s.c.a.AnnotationConfigApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.cloud.aws.core.env.ResourceIdResolver.BEAN_NAME': Invocation of init method failed; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'stackResourceRegistryFactoryBean' defined in class path resource [org/springframework/cloud/aws/autoconfigure/context/ContextStackAutoConfiguration.class]: Unsatisfied dependency expressed through method 'stackResourceRegistryFactoryBean' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'amazonCloudFormation' defined in class path resource [org/springframework/cloud/aws/autoconfigure/context/ContextStackAutoConfiguration.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: There is no EC2 meta data available, because the application is not running in the EC2 environment. Region detection is only possible if the application is running on a EC2 instance
2019-09-20 01:25:24.750  INFO 18552 --- [  restartedMain] ConditionEvaluationReportLoggingListener :

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2019-09-20 01:25:24.764 ERROR 18552 --- [  restartedMain] o.s.boot.SpringApplication               : Application run failed

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.cloud.aws.core.env.ResourceIdResolver.BEAN_NAME': Invocation of init method failed; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'stackResourceRegistryFactoryBean' defined in class path resource [org/springframework/cloud/aws/autoconfigure/context/ContextStackAutoConfiguration.class]: Unsatisfied dependency expressed through method 'stackResourceRegistryFactoryBean' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'amazonCloudFormation' defined in class path resource [org/springframework/cloud/aws/autoconfigure/context/ContextStackAutoConfiguration.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: There is no EC2 meta data available, because the application is not running in the EC2 environment. Region detection is only possible if the application is running on a EC2 instance
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1778) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:593) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:845) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:877) ~[spring-context-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549) ~[spring-context-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:744) ~[spring-boot-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:391) ~[spring-boot-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:312) ~[spring-boot-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1215) ~[spring-boot-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1204) ~[spring-boot-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at com.example.demo.DemoApplication.main(DemoApplication.java:15) ~[main/:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
    at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
    at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) ~[spring-boot-devtools-2.1.8.RELEASE.jar:2.1.8.RELEASE]
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'stackResourceRegistryFactoryBean' defined in class path resource [org/springframework/cloud/aws/autoconfigure/context/ContextStackAutoConfiguration.class]: Unsatisfied dependency expressed through method 'stackResourceRegistryFactoryBean' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'amazonCloudFormation' defined in class path resource [org/springframework/cloud/aws/autoconfigure/context/ContextStackAutoConfiguration.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: There is no EC2 meta data available, because the application is not running in the EC2 environment. Region detection is only possible if the application is running on a EC2 instance
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:769) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE]
</code>```

答:
You have set the cloud.aws.region.auto=true parameter which enables the automatic region detection

There is no EC2 meta data available, because the application is not
  running in the EC2 environment. Region detection is only possible if
  the application is running on a EC2 instance

See cloud aws documentation here

Set it to false or remove it to avoid getting that error.

If you want to simulate the aws environment locally, the localstack project could be useful

https://github.com/localstack/localstack

ContentLicense: CC BY-SA 4.0

Body:
I have checked on other posts but version seems to play a role and my spring boot version is

'2.1.8.RELEASE'

Spring boot does not start with the dependency
I have tried several options to get the application to start but get no success.
I only want to make use of S3 and RDS and maybe EC2.

Any help is much appreciated. Thanks.

implementation 'org.springframework.cloud:spring-cloud-starter-aws'

and the configuration of

cloud.aws.region.static=us-east-1
cloud.aws.credentials.accessKey=key
cloud.aws.credentials.secretKey=secret

cloud.aws.region.auto=true

# Disable auto cloud formation
cloud.aws.stack.auto=false

Keep getting the error:

2019-09-20 01:25:24.740  WARN 18552 --- [  restartedMain] s.c.a.AnnotationConfigApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.cloud.aws.core.env.ResourceIdResolver.BEAN_NAME': Invocation of init method failed; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'stackResourceRegistryFactoryBean' defined in class path resource [org/springframework/cloud/aws/autoconfigure/context/ContextStackAutoConfiguration.class]: Unsatisfied dependency expressed through method 'stackResourceRegistryFactoryBean' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'amazonCloudFormation' defined in class path resource [org/springframework/cloud/aws/autoconfigure/context/ContextStackAutoConfiguration.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: There is no EC2 meta data available, because the application is not running in the EC2 environment. Region detection is only possible if the application is running on a EC2 instance
2019-09-20 01:25:24.750  INFO 18552 --- [  restartedMain] ConditionEvaluationReportLoggingListener :

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2019-09-20 01:25:24.764 ERROR 18552 --- [  restartedMain] o.s.boot.SpringApplication               : Application run failed

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.cloud.aws.core.env.ResourceIdResolver.BEAN_NAME': Invocation of init method failed; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'stackResourceRegistryFactoryBean' defined in class path resource [org/springframework/cloud/aws/autoconfigure/context/ContextStackAutoConfiguration.class]: Unsatisfied dependency expressed through method 'stackResourceRegistryFactoryBean' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'amazonCloudFormation' defined in class path resource [org/springframework/cloud/aws/autoconfigure/context/ContextStackAutoConfiguration.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: There is no EC2 meta data available, because the application is not running in the EC2 environment. Region detection is only possible if the application is running on a EC2 instance
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1778) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:593) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:845) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:877) ~[spring-context-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549) ~[spring-context-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:744) ~[spring-boot-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:391) ~[spring-boot-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:312) ~[spring-boot-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1215) ~[spring-boot-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1204) ~[spring-boot-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at com.example.demo.DemoApplication.main(DemoApplication.java:15) ~[main/:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
    at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
    at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) ~[spring-boot-devtools-2.1.8.RELEASE.jar:2.1.8.RELEASE]
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'stackResourceRegistryFactoryBean' defined in class path resource [org/springframework/cloud/aws/autoconfigure/context/ContextStackAutoConfiguration.class]: Unsatisfied dependency expressed through method 'stackResourceRegistryFactoryBean' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'amazonCloudFormation' defined in class path resource [org/springframework/cloud/aws/autoconfigure/context/ContextStackAutoConfiguration.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: There is no EC2 meta data available, because the application is not running in the EC2 environment. Region detection is only possible if the application is running on a EC2 instance
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:769) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE]


问:
Switching to an iframe on android native and web app using appium via ROBOT framework
Hi I have been searching a lot on the internet to find how i am supposed to switch from web or native context view to an iframe. I am trying to automate a user logging into an app and the third piece of identification is generating a OTP. This happens to be inside an iframe and i have tried quite a few things to interact with it. Firstly I cannot find any good documentation on how to achieve this through keywords (Appium) using robot, and i do not have a lot of programming experience to write it in python then call it but i have tried.

First thing i tried was using the keyword 'switch to context' and 'get contexts' which i am already using to switch between native and webview already:

```<code>List Contexts
${contexts}=                              Get Contexts
${native}=                                Get From List           ${contexts}           0
${webview}=                               Get From List           ${contexts}           1  #-1
${chromeviewiframe}                       get from list           ${contexts}           -1  #1
Set Test Variable                         ${native}
Set Test Variable                         ${webview}
set test variable                         ${chromeviewiframe}

#Test Case code
sleep 60
list contexts
switch to context  ${chromeviewiframe}
wait until element is visible  xpath=//*[@id="btnSMS"]  30
click element  xpath=//*[@id="btnSMS"]
</code>```

However it never finds the iframe or button and therefore times out - I am not sure if 'get contexts' can be used to find iframes.

I have also tried to put the little bit of code appium supplied on their page into a python file in which i intended to call and hoped that would switch frames but didnt succeed at this attempt

```<code>#no idea what library's i am supposed to import and if the return makes sense?
class _frames():
def frame (self):
self.driver.switch_to.frame(3)
return   self.driver.switch_to.frame(3)
</code>```

My iframe xpath is (x'd out some characters) #iframe   //*[@id="xxx2iframe"]

I have been having errors such as:

The phone is still activate and connection isnt lost but i think it just cant find the iframe context - I cant properly test the python file as the code isn't compelete and im not sure what i need to do to fix it to test that 'solution' out. I also wondered if i had another file calling selenium and call the switch frame keyword would it work for appium automation as they use the same drivers? I assume not?

Help to figure this out would be much appreciated, there isn't much point in me writing automation test cases if i cannot get it to automatically log in and get past this point.

Kind Regards, Jem

答:
Ok so if anyone else searches for this question ive came up with an answer which is similar to the solution to this question: How to find XPath for button within iframe using python?

However it didn't relate and explain how it could be used in Robot framework so what i did was:

Clicked (ctrl+click) on appium keywords from my robot file which open the '_applicationmannagement.py' file which contains all the python methods which make up the keywords for appium Library

2.Inserted the following method in python:

```<code>def frame (self):
  driver = self._current_application()
  driver.switch_to.frame(driver.find_element_by_xpath( "//*[@id=\"xxx2iframe\"]"))
  WebDriverWait(driver, 30).until(EC.element_to_be_clickable(("xpath","//*
  [@id='btnSMS']"))).click()
</code>```

Then in my robot file i simply just call the python method frame by writing the word 'frame' as part of my test case

This method switches to the iframe by using xpath and  then it waits up until 30 seconds to find the button and once found it clicks it.

One thing to point out which was stopping this was the emulator might need to be restarted  as at one point it would not load the iframe on the device.

I really hope this helps someone!

Body:
Hi I have been searching a lot on the internet to find how i am supposed to switch from web or native context view to an iframe. I am trying to automate a user logging into an app and the third piece of identification is generating a OTP. This happens to be inside an iframe and i have tried quite a few things to interact with it. Firstly I cannot find any good documentation on how to achieve this through keywords (Appium) using robot, and i do not have a lot of programming experience to write it in python then call it but i have tried.

First thing i tried was using the keyword 'switch to context' and 'get contexts' which i am already using to switch between native and webview already:

List Contexts
${contexts}=                              Get Contexts
${native}=                                Get From List           ${contexts}           0
${webview}=                               Get From List           ${contexts}           1  #-1
${chromeviewiframe}                       get from list           ${contexts}           -1  #1
Set Test Variable                         ${native}
Set Test Variable                         ${webview}
set test variable                         ${chromeviewiframe}

#Test Case code
sleep 60
list contexts
switch to context  ${chromeviewiframe}
wait until element is visible  xpath=//*[@id="btnSMS"]  30
click element  xpath=//*[@id="btnSMS"]

However it never finds the iframe or button and therefore times out - I am not sure if 'get contexts' can be used to find iframes.

I have also tried to put the little bit of code appium supplied on their page into a python file in which i intended to call and hoped that would switch frames but didnt succeed at this attempt

#no idea what library's i am supposed to import and if the return makes sense?
class _frames():
def frame (self):
self.driver.switch_to.frame(3)
return   self.driver.switch_to.frame(3)

My iframe xpath is (x'd out some characters) #iframe   //*[@id="xxx2iframe"]

I have been having errors such as:

The phone is still activate and connection isnt lost but i think it just cant find the iframe context - I cant properly test the python file as the code isn't compelete and im not sure what i need to do to fix it to test that 'solution' out. I also wondered if i had another file calling selenium and call the switch frame keyword would it work for appium automation as they use the same drivers? I assume not?

Help to figure this out would be much appreciated, there isn't much point in me writing automation test cases if i cannot get it to automatically log in and get past this point.

Kind Regards, Jem

Body:
Ok so if anyone else searches for this question ive came up with an answer which is similar to the solution to this question: How to find XPath for button within iframe using python?

However it didn't relate and explain how it could be used in Robot framework so what i did was:

Clicked (ctrl+click) on appium keywords from my robot file which open the '_applicationmannagement.py' file which contains all the python methods which make up the keywords for appium Library

2.Inserted the following method in python:

def frame (self):
  driver = self._current_application()
  driver.switch_to.frame(driver.find_element_by_xpath( "//*[@id=\"xxx2iframe\"]"))
  WebDriverWait(driver, 30).until(EC.element_to_be_clickable(("xpath","//*
  [@id='btnSMS']"))).click()

Then in my robot file i simply just call the python method frame by writing the word 'frame' as part of my test case

This method switches to the iframe by using xpath and  then it waits up until 30 seconds to find the button and once found it clicks it.

One thing to point out which was stopping this was the emulator might need to be restarted  as at one point it would not load the iframe on the device.

I really hope this helps someone!


问:
How to trick an application into thinking its stdout is a terminal, not a pipe
I'm trying to do the opposite of "Detect if stdin is a terminal or pipe?".

I'm running an application that's changing its output format because it detects a pipe on STDOUT, and I want it to think that it's an interactive terminal so that I get the same output when redirecting.

I was thinking that wrapping it in an expect script or using a proc_open() in PHP would do it, but it doesn't.

Any ideas out there?

答:
Updating @A-Ron's answer to
a) work on both Linux & MacOs
b) propagate status code indirectly (since MacOs script does not support it)

faketty () {
  # Create a temporary file for storing the status code
  tmp=$(mktemp)

  # Ensure it worked or fail with status 99
  [ "$tmp" ] || return 99

  # Produce a script that runs the command provided to faketty as
  # arguments and stores the status code in the temporary file
  cmd="$(printf '%q ' "$@")"'; echo $? > '$tmp

  # Run the script through /bin/sh with fake tty
  if [ "$(uname)" = "Darwin" ]; then
    # MacOS
    script -Fq /dev/null /bin/sh -c "$cmd"
  else
    script -qfc "/bin/sh -c $(printf "%q " "$cmd")" /dev/null
  fi

  # Ensure that the status code was written to the temporary file or
  # fail with status 99
  [ -s $tmp ] || return 99

  # Collect the status code from the temporary file
  err=$(cat $tmp)

  # Remove the temporary file
  rm -f $tmp

  # Return the status code
  return $err
}
```

<p>Examples:</p>

<pre class="lang-sh prettyprint-override"><code>$ faketty false ; echo $?
1

$ faketty echo '$HOME' ; echo $?
$HOME
0

embedded_example () {
  faketty perl -e 'sleep(5); print "Hello  world\n"; exit(3);' > LOGFILE 2>&1 </dev/null &
  pid=$!

  # do something else
  echo 0..
  sleep 2
  echo 2..

  echo wait
  wait $pid
  status=$?
  cat LOGFILE
  echo Exit status: $status
}

$ embedded_example
0..
2..
wait
Hello  world
Exit status: 3
</code>```

OwnerDisplayName: Chris

Body:
Updating @A-Ron's answer to
a) work on both Linux & MacOs
b) propagate status code indirectly (since MacOs script does not support it)

faketty () {
  # Create a temporary file for storing the status code
  tmp=$(mktemp)

  # Ensure it worked or fail with status 99
  [ "$tmp" ] || return 99

  # Produce a script that runs the command provided to faketty as
  # arguments and stores the status code in the temporary file
  cmd="$(printf '%q ' "$@")"'; echo $? > '$tmp

  # Run the script through /bin/sh with fake tty
  if [ "$(uname)" = "Darwin" ]; then
    # MacOS
    script -Fq /dev/null /bin/sh -c "$cmd"
  else
    script -qfc "/bin/sh -c $(printf "%q " "$cmd")" /dev/null
  fi

  # Ensure that the status code was written to the temporary file or
  # fail with status 99
  [ -s $tmp ] || return 99

  # Collect the status code from the temporary file
  err=$(cat $tmp)

  # Remove the temporary file
  rm -f $tmp

  # Return the status code
  return $err
}

Examples:

$ faketty false ; echo $?
1

$ faketty echo '$HOME' ; echo $?
$HOME
0

embedded_example () {
  faketty perl -e 'sleep(5); print "Hello  world\n"; exit(3);' > LOGFILE 2>&1 </dev/null &
  pid=$!

  # do something else
  echo 0..
  sleep 2
  echo 2..

  echo wait
  wait $pid
  status=$?
  cat LOGFILE
  echo Exit status: $status
}

$ embedded_example
0..
2..
wait
Hello  world
Exit status: 3


问:
Code Igniter Login, Session and Redirect Problem in Internet Explorer?
I'm still new to code igniter and I'm having problems getting the login system to work.

The login always works when I use Firefox.  The login consistently works on some IE7 browsers but consistently fails on other IE7 browsers.

When tracing the code, I see that the models/redux_auth_model.php does successfully authenticate the user, it writes user information into the $this->session->set_userdata() and it redirect them to a member's page of my choosing.   Here's the code:

```<code>public function login($identity = false, $password = false)
{
            $identity_column = $this->config->item('identity');
            $users_table     = $this->tables['users'];

            if ($identity === false || $password === false || $this->identity_check($identity) == false)
            {
                return false;
            }

            $query = $this->db->select($identity_column.', email, password, group_id')
                           ->where($identity_column, $identity)
                           ->where('active', 'Active')
                           ->limit(1)
                           ->get($users_table);

        $result = $query->row();

        if ($query->num_rows() == 1)
        {
            //$password = $this->hash_password_db($identity, $password);

           if (!empty($result->activation_code)) { return false; }

                if ($result->password === $password)
                {
                    $this->session->set_userdata($identity_column,  $result->{$identity_column});
                    $this->session->set_userdata('email',  $result->email);
                    $this->session->set_userdata('group',  $result->group_id);
                    return true;
                }
        }

        return false;
}
</code>```

I did a variable dump of $this->session in both IE7 and FF and confirmed that all the userdata is intact before the redirect.  The session had my email information, group information and $identity_column information.

However, after the redirect,  the session data is empty on some IE7 browsers, which is why CI keeps booting me out of the system. It's fully intact on other IE7 browsers and always intact in Firefox.

Why would session data be browser dependent?

Any ideas on how to troubleshoot this further? I am baffled...

答: I faced the same problem while using IE8 with browser mode. I've found the problem is in matching the user agent. In session database it saves useragent as IE7 but from cookie it gets IE8. I've set $config[sess_match_useragent] = FALSE and the problem is solved.

ContentLicense: CC BY-SA 2.5

Body:
I'm still new to code igniter and I'm having problems getting the login system to work.

The login always works when I use Firefox.  The login consistently works on some IE7 browsers but consistently fails on other IE7 browsers.

When tracing the code, I see that the models/redux_auth_model.php does successfully authenticate the user, it writes user information into the $this->session->set_userdata() and it redirect them to a member's page of my choosing.   Here's the code:

public function login($identity = false, $password = false)
{
            $identity_column = $this->config->item('identity');
            $users_table     = $this->tables['users'];

            if ($identity === false || $password === false || $this->identity_check($identity) == false)
            {
                return false;
            }

            $query = $this->db->select($identity_column.', email, password, group_id')
                           ->where($identity_column, $identity)
                           ->where('active', 'Active')
                           ->limit(1)
                           ->get($users_table);

        $result = $query->row();

        if ($query->num_rows() == 1)
        {
            //$password = $this->hash_password_db($identity, $password);

           if (!empty($result->activation_code)) { return false; }

                if ($result->password === $password)
                {
                    $this->session->set_userdata($identity_column,  $result->{$identity_column});
                    $this->session->set_userdata('email',  $result->email);
                    $this->session->set_userdata('group',  $result->group_id);
                    return true;
                }
        }

        return false;
}

I did a variable dump of $this->session in both IE7 and FF and confirmed that all the userdata is intact before the redirect.  The session had my email information, group information and $identity_column information.

However, after the redirect,  the session data is empty on some IE7 browsers, which is why CI keeps booting me out of the system. It's fully intact on other IE7 browsers and always intact in Firefox.

Why would session data be browser dependent?

Any ideas on how to troubleshoot this further? I am baffled...

ContentLicense: CC BY-SA 3.0


问:
How to resize an image in http response while my input image received to me in a plain data format?
I'm new in Django and recently I wrote a project about image representation.

in my view's function, I have a function in order to show images. but I first download the image from a service which is an encryption/decryption service.
it means that the downloaded image is in plain data byte format.

Now I want to write a new function to show that image in a smaller size instead of real size for faster loading. also, I want to show an image in another function as a cropped image.

How I can resize and crop images in the fastest way to save time waiting?

答:
```<code>pip install python-resize-image
</code>```

For example

```<code>from PIL import Image

from resizeimage import resizeimage

with open('test-image.jpeg', 'r+b') as f:
    with Image.open(f) as image:
        cover = resizeimage.resize_cover(image, [200, 100])
        cover.save('test-image-cover.jpeg', image.format)
</code>```

From https://pypi.org/project/python-resize-image/

Body:
pip install python-resize-image

For example

from PIL import Image

from resizeimage import resizeimage

with open('test-image.jpeg', 'r+b') as f:
    with Image.open(f) as image:
        cover = resizeimage.resize_cover(image, [200, 100])
        cover.save('test-image-cover.jpeg', image.format)

From https://pypi.org/project/python-resize-image/


问:
Print data on Zebra printer from browser (Windows or MacOS)
I have developed a web application that needs to print on Zebra (GT800) silently directly from browser. The web application is hosted by Amazon AWS, so it is in a different network (so I can't open a socket via PHP directly from the server).
I need to find the best way to print from client browser (such as Firefox or Chrome) to Windows or MacOS on Zebra printer via raw commands ZPL or EPL.

I tried this project https://github.com/qzind/qz-print but it not seems to be the best solution because each print job needs to confirm and besides I need to purchase a certificate. Is there a more simple and clean solution through JS, jQuery or third-party plugins in Chrome or Firefox?

Thanks a lot!

答: you can use Zebra's application for this, Zebra Browser Print, only limit is to have printer connected to USB or Network</p>


问:
simplest way to send an object with Tcpclinet c#
im new to c# and i was wondering , what is the simplest way to send an object using tcpClient , itried the following code but it throws a wierd error
client code :

```<code>TcpClient client = new TcpClient(ip, port);
StreamWriter writer = new StreamWriter(client.GetStream());
NetworkStream strm = client.GetStream();
BinaryFormatter formatter = new BinaryFormatter();
Transaction tx = new transaction();

string msg = string.Empty;

msg = "transaction";
writer.WriteLine(msg);
writer.Flush();

formatter.Serialize(strm,tx);
</code>```

and on the receiving end

Server Code :

```<code>while(true){
TcpClient client = server.AcceptTcpClient();
IFormatter formatter = new BinaryFormatter();
NetworkStream strm = client.GetStream();
StreamReader reader = new StreamReader(client.GetStream());
string msg = string.Empty;
while (!((msg = reader.ReadLine()).Equals("exit"))){

Transaction tx = (Transaction)formatter.Deserialize(strm);

}
</code>```

it produces this error on the server

```<code>input stream is not a valid ibinary format intital content is :0c-02-00-00 .....
</code>```

so can someone please help me or if there another simple and clean way of sending objects using tcpclient ?

答:
The underlying problem here is tied into the way that you are mixing two different mechanisms to read and write to a stream, specifically: using StreamReader and a separate stream-based parser. It is also a bad idea to do this with StreamWriter, but ... I think you would get away with it sort-of, although it is still a bad idea.

The problem here is that StreamReader is greedy. When you ask it for a line, it doesn't read from the stream byte-by-byte looking for a \r or \n - it grabs a buffer of data from the stream, and then processes it as you ask for it. In this way, it assumes that it is now the sole owner of the stream.

So; when you do this:

while (!((msg = reader.ReadLine()).Equals("exit"))){
   Transaction tx = (Transaction)formatter.Deserialize(strm);
}
```

<p>the reader consumes <em>more than</em> just <code>"transaction\r\n</code>" - it consumes that line <em>and some undefined number of bytes from whatever comes after</em>. Then, when <code>BinaryFormatter</code> tries to read the stream, it finds itself half way through a message, and it explodes in a shower of sparks.</p>

<p>Ideally, limit yourself to <em>one serialization mechanism</em>. Meaning: lose  <code>StreamReader</code>/<code>StreamWriter</code> <strong>completely</strong> here.</p>

<p>If I could propose an alternative mechanism using protobuf-net and inheritance:</p>

<pre class="lang-cs prettyprint-override"><code>[ProtoContract]
[ProtoInclude(1, typeof(ShutdownMessage))]
[ProtoInclude(2, typeof(TransactionMessage))]
public abstract class MessageBase {}

[ProtoContract]
public sealed class ShutdownMessage : MessageBase {}

[ProtoContract]
public sealed class TransactionMessage : MessageBase {
    // your data here
}
</code>```

and now you can send any number of messages with:

public void Send(MessageBase message) {
    Serializer.SerializeWithLengthPrefix(strm, message, PrefixStyle.Base128);
}
```

<p>and <em>receive</em> any number of messages with:</p>

<pre class="lang-cs prettyprint-override"><code>while (true) {
    var msg = Serializer.DeserializeWithLengthPrefix<MessageBase>(strm, PrefixStyle.Base128);
    if (msg is null || msg is ShutdownMessage) break; // all done
    switch (msg)
    {
        case TransactionMessage tx: ProcessTransaction(tx); break;
        // etc
    }
}

</code>```

Body:
im new to c# and i was wondering , what is the simplest way to send an object using tcpClient , itried the following code but it throws a wierd error
client code :

TcpClient client = new TcpClient(ip, port);
StreamWriter writer = new StreamWriter(client.GetStream());
NetworkStream strm = client.GetStream();
BinaryFormatter formatter = new BinaryFormatter();
Transaction tx = new transaction();

string msg = string.Empty;

msg = "transaction";
writer.WriteLine(msg);
writer.Flush();

formatter.Serialize(strm,tx);

and on the receiving end

Server Code :

while(true){
TcpClient client = server.AcceptTcpClient();
IFormatter formatter = new BinaryFormatter();
NetworkStream strm = client.GetStream();
StreamReader reader = new StreamReader(client.GetStream());
string msg = string.Empty;
while (!((msg = reader.ReadLine()).Equals("exit"))){

Transaction tx = (Transaction)formatter.Deserialize(strm);

}

it produces this error on the server

input stream is not a valid ibinary format intital content is :0c-02-00-00 .....

so can someone please help me or if there another simple and clean way of sending objects using tcpclient ?

Body:
The underlying problem here is tied into the way that you are mixing two different mechanisms to read and write to a stream, specifically: using StreamReader and a separate stream-based parser. It is also a bad idea to do this with StreamWriter, but ... I think you would get away with it sort-of, although it is still a bad idea.

The problem here is that StreamReader is greedy. When you ask it for a line, it doesn't read from the stream byte-by-byte looking for a \r or \n - it grabs a buffer of data from the stream, and then processes it as you ask for it. In this way, it assumes that it is now the sole owner of the stream.

So; when you do this:

while (!((msg = reader.ReadLine()).Equals("exit"))){
   Transaction tx = (Transaction)formatter.Deserialize(strm);
}

the reader consumes more than just "transaction\r\n" - it consumes that line and some undefined number of bytes from whatever comes after. Then, when BinaryFormatter tries to read the stream, it finds itself half way through a message, and it explodes in a shower of sparks.

Ideally, limit yourself to one serialization mechanism. Meaning: lose  StreamReader/StreamWriter completely here.

If I could propose an alternative mechanism using protobuf-net and inheritance:

[ProtoContract]
[ProtoInclude(1, typeof(ShutdownMessage))]
[ProtoInclude(2, typeof(TransactionMessage))]
public abstract class MessageBase {}

[ProtoContract]
public sealed class ShutdownMessage : MessageBase {}

[ProtoContract]
public sealed class TransactionMessage : MessageBase {
    // your data here
}

and now you can send any number of messages with:

public void Send(MessageBase message) {
    Serializer.SerializeWithLengthPrefix(strm, message, PrefixStyle.Base128);
}

and receive any number of messages with:

while (true) {
    var msg = Serializer.DeserializeWithLengthPrefix<MessageBase>(strm, PrefixStyle.Base128);
    if (msg is null || msg is ShutdownMessage) break; // all done
    switch (msg)
    {
        case TransactionMessage tx: ProcessTransaction(tx); break;
        // etc
    }
}


问:
solution : Manage space between group columns in highchart
I was working with highchart on group columns , well here I had to reduce the size of column but by doing this highchart weirdly managing space between columns when data is less, so I was searching for solution where I found bellow link which is realy helpfull

https://github.com/highcharts/highcharts-react/issues/77

答:
You can manage the space by using pointPadding and groupPadding properties:

```<code>plotOptions: {
  series: {
    pointPadding: 0.1,
    groupPadding: 0.3
  }
}
</code>```

Live demo: http://jsfiddle.net/BlackLabel/6m4e8x0y/4875/

API Reference:

https://api.highcharts.com/highcharts/plotOptions.column.pointPadding

https://api.highcharts.com/highcharts/plotOptions.column.groupPadding

Body:
You can manage the space by using pointPadding and groupPadding properties:

plotOptions: {
  series: {
    pointPadding: 0.1,
    groupPadding: 0.3
  }
}

Live demo: http://jsfiddle.net/BlackLabel/6m4e8x0y/4875/

API Reference:

https://api.highcharts.com/highcharts/plotOptions.column.pointPadding

https://api.highcharts.com/highcharts/plotOptions.column.groupPadding


问:
Django pagination dependent on ordering
I have the following model (simplified):

```<code>class Post(models.Model):
    title = models.CharField(max_length=20)
    date_created = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ('-date_created',) # note the "reverse" ordering here
</code>```

, then my custom DetailView based on generic.DetailView:

```<code>class PostDetailView(generic.DetailView):
    queryset = Post.objects.all()
</code>```

and, finally, the following template:

```<code>{% with object.get_previous_by_date_created as prev %}
    {% if prev %}
    <a class="nav-link-prev"
       href="{% url "blog:post_detail" pk=prev.id %}">Previous</a>
    {% endif %}
{% endwith %}

{% with object.get_next_by_date_created as next %}
    {% if next %}
    <a class="nav-link-next"
       href="{% url "blog:post_detail" pk=next.id %}">Next</a>
    {% endif %}
{% endwith %}
</code>```

My pagination implemented this way works, but due to the reverse ordering (i.e -date_created) field, its Previous/Next labels are misplaced. In other words my template outputs "Previous" where it should be "Next", and vice versa. If I remove a - sign in ordering = ('-date_created',) it will work fine, but that's not the ordering I would like to have on my website.

Is there an easy and idiomatic way of fixing this misbehavior? What am I missing?

答:
I think you have to use DetailView with mixin  MultipleObjectMixin like below...

```<code>from django.views.generic.detail import DetailView
from django.views.generic.list import MultipleObjectMixin
from django.core import paginator

class PostDetailView(DetailView, MultipleObjectMixin):
    model = Post
    paginate_by = 5

    def get_context_data(self, **kwargs):
        object_list = Post.objects.all().order_by('-date_created')
        context = super(PostDetailView, self).get_context_data(object_list=object_list, **kwargs)
        post_paginator = paginator.Paginator(object_list, self.paginate_by)
        # Catch invalid page numbers
        try:
            post_page_obj = post_paginator.page(purchases_page)
        except (paginator.PageNotAnInteger, paginator.EmptyPage):
            post_page_obj = post_paginator.page(1)

        context["post_page_obj"] = post_page_obj
        return context
</code>```

Now, you should be able to use pagination method with post_page_obj variable

Title: Django pagination dependent on ordering

Body:
I have the following model (simplified):

class Post(models.Model):
    title = models.CharField(max_length=20)
    date_created = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ('-date_created',) # note the "reverse" ordering here

, then my custom DetailView based on generic.DetailView:

class PostDetailView(generic.DetailView):
    queryset = Post.objects.all()

and, finally, the following template:

{% with object.get_previous_by_date_created as prev %}
    {% if prev %}
    Previous
    {% endif %}
{% endwith %}

{% with object.get_next_by_date_created as next %}
    {% if next %}
    Next
    {% endif %}
{% endwith %}

My pagination implemented this way works, but due to the reverse ordering (i.e -date_created) field, its Previous/Next labels are misplaced. In other words my template outputs "Previous" where it should be "Next", and vice versa. If I remove a - sign in ordering = ('-date_created',) it will work fine, but that's not the ordering I would like to have on my website.

Is there an easy and idiomatic way of fixing this misbehavior? What am I missing?

Body:
I think you have to use DetailView with mixin  MultipleObjectMixin like below...

from django.views.generic.detail import DetailView
from django.views.generic.list import MultipleObjectMixin
from django.core import paginator

class PostDetailView(DetailView, MultipleObjectMixin):
    model = Post
    paginate_by = 5

    def get_context_data(self, **kwargs):
        object_list = Post.objects.all().order_by('-date_created')
        context = super(PostDetailView, self).get_context_data(object_list=object_list, **kwargs)
        post_paginator = paginator.Paginator(object_list, self.paginate_by)
        # Catch invalid page numbers
        try:
            post_page_obj = post_paginator.page(purchases_page)
        except (paginator.PageNotAnInteger, paginator.EmptyPage):
            post_page_obj = post_paginator.page(1)

        context["post_page_obj"] = post_page_obj
        return context

Now, you should be able to use pagination method with post_page_obj variable


问:
Select a random key from 2 Python dictionaries
I have 2 dictionaries in Python
the user is asked to press a key to show a random key from the 2 dictionaries
How can I do that?

Thank you

答:
You can use random.choice:</p>

```<code>>>> import random
>>> random.choice([*dict1.keys(), *dict2.keys()])
</code>```

Body:
You can use random.choice:

>>> import random
>>> random.choice([*dict1.keys(), *dict2.keys()])


问:
Can you use template literal for function name in javascript?
can you use template literals to name functions dynamically

```<code>let variable = "something"

function `constant${variable}` () {
               //do something
}
</code>```

答:
You can declare a variable and fetch its context using this keyword to declare your function

Example

```<code>let fnName = "CoolDynamicFunction";

this[`${fnName}`] = () => {
  console.log("I'm a cool dynamic function")
}
</code>```

and then call it using

```<code>CoolDynamicFunction()
</code>```

Body:
can you use template literals to name functions dynamically

let variable = "something"

function `constant${variable}` () {
               //do something
}

Body:
You can declare a variable and fetch its context using this keyword to declare your function

Example

let fnName = "CoolDynamicFunction";

this[`${fnName}`] = () => {
  console.log("I'm a cool dynamic function")
}

and then call it using

CoolDynamicFunction()


问:
How to make icon spin in react-native-paper?
I am having this react-native-paper button:

```<code>      <Button
        disabled={loading}
        icon="refresh"
        mode="contained"
        onPress={this.refreshData.bind(this)}
      >
        Refresh
      </Button>
</code>```

How can I make the icon spin when loading=true?

答:
for the spinning icon do this.

declare one variable refreshing any boolean value when data refresh value set to be true and icon spinning start.

```<code>      <Button
        loading={loading}
        disabled={loading}
        icon="refresh"
        mode="contained"
        onPress={this.refreshData.bind(this)}
      >
        Refresh
      </Button>
</code>```

react-native-paper button have props like.. loading
it's simply spinning icon

here snack link

Body:
I am having this react-native-paper button:

      <Button
        disabled={loading}
        icon="refresh"
        mode="contained"
        onPress={this.refreshData.bind(this)}
      >
        Refresh
      </Button>

How can I make the icon spin when loading=true?

Body:
for the spinning icon do this.

declare one variable refreshing any boolean value when data refresh value set to be true and icon spinning start.

      <Button
        loading={loading}
        disabled={loading}
        icon="refresh"
        mode="contained"
        onPress={this.refreshData.bind(this)}
      >
        Refresh
      </Button>

react-native-paper button have props like.. loading
it's simply spinning icon

here snack link


问:
Codeigniter Sessions Checking from a header view file
I am fairly new and just started to use Codeigniter, and have come across some confusion regarding sessions.

What I want to achieve is, like in regular php, I want to check if a user is logged in by using a header include file which checks the session data. I dont want to check/write that checking code in every controller while passing data to the view file.

Can someone please show me how it can be done?

Ex. I don't want to do the following in every controller:

```<code>//Controller:
if($this->session->userdata('loggedin'){
$data['loggedin'] = $this->session->userdata('loggedin');
}
//I dont want to check the above on every function in every controller
$this->load->view('some_view_file', $data);

//some_view_file
if(isset($loggedin)){
echo "You are logged in!";
}
else
{
echo "Please log in!";
}
</code>```

Instead, I want something to like the following:

```<code>//some view file
if(isset($loggedin))
{
echo "your logged in";
}
else
{
echo "please log in";
}
</code>```

And also, how can I use native php sessions instead of CI Sessions. Any help will be much appreciated. Thanks.

答:
I think using a construct on your controller would be the smartest approach.

I also recommend encrypting your session cookie.

```<code>
class Blog extends CI_Controller {

       public function __construct()
       {
            parent::__construct();
            //always check if session userdata value "logged_in" is not true
            if(!$this->session->userdata("logged_in"))
            {
                 redirect('login');
            }

       }
}
</code>```

Body:
I am fairly new and just started to use Codeigniter, and have come across some confusion regarding sessions.

What I want to achieve is, like in regular php, I want to check if a user is logged in by using a header include file which checks the session data. I dont want to check/write that checking code in every controller while passing data to the view file.

Can someone please show me how it can be done?

Ex. I don't want to do the following in every controller:

//Controller:
if($this->session->userdata('loggedin'){
$data['loggedin'] = $this->session->userdata('loggedin');
}
//I dont want to check the above on every function in every controller
$this->load->view('some_view_file', $data);

//some_view_file
if(isset($loggedin)){
echo "You are logged in!";
}
else
{
echo "Please log in!";
}

Instead, I want something to like the following:

//some view file
if(isset($loggedin))
{
echo "your logged in";
}
else
{
echo "please log in";
}

And also, how can I use native php sessions instead of CI Sessions. Any help will be much appreciated. Thanks.

Body:
I think using a construct on your controller would be the smartest approach.

I also recommend encrypting your session cookie.

class Blog extends CI_Controller {

       public function __construct()
       {
            parent::__construct();
            //always check if session userdata value "logged_in" is not true
            if(!$this->session->userdata("logged_in"))
            {
                 redirect('login');
            }

       }
}


问:
Swift - changing image view background image via segmented control
The title itself explains as much as i will be able to. Basically, i have a segmented control that i want to change the image within my image view after each segment is selected, but i can't seem to apply or find the logic to resolve my problem. The answer itself is probably very simple, but i'm really new to Swift and didn't manage to find an answer anywhere, so i would love a solution to my problem. Thanks!</p>

```<code>@IBOutlet weak var newImageView: UIImageView!

@IBAction func chooseImage(sender: AnyObject) {
    if myPhotoSegment.selectedSegmentIndex == 0
    {

        newImageView = UIImage(named: "3.jpg")

    }

    if myPhotoSegment.selectedSegmentIndex == 1
    {

    }
</code>```

答:
Segment using image in imageview in swift4

```<code>@IBOutlet weak var bgimage: UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()

    self.view.backgroundColor = UIColor.red

    let itemsimg = ["google", "facebook", "instagram" , "twitter"]
    let customSI = UISegmentedControl(items: itemsimg)
    customSI.selectedSegmentIndex = 0

    customSI.frame = CGRect(x:50, y:100, width:300, height: 40)

    customSI.layer.cornerRadius = 5.0
    customSI.backgroundColor = UIColor.black
    customSI.tintColor = UIColor.white

    customSI.addTarget(self, action: #selector(changeimg),for: .valueChanged)

    self.view.addSubview(customSI)
}

@objc func changeimg(sender: UISegmentedControl) {
    switch sender.selectedSegmentIndex {
    case 1:
        bgimage.image = UIImage(named: "facebook")
    case 2:
        bgimage.image = UIImage(named: "instagram")
    case 3:
        bgimage.image = UIImage(named: "twitter")
    default:
        bgimage.image = UIImage(named: "google")
    }
}
</code>```

}

Body:
The title itself explains as much as i will be able to. Basically, i have a segmented control that i want to change the image within my image view after each segment is selected, but i can't seem to apply or find the logic to resolve my problem. The answer itself is probably very simple, but i'm really new to Swift and didn't manage to find an answer anywhere, so i would love a solution to my problem. Thanks!

@IBOutlet weak var newImageView: UIImageView!

@IBAction func chooseImage(sender: AnyObject) {
    if myPhotoSegment.selectedSegmentIndex == 0
    {

        newImageView = UIImage(named: "3.jpg")

    }

    if myPhotoSegment.selectedSegmentIndex == 1
    {

    }

Body:
Segment using image in imageview in swift4

@IBOutlet weak var bgimage: UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()

    self.view.backgroundColor = UIColor.red

    let itemsimg = ["google", "facebook", "instagram" , "twitter"]
    let customSI = UISegmentedControl(items: itemsimg)
    customSI.selectedSegmentIndex = 0

    customSI.frame = CGRect(x:50, y:100, width:300, height: 40)

    customSI.layer.cornerRadius = 5.0
    customSI.backgroundColor = UIColor.black
    customSI.tintColor = UIColor.white

    customSI.addTarget(self, action: #selector(changeimg),for: .valueChanged)

    self.view.addSubview(customSI)
}

@objc func changeimg(sender: UISegmentedControl) {
    switch sender.selectedSegmentIndex {
    case 1:
        bgimage.image = UIImage(named: "facebook")
    case 2:
        bgimage.image = UIImage(named: "instagram")
    case 3:
        bgimage.image = UIImage(named: "twitter")
    default:
        bgimage.image = UIImage(named: "google")
    }
}

}


问:
How replace specific strings on conditions in R?
I have data where I have compressed duplicate gene results to each be in 1 row. This has made some rows filled with commas, I am trying to replace rows which only contain commas with NA. However, I also have rows with commas and qualitative data I am trying to keep. For example:

```<code>Gene     Condition
Gene1    Name=Asymmetrical dimethylarginine level, Name=Bipolar disorder and schizophrenia, Name=3-hydroxypropylmercapturic acid levels in smoker
Gene2    Name=blood pressure, Name=diabetes
Gene3    Name=heart disease, , , , ,
Gene4    , , , , , , , , ,
Gene5    NA
Gene6    , , ,
</code>```

Expected output:

```<code>Gene     Condition
Gene1    Name=Asymmetrical dimethylarginine level, Name=Bipolar disorder and schizophrenia, Name=3-hydroxypropylmercapturic acid levels in smoker
Gene2    Name=blood pressure, Name=diabetes
Gene3    Name=heart disease, , , , ,
Gene4    NA
Gene5    NA
Gene6    NA
#ideally I would get rid of Gene3's extra commas but this is not necessary
</code>```

I am trying to code for a statement like "if the row has only commas in the condition column replace to NA", and trying to do it with a statement like data$Condition[ if("," & ![A-Z]|[a-z]|[=]) ] <- "NA" but I'm not sure how to get the syntax right or if this will work for all rows with only commas but the number of commas varies - I am new to R so any guidance would be appreciated.

Example data:

```<code>DF <-
structure(list(Gene = c("Gene1", "Gene2", "Gene3", "Gene4", "Gene5",
"Gene6"), Condition = c("Name=Asymmetrical dimethylarginine leve,l Name=Bipolar disorder and schizophrenia, Name=3-hydroxypropylmercapturic acid levels in smoker",
"Name=blood pressure, Name=diabetes", "Name=heart disease, , , , ,",
", , , , , , , , ,", NA, "Name=kidney disease, , ,")),
row.names = c(NA, -6L), class = "data.frame")
</code>```

答:
If I understood you correctly, You can try this for removing commas if a cell contains only commas

```<code>DF$condition <- gsub('^(,\\s*)+$',NA, DF$Condition)
</code>```

However, if you want to remove trailing commas only and replacing all commas cell with NA then you can try:

```<code>DF$condition <- gsub('^$', NA, gsub('(,\\s*)+$','', DF$Condition))
</code>```

1st Output:

```<code>> gsub('^(,\\s*)+$',NA, DF$Condition)
[1] "Name=Asymmetrical dimethylarginine leve,l Name=Bipolar disorder and schizophrenia, Name=3-hydroxypropylmercapturic acid levels in smoker"
[2] "Name=blood pressure, Name=diabetes"
[3] "Name=heart disease, , , , ,"
[4] NA
[5] NA
[6] "Name=kidney disease, , ,"
</code>```

2nd Output:

```<code>> gsub('^$', NA, gsub('(,\\s*)+$','', DF$Condition))
[1] "Name=Asymmetrical dimethylarginine leve,l Name=Bipolar disorder and schizophrenia, Name=3-hydroxypropylmercapturic acid levels in smoker"
[2] "Name=blood pressure, Name=diabetes"
[3] "Name=heart disease"
[4] NA
[5] NA
[6] "Name=kidney disease"
</code>```

Body:
I have data where I have compressed duplicate gene results to each be in 1 row. This has made some rows filled with commas, I am trying to replace rows which only contain commas with NA. However, I also have rows with commas and qualitative data I am trying to keep. For example:

Gene     Condition
Gene1    Name=Asymmetrical dimethylarginine level, Name=Bipolar disorder and schizophrenia, Name=3-hydroxypropylmercapturic acid levels in smoker
Gene2    Name=blood pressure, Name=diabetes
Gene3    Name=heart disease, , , , ,
Gene4    , , , , , , , , ,
Gene5    NA
Gene6    , , ,

Expected output:

Gene     Condition
Gene1    Name=Asymmetrical dimethylarginine level, Name=Bipolar disorder and schizophrenia, Name=3-hydroxypropylmercapturic acid levels in smoker
Gene2    Name=blood pressure, Name=diabetes
Gene3    Name=heart disease, , , , ,
Gene4    NA
Gene5    NA
Gene6    NA
#ideally I would get rid of Gene3's extra commas but this is not necessary

I am trying to code for a statement like "if the row has only commas in the condition column replace to NA", and trying to do it with a statement like data$Condition[ if("," & ![A-Z]|[a-z]|[=]) ] <- "NA" but I'm not sure how to get the syntax right or if this will work for all rows with only commas but the number of commas varies - I am new to R so any guidance would be appreciated.

Example data:

DF <-
structure(list(Gene = c("Gene1", "Gene2", "Gene3", "Gene4", "Gene5",
"Gene6"), Condition = c("Name=Asymmetrical dimethylarginine leve,l Name=Bipolar disorder and schizophrenia, Name=3-hydroxypropylmercapturic acid levels in smoker",
"Name=blood pressure, Name=diabetes", "Name=heart disease, , , , ,",
", , , , , , , , ,", NA, "Name=kidney disease, , ,")),
row.names = c(NA, -6L), class = "data.frame")

Body:
If I understood you correctly, You can try this for removing commas if a cell contains only commas

DF$condition <- gsub('^(,\\s*)+$',NA, DF$Condition)

However, if you want to remove trailing commas only and replacing all commas cell with NA then you can try:

DF$condition <- gsub('^$', NA, gsub('(,\\s*)+$','', DF$Condition))

1st Output:

> gsub('^(,\\s*)+$',NA, DF$Condition)
[1] "Name=Asymmetrical dimethylarginine leve,l Name=Bipolar disorder and schizophrenia, Name=3-hydroxypropylmercapturic acid levels in smoker"
[2] "Name=blood pressure, Name=diabetes"
[3] "Name=heart disease, , , , ,"
[4] NA
[5] NA
[6] "Name=kidney disease, , ,"

2nd Output:

> gsub('^$', NA, gsub('(,\\s*)+$','', DF$Condition))
[1] "Name=Asymmetrical dimethylarginine leve,l Name=Bipolar disorder and schizophrenia, Name=3-hydroxypropylmercapturic acid levels in smoker"
[2] "Name=blood pressure, Name=diabetes"
[3] "Name=heart disease"
[4] NA
[5] NA
[6] "Name=kidney disease"


问:
Running into error - all go routines are asleep error when implementing a lexer in golang
I'm trying to write a scanner/lexer in go, I thought I'd figure it out and after attempting to implement I ran into the error mentioned in the title. Any advice?

Essentially, I'm trying to implement a scanner based on the information from Rob Pike's talk at the Go conference in 2011. He talks about using a finite state machine to implement a scanner in a way that's similar to this:

type state func(s *Scanner) state

basically a recursive structure, in my state implementation, in my emit function I'm trying to print out details about the tokens being received.

```<code>    package scanner

/*
A scanner initializes itself to scan a string/file, then launches a goroutine
that returns the scanner and a channel of items to be tokenized!
*/
import (
    t "CPRL/token"
    "fmt"
    "io/ioutil"
    "log"
    "strings"
    // "unicode"
)

//Scanner - performs lexical analysis

    type Scanner struct {
        CH rune //character examined

        FILE  string //the name of our current file, used for error reporting
        input string //the string currently being scanned

        start int //start position of our token
        curr  int //current position in input
        line  int //current line we are scanning
        width int //the size of last rune read

        tokens chan t.Token //channel of scanned tokens!

    }

    func (s Scanner) String() string {
        var str []string

        if s.FILE != "" {
            str = append(str, s.FILE+": ")
        }

        return strings.Join(str, "")
    }

//Scan - create a new scanner for current input
func Scan(File string) *Scanner {
    buf, err := ioutil.ReadFile(File)
    if err != nil {
        log.Fatal(err)
    }

    in := string(buf)
    s := &Scanner{
        FILE:   File,
        input:  in,
        line:   1,
        tokens: make(chan t.Token),
    }
    go s.Init()
    return s
}

//Init - initialize a created a scanner

    func (s *Scanner) Init() {
        for state := scanTo; state != nil; {
            state = state(s)
            fmt.Println("State entered")
        }
    }
</code>```

I'm attempting to print all the tokens as strings with code that looks like this, in another package

```<code>for tok := range t.Tokens {
  fmt.Println(tok.String())
}
</code>```

Here, we have the slides from Rob Pike's talk at go conference:
https://talks.golang.org/2011/lex.slide#1

This is the project I'm working on currently.
https://github.com/Apheuz/CPRL

答:
channels are blocking.

your call to

```<code>for tok := range s.tokens
</code>```

will block, until someone is writing to the channel or closing it..

but no one will!

Body:
I'm trying to write a scanner/lexer in go, I thought I'd figure it out and after attempting to implement I ran into the error mentioned in the title. Any advice?

Essentially, I'm trying to implement a scanner based on the information from Rob Pike's talk at the Go conference in 2011. He talks about using a finite state machine to implement a scanner in a way that's similar to this:

type state func(s *Scanner) state

basically a recursive structure, in my state implementation, in my emit function I'm trying to print out details about the tokens being received.

    package scanner

/*
A scanner initializes itself to scan a string/file, then launches a goroutine
that returns the scanner and a channel of items to be tokenized!
*/
import (
    t "CPRL/token"
    "fmt"
    "io/ioutil"
    "log"
    "strings"
    // "unicode"
)

//Scanner - performs lexical analysis

    type Scanner struct {
        CH rune //character examined

        FILE  string //the name of our current file, used for error reporting
        input string //the string currently being scanned

        start int //start position of our token
        curr  int //current position in input
        line  int //current line we are scanning
        width int //the size of last rune read

        tokens chan t.Token //channel of scanned tokens!

    }

    func (s Scanner) String() string {
        var str []string

        if s.FILE != "" {
            str = append(str, s.FILE+": ")
        }

        return strings.Join(str, "")
    }

//Scan - create a new scanner for current input
func Scan(File string) *Scanner {
    buf, err := ioutil.ReadFile(File)
    if err != nil {
        log.Fatal(err)
    }

    in := string(buf)
    s := &Scanner{
        FILE:   File,
        input:  in,
        line:   1,
        tokens: make(chan t.Token),
    }
    go s.Init()
    return s
}

//Init - initialize a created a scanner

    func (s *Scanner) Init() {
        for state := scanTo; state != nil; {
            state = state(s)
            fmt.Println("State entered")
        }
    }

I'm attempting to print all the tokens as strings with code that looks like this, in another package

for tok := range t.Tokens {
  fmt.Println(tok.String())
}

Here, we have the slides from Rob Pike's talk at go conference:
https://talks.golang.org/2011/lex.slide#1

This is the project I'm working on currently.
https://github.com/Apheuz/CPRL

Body:
channels are blocking.

your call to

for tok := range s.tokens

will block, until someone is writing to the channel or closing it..

but no one will!


问:
What is the UrlFetch Post Size Limit?
I'm trying to find out what the UrlFetchApp's POST Size Limit is?  A script uploads a few emailed attachments to a web service, and is getting back the following error:

"Limit Exceeded: UrlFetch Post Size. (line XX)".

I have no way to figure this out short of sending a bunch of different sized files to it.

答:
updated information: now it's 50MB
https://developers.google.com/apps-script/guides/services/quotas#current_limitations</p>

Title: What is the UrlFetch Post Size Limit?


问:
VS code BeautifulSoup4 issue: ModuleNotFoundError: No module named 'bs4'
I got error when ran a flask app. This project includes scraping so I installed BeatifulSoup4 in python virtual env. When I ran flask, I got error.

ModuleNotFoundError: No module named 'bs4'

But I installed BeautifulSoup4 correctly. pip3 install beautifulsoup4

There is a weird thing.
When I wrote at terminal, it imported bs4 successfully.

答:
You have to install bs4 package for running beautifulsoup4. If you install only beautifulsoup4, then it won't work as you are using the following import:

```<code>from bs4 import BeautifulSoup
</code>```

Also, it won't work because BeautifulSoup is the sub-package of bs4.

Body:
You have to install bs4 package for running beautifulsoup4. If you install only beautifulsoup4, then it won't work as you are using the following import:

from bs4 import BeautifulSoup

Also, it won't work because BeautifulSoup is the sub-package of bs4.


问:
How do I accomplish an if/else in mustache.js?
It seems rather odd that I can't figure how to do this in mustache. Is it supported?

This is my sad attempt at trying:

```<code>    {{#author}}
      {{#avatar}}
        <img src="{{avatar}}"/>
      {{/avatar}}
      {{#!avatar}}
        <img src="/images/default_avatar.png" height="75" width="75" />
      {{/avatar}}
    {{/author}}
</code>```

This obviously isn't right, but the documentation doesn't mention anything like this. The word "else" isn't even mentioned :(

Also, why is mustache designed this way? Is this sort of thing considered bad? Is it trying to force me to set the default value in the model itself? What about the cases where that isn't possible?

答:
This is something you solve in the "controller", which is the point of logicless templating.

```<code>// some function that retreived data through ajax
function( view ){

   if ( !view.avatar ) {
      // DEFAULTS can be a global settings object you define elsewhere
      // so that you don't have to maintain these values all over the place
      // in your code.
      view.avatar = DEFAULTS.AVATAR;
   }

   // do template stuff here

}
</code>```

This is actually a LOT better then maintaining image url's or other media that might or might not change in your templates, but takes some getting used to. The point is to unlearn template tunnel vision, an avatar img url is bound to be used in other templates, are you going to maintain that url on X templates or a single DEFAULTS settings object? ;)

Another option is to do the following:

```<code>// augment view
view.hasAvatar = !!view.avatar;
view.noAvatar = !view.avatar;
</code>```

And in the template:

```<code>{{#hasAvatar}}
    SHOW AVATAR
{{/hasAvatar}}
{{#noAvatar}}
    SHOW DEFAULT
{{/noAvatar}}
</code>```

But that's going against the whole meaning of logicless templating. If that's what you want to do, you want logical templating and you should not use Mustache, though do give it yourself a fair chance of learning this concept ;)

Body:
It seems rather odd that I can't figure how to do this in mustache. Is it supported?

This is my sad attempt at trying:

    {{#author}}
      {{#avatar}}

      {{/avatar}}
      {{#!avatar}}

      {{/avatar}}
    {{/author}}

This obviously isn't right, but the documentation doesn't mention anything like this. The word "else" isn't even mentioned :(

Also, why is mustache designed this way? Is this sort of thing considered bad? Is it trying to force me to set the default value in the model itself? What about the cases where that isn't possible?

Body:
This is something you solve in the "controller", which is the point of logicless templating.

// some function that retreived data through ajax
function( view ){

   if ( !view.avatar ) {
      // DEFAULTS can be a global settings object you define elsewhere
      // so that you don't have to maintain these values all over the place
      // in your code.
      view.avatar = DEFAULTS.AVATAR;
   }

   // do template stuff here

}

This is actually a LOT better then maintaining image url's or other media that might or might not change in your templates, but takes some getting used to. The point is to unlearn template tunnel vision, an avatar img url is bound to be used in other templates, are you going to maintain that url on X templates or a single DEFAULTS settings object? ;)

Another option is to do the following:

// augment view
view.hasAvatar = !!view.avatar;
view.noAvatar = !view.avatar;

And in the template:

{{#hasAvatar}}
    SHOW AVATAR
{{/hasAvatar}}
{{#noAvatar}}
    SHOW DEFAULT
{{/noAvatar}}

But that's going against the whole meaning of logicless templating. If that's what you want to do, you want logical templating and you should not use Mustache, though do give it yourself a fair chance of learning this concept ;)


问:
How to initialize an array in Kotlin with values?
In Java an array can be initialized such as:

```<code>int numbers[] = new int[] {10, 20, 30, 40, 50}
</code>```

How does Kotlin's array initialization look like?

答:
In this way, you can initialize the int array in koltin.</p>

```<code> val values: IntArray = intArrayOf(1, 2, 3, 4, 5,6,7)
</code>```

Body:
In Java an array can be initialized such as:

int numbers[] = new int[] {10, 20, 30, 40, 50}

How does Kotlin's array initialization look like?

Body:
In this way, you can initialize the int array in koltin.

 val values: IntArray = intArrayOf(1, 2, 3, 4, 5,6,7)


问:
What is the usage and purpose of $any() type cast in angular
i Angular.io site i saw this title:

The $any() type cast function
Sometimes a binding expression triggers a type error during AOT compilation and it is not possible or difficult to fully specify the type. To silence the error, you can use the $any() cast function to cast the expression to the any type as in the following example:

```<code><p>The item's undeclared best by date is: {{$any(item).bestByDate}}</p>
</code>```

but there is no longer description or benefit or practice in it.

What's that technically?

When we have to and need to use of this
stuff?

答:
"fullTemplateTypeCheck" in the "angularCompilerOptions" of the project's enabled. Angular compiler will be stricter when checking your templates type and catch any errors before they cause crashes at runtime.

$any() can be used in binding expressions to disable type checking of
  this expression. This is really similar to as any in TypeScript, and allows expressions that work at runtime but do not type-check.

For More Info Check this:

Body:
i Angular.io site i saw this title:

The $any() type cast function
Sometimes a binding expression triggers a type error during AOT compilation and it is not possible or difficult to fully specify the type. To silence the error, you can use the $any() cast function to cast the expression to the any type as in the following example:

The item's undeclared best by date is: {{$any(item).bestByDate}}

but there is no longer description or benefit or practice in it.

What's that technically?

When we have to and need to use of this
stuff?


答:
You can try grepl like below, where the lines with , only will be set to NA

```<code>DF <- within(DF,Condition <-replace(Condition,!grepl("[[:alnum:]]",Condition),NA))
</code>```

Title: How replace specific strings on conditions in R?

Body:
You can try grepl like below, where the lines with , only will be set to NA

DF <- within(DF,Condition <-replace(Condition,!grepl("[[:alnum:]]",Condition),NA))


问:
C++ condition variable with no time out
Recently, I met a problem which is related with condition variable in C++. The code is shown below :

```<code>#include <iostream>
#include <thread>
#include <chrono>
#include <mutex>
#include <condition_variable>

std::condition_variable cv;
std::mutex mutex;

int main(){

std::unique_lock<std::mutex> uniqueLock(mutex);

while (true)
{

    if(cv.wait_for(uniqueLock, std::chrono::milliseconds(1000)) == std::cv_status::no_timeout)
    {
      std::cout << "has image" << std::endl;

    }
    else
    {
        std::cout<< "time out " << std::endl;
    }

}

return 0;
}
</code>```

The goal of this code is that : each time when condition variable is notified in another thread (cv.notify()), it show "has image " in the console, and if it can not be notified more than 1000 milliseconds, it shows "time out".

So the theoretical output of the above code is (because the condition variable is not notified) :

```<code>time out
time out
time out
time out
</code>```

But when i execute this code in the Vs2015, I found that the output is strange:

```<code>has image
time out
has image
time out
time out
time out
has image
has image
time out
time out
time out
time out
time out
has image
has image
</code>```

I would like to know why i have this output and how can i achieve my goal

Thanks !

答:
I don't know what the cause of your error is (but there are some plausible explanations in the comments). However, one way to fix your issue is to use the other overload of wait_for, which includes a predicate.

It could look something like this (hasImage is just a bool here, replace it with something that makes sense for your needs - !imageStorage.empty() or similar):

```<code>while (true)
{

    if (cv.wait_for(uniqueLock, std::chrono::milliseconds(1000), []() {return hasImage;}))
    {
        std::cout << "has image" << std::endl;
        hasImage = false;
    }
    else
    {
        std::cout << "time out " << std::endl;
    }

}
</code>```

The pertinent point is that the predicate checks if there actually is a new image, and if there isn't then it should continue to wait.

One limitation with this method is that, if the predicate returns false (no image), then you don't know if the condition variable woke due to a spurious wakeup, a timeout, or if there actually was an image but another thread just took it away before this one woke up. But if that is something your design can handle, then this variation works very well.

Title: C++ condition variable with no time out

Body:
Recently, I met a problem which is related with condition variable in C++. The code is shown below :

#include <iostream>
#include <thread>
#include <chrono>
#include <mutex>
#include <condition_variable>

std::condition_variable cv;
std::mutex mutex;

int main(){

std::unique_lock<std::mutex> uniqueLock(mutex);

while (true)
{

    if(cv.wait_for(uniqueLock, std::chrono::milliseconds(1000)) == std::cv_status::no_timeout)
    {
      std::cout << "has image" << std::endl;

    }
    else
    {
        std::cout<< "time out " << std::endl;
    }

}

return 0;
}

The goal of this code is that : each time when condition variable is notified in another thread (cv.notify()), it show "has image " in the console, and if it can not be notified more than 1000 milliseconds, it shows "time out".

So the theoretical output of the above code is (because the condition variable is not notified) :

time out
time out
time out
time out

But when i execute this code in the Vs2015, I found that the output is strange:

has image
time out
has image
time out
time out
time out
has image
has image
time out
time out
time out
time out
time out
has image
has image

I would like to know why i have this output and how can i achieve my goal

Thanks !

Body:
I don't know what the cause of your error is (but there are some plausible explanations in the comments). However, one way to fix your issue is to use the other overload of wait_for, which includes a predicate.

It could look something like this (hasImage is just a bool here, replace it with something that makes sense for your needs - !imageStorage.empty() or similar):

while (true)
{

    if (cv.wait_for(uniqueLock, std::chrono::milliseconds(1000), []() {return hasImage;}))
    {
        std::cout << "has image" << std::endl;
        hasImage = false;
    }
    else
    {
        std::cout << "time out " << std::endl;
    }

}

The pertinent point is that the predicate checks if there actually is a new image, and if there isn't then it should continue to wait.

One limitation with this method is that, if the predicate returns false (no image), then you don't know if the condition variable woke due to a spurious wakeup, a timeout, or if there actually was an image but another thread just took it away before this one woke up. But if that is something your design can handle, then this variation works very well.


问:
Why is the OData $batch request in my SAPUI5 application failing?
I have an OData v2 service running on Wildfly. This service is connected to a single table in SQL Server. Querying this service's metadata and table data in Postman works great. I believe the OData service itself is working like it should.

I have an SAPUI5 application that is pointing to the service (called SITEDATA) in the descriptor:

```<code>"sap.app": {
    ...,
    "dataSources": {
        "SAM": {
            "uri": "http://localhost:8080/odata/SITEDATA/",
            "type": "OData",
            "settings": {
                "odataVersion": "2.0"
            }
        }
    },...

"sap.ui5": {
    ...,
    "models": {
        ...,
        "perDiem": {
            "dataSource": "SAM"
        }...
</code>```

I have a very simple view that points to the single table (which is also called SITEDATA):

```<code>    <List
    items="{ path : 'perDiem>/SITEDATA' }">
    ...
    <items>
        <ObjectListItem title="{perDiem>SITE_ID}">
</code>```

When I run the application I can see that the application successfully queries the service for:

http: //localhost:8080/odata/SITEDATA/$metadata

http: //localhost:8080/odata/SITEDATA/SITEDATA?$skip=0&$top=100

...as well as a bunch of other things. But then I get this:

The WildFly log shows that SITEDATA/$batch just doesn't exist. However, localhost:8080/odata/SITEDATA/SITEDATA/$batch works just fine.

And after researching this problem for days it looks like yes, the $batch request should be performed on the table, not the service. So the error makes sense. But I can't find any way to fix this.

Has any one experienced this problem or see anything I need to do to correct it?

答:
If you want to avoid $batch calls to your backend I suggest you to explicitly declare your model as:</p>

```<code>    "perDiem": {
        "type": "sap.ui.model.odata.v2.ODataModel",
        "settings": {
            "defaultOperationMode": "Server",
            "defaultBindingMode": "TwoWay",
            "defaultCountMode": "Inline",
            "useBatch": false
        },
        "dataSource": "SAM",
        "preload": true
    }
</code>```

Body:
I have an OData v2 service running on Wildfly. This service is connected to a single table in SQL Server. Querying this service's metadata and table data in Postman works great. I believe the OData service itself is working like it should.

I have an SAPUI5 application that is pointing to the service (called SITEDATA) in the descriptor:

"sap.app": {
    ...,
    "dataSources": {
        "SAM": {
            "uri": "http://localhost:8080/odata/SITEDATA/",
            "type": "OData",
            "settings": {
                "odataVersion": "2.0"
            }
        }
    },...

"sap.ui5": {
    ...,
    "models": {
        ...,
        "perDiem": {
            "dataSource": "SAM"
        }...

I have a very simple view that points to the single table (which is also called SITEDATA):

    <List
    items="{ path : 'perDiem>/SITEDATA' }">
    ...
    <items>
        <ObjectListItem title="{perDiem>SITE_ID}">

When I run the application I can see that the application successfully queries the service for:

http: //localhost:8080/odata/SITEDATA/$metadata

http: //localhost:8080/odata/SITEDATA/SITEDATA?$skip=0&$top=100

...as well as a bunch of other things. But then I get this:

The WildFly log shows that SITEDATA/$batch just doesn't exist. However, localhost:8080/odata/SITEDATA/SITEDATA/$batch works just fine.

And after researching this problem for days it looks like yes, the $batch request should be performed on the table, not the service. So the error makes sense. But I can't find any way to fix this.

Has any one experienced this problem or see anything I need to do to correct it?

Body:
If you want to avoid $batch calls to your backend I suggest you to explicitly declare your model as:

    "perDiem": {
        "type": "sap.ui.model.odata.v2.ODataModel",
        "settings": {
            "defaultOperationMode": "Server",
            "defaultBindingMode": "TwoWay",
            "defaultCountMode": "Inline",
            "useBatch": false
        },
        "dataSource": "SAM",
        "preload": true
    }


问:
Program for communicating with windows named pipes
I am relatively new to named pipes in windows.

I require a windows tool similar to linux's socat for communicating via named pipes. Can Cygwin's socat access windows named pipes? If so, how?

答:
Building on the answer from smichak you can actually use the Putty's plink with socat to get a cygwin pipe:</p>

```<code>socat UNIX-LISTEN:/tmp/openssh-ssh-agent,umask=066,fork EXEC:"PLINK.EXE -serial //./pipe/openssh-ssh-agent",pipes
</code>```

Body:
Building on the answer from smichak you can actually use the Putty's plink with socat to get a cygwin pipe:

socat UNIX-LISTEN:/tmp/openssh-ssh-agent,umask=066,fork EXEC:"PLINK.EXE -serial //./pipe/openssh-ssh-agent",pipes


问:
AngularJS Scope is not accessible through console
I just started learning angular js. I have understanding that we can access and debug scope available to any dom element by selecting/inspecting anywhere on the page and running

```<code>angular.element($0).scope()
</code>```

code on console. But if you try this, I find its value undefined. How they are hiding it and how can I reach to data through console?

答:
Its likley that debugInfoEnabled in $compileProvider is set to false, which means angular.element($0).scope() will always return undefined

You can however run angular.reloadWithDebugInfo in the console which will override this.

Reference:

AngularJS $compileProvider Documentation

AngularJS reloadWithDebugInfo Documentation

Body:
I just started learning angular js. I have understanding that we can access and debug scope available to any dom element by selecting/inspecting anywhere on the page and running

angular.element($0).scope()

code on console. But if you try this, I find its value undefined. How they are hiding it and how can I reach to data through console?


问:
Close and restart the current application in DELPHI
How can I do this one?

For some reason or selected by the user, “ask” the current application to restart it self.

答:
You could have a separate simple restart.exe program that you run from your program and pass it the name of your executable file. Then close your program. The restart program can wait for a time, or until the executable file is read-writeable which seems to mean it is not running, then it can execute it and close itself.

I expect there is a better way to do this, maybe sombody can provide a better solution, but this function seems to tell me whether an executable is currently running:

```<code>function CanReadWriteFile(const f: TFileName): boolean;
var
  i: integer;
begin
  Result := false;
  i := FileOpen(f, fmOpenReadWrite);
  if i >= 0 then begin
    Result := true;
    FileClose(i);
  end;
end;
</code>```

Body:
You could have a separate simple restart.exe program that you run from your program and pass it the name of your executable file. Then close your program. The restart program can wait for a time, or until the executable file is read-writeable which seems to mean it is not running, then it can execute it and close itself.

I expect there is a better way to do this, maybe sombody can provide a better solution, but this function seems to tell me whether an executable is currently running:

function CanReadWriteFile(const f: TFileName): boolean;
var
  i: integer;
begin
  Result := false;
  i := FileOpen(f, fmOpenReadWrite);
  if i >= 0 then begin
    Result := true;
    FileClose(i);
  end;
end;


问:
System.AccessViolationException when handing an array over to a dynamically loaded c++ DLL in C#
I am dynamically loading a DLL originally written in C++ in a C# program and hand over an array as an argument like this:

```<code>// That's only for being able to load the DLL dynamically during runtime
[DllImport(@"C:\Windows\System32\kernel32.dll", EntryPoint = "LoadLibrary")]
public static extern IntPtr LoadLibrary([MarshalAs(UnmanagedType.LPStr)] string dllToLoad);

[DllImport(@"C:\Windows\System32\kernel32.dll", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)]
public static extern IntPtr GetProcAddress(IntPtr hModule, string procedureName);

[DllImport(@"C:\Windows\System32\kernel32.dll", EntryPoint = "FreeLibrary")]
public static extern bool FreeLibrary(IntPtr hModule);

// Delegate with function signature for the DISCON function
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.U4)]
delegate void DisconDelegate(float[] arr);

static void Main(string[] args){
   // Load DLL
   IntPtr _dllhandle = IntPtr.Zero;
   DisconDelegate _discon = null;
   string dllPath = @"D:\myProject\Trivial_discon.dll";

    _dllhandle = LoadLibrary(dllPath);
    var discon_handle = GetProcAddress(_dllhandle, "DISCON");
   _discon = (DisconDelegate)Marshal.GetDelegateForFunctionPointer(discon_handle, typeof(DisconDelegate));

   // create the array and change it after its initialization
   float[] arr = new float[] { 5, 6, 7 };
   arr[0] = 7;

   _discon(arr);
}

</code>```

Note that I change after the initialization once again with arr[0] = 7; an entry of the array. This returns the following error: System.AccessViolationException
  HResult=0x80004003
  Message=Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
  Source=
  StackTrace:

However, if I leave arr[0] = 7; away, it works.

So I am wondering: Why is it problematic to change an entry of the array after the initialization in this context? And how can I fix this problem, i.e., how to change the entries of an array after its initialization and still being able to hand it over as an argument to the DLL?

答:
You need to convert the array from managed memory to unmanaged memory.  Try following </p>

```<code>       static void Main(string[] args)
        {

            Data data = new Data();
            data.arr = new float[] { 5, 6, 7 };
            IntPtr arrPtr = Marshal.AllocHGlobal(data.arr.Length * sizeof(float));
            Marshal.StructureToPtr(data, arrPtr, true);
        }
        [StructLayout(LayoutKind.Sequential)]
        public struct Data
        {

            public float[] arr;
        }
</code>```

Body:
I am dynamically loading a DLL originally written in C++ in a C# program and hand over an array as an argument like this:

// That's only for being able to load the DLL dynamically during runtime
[DllImport(@"C:\Windows\System32\kernel32.dll", EntryPoint = "LoadLibrary")]
public static extern IntPtr LoadLibrary([MarshalAs(UnmanagedType.LPStr)] string dllToLoad);

[DllImport(@"C:\Windows\System32\kernel32.dll", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)]
public static extern IntPtr GetProcAddress(IntPtr hModule, string procedureName);

[DllImport(@"C:\Windows\System32\kernel32.dll", EntryPoint = "FreeLibrary")]
public static extern bool FreeLibrary(IntPtr hModule);

// Delegate with function signature for the DISCON function
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.U4)]
delegate void DisconDelegate(float[] arr);

static void Main(string[] args){
   // Load DLL
   IntPtr _dllhandle = IntPtr.Zero;
   DisconDelegate _discon = null;
   string dllPath = @"D:\myProject\Trivial_discon.dll";

    _dllhandle = LoadLibrary(dllPath);
    var discon_handle = GetProcAddress(_dllhandle, "DISCON");
   _discon = (DisconDelegate)Marshal.GetDelegateForFunctionPointer(discon_handle, typeof(DisconDelegate));

   // create the array and change it after its initialization
   float[] arr = new float[] { 5, 6, 7 };
   arr[0] = 7;

   _discon(arr);
}

Note that I change after the initialization once again with arr[0] = 7; an entry of the array. This returns the following error: System.AccessViolationException
  HResult=0x80004003
  Message=Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
  Source=
  StackTrace:

However, if I leave arr[0] = 7; away, it works.

So I am wondering: Why is it problematic to change an entry of the array after the initialization in this context? And how can I fix this problem, i.e., how to change the entries of an array after its initialization and still being able to hand it over as an argument to the DLL?

Body:
You need to convert the array from managed memory to unmanaged memory.  Try following

       static void Main(string[] args)
        {

            Data data = new Data();
            data.arr = new float[] { 5, 6, 7 };
            IntPtr arrPtr = Marshal.AllocHGlobal(data.arr.Length * sizeof(float));
            Marshal.StructureToPtr(data, arrPtr, true);
        }
        [StructLayout(LayoutKind.Sequential)]
        public struct Data
        {

            public float[] arr;
        }


问:
Aligning UIToolBar items
I have three UIBarButtonItem created as below. They align left and I'd like to align center so there isn't a gap on the right side. I don't see an align property on UIToolBar. Is there another way to accomplish this?

```<code>//create some buttons
UIBarButtonItem *aboutButton = [[UIBarButtonItem alloc] initWithTitle:@"About" style:UIBarButtonItemStyleBordered target:self action:@selector(showAbout:)];
[toolbar setItems:[NSArray arrayWithObjects:settingsButton,deleteButton,aboutButton,nil]];
//Add the toolbar as a subview to the navigation controller.
[self.navigationController.view addSubview:toolbar];
</code>```

答:
Add two UIBarButtonSystemItemFlexibleSpace items to your toolbar, to the left and right of your items

```<code>UIBarButtonItem *flexibleSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
[toolbar setItems:[NSArray arrayWithObjects:flexibleSpace, settingsButton,deleteButton,aboutButton, flexibleSpace, nil]];
</code>```

Adding these as you would any other toolbar items will distribute space evenly between the two of them.

Title: Aligning UIToolBar items

Body:
I have three UIBarButtonItem created as below. They align left and I'd like to align center so there isn't a gap on the right side. I don't see an align property on UIToolBar. Is there another way to accomplish this?

//create some buttons
UIBarButtonItem *aboutButton = [[UIBarButtonItem alloc] initWithTitle:@"About" style:UIBarButtonItemStyleBordered target:self action:@selector(showAbout:)];
[toolbar setItems:[NSArray arrayWithObjects:settingsButton,deleteButton,aboutButton,nil]];
//Add the toolbar as a subview to the navigation controller.
[self.navigationController.view addSubview:toolbar];

Body:
Add two UIBarButtonSystemItemFlexibleSpace items to your toolbar, to the left and right of your items

UIBarButtonItem *flexibleSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
[toolbar setItems:[NSArray arrayWithObjects:flexibleSpace, settingsButton,deleteButton,aboutButton, flexibleSpace, nil]];

Adding these as you would any other toolbar items will distribute space evenly between the two of them.

OwnerDisplayName: nduplessis


问:
How to compute 'Mode' as in Mean, Median Mode using BEX?
Have any one explored how to perform Mode (one of the 3 challenges.. Mean, Median & Mode) using SAP BEx Query Designer/WAD (no BO tools). Any inputs to compute Mode for a data set would be very helpful.

答:
Apologies if this is unhelpful (not knowing BEx), but in langauges that dont have a sense of order you need to create an extra column which stores the 'order' of the data. Then count the number of observations you have, if it is odd then choose the value related to the observation which = int(observation count)/2+1. Otherwise if it is even, then you (usually) take the mean of the int(observation count)/2 and int(observation count)/2+1 rows.

e.g.1

data =1,3,4,8,8,9,9

order=1,2,3,4,5,6,7

odd number of observations
median = int(7/2)+1 = 3rd observation which is 8

e.g.2

data =1,3,4,5,8,8,9,9

order=1,2,3,4,5,6,7,8

even number of observations
median is between the = int(8/2) and the int(8/2)+1 observations = 4th and 5th observations, which is the mean of 5 and 8 = 6.5

I could write a query in SQL Server to paste in, but not sure if that would be helpful. Let me know ...