问:
Proper why to bind a function with parameters to child component in React Native
I am still new to React Native and I struggle a bit with the programming paradigm. What I am trying to do (by following the structure of another React.js project) is to create a container (parent component) which contains a number of other components. My ultimate goal is to pass and handle all of the props in the parent component. Child component only shows them. My structure looks something like this:

```<code>export default class TemporaryCardRequestScreen extends React.Component {
    constructor(props) {
        super(props);
        this.showDateTimePicker = this.showDateTimePicker.bind(this);
        this.hideDateTimePicker = this.hideDateTimePicker.bind(this);
        this.handleDatePicked = this.handleDatePicked.bind(this);

        this.state.fromDateTime = {
            isVisible: false,
            value: new Date()
        }
    }

    showDateTimePicker = () => { /*body*/ };

    hideDateTimePicker = () => { /*body*/ };

    handleDatePicked = date => { /*body*/ };

    render() {
        return (
            <DateTimePickerComponent
                isVisible={this.state.fromDateTime.isVisible}
                onConfirmPressed={this.handleDatePicked}
                onCancelPressed={this.hideDateTimePicker}
                showDateTimePicker={this.showDateTimePicker}
                value={this.state.fromDateTime.value}
            />
        );
    }
}
</code>```

and the, my child component looks something like this:

```<code>// npm ref.: https://github.com/mmazzarolo/react-native-modal-datetime-picker
export default class DateTimePickerComponent extends Component {
    constructor(props) {
      super(props);
    }

    render() {
        const {
            isVisible,
            onConfirmPressed,
            onCancelPressed,
            showDateTimePicker } = this.props;

        return (
            <>
            <Button title="Show DatePicker" onPress={showDateTimePicker} />
            <DateTimePicker
                isVisible={isVisible}
                onConfirm={onConfirmPressed}
                onCancel={onCancelPressed}
                mode='datetime'
                is24Hour={false}
                date={new Date()}
            />
        </>
      );
    }
  }
</code>```

My focus now is on

```<code>onConfirmPressed={this.handleDatePicked}
</code>```

currently, this.handleDatePicked accepts a single argument but I'd like it to accept one additional which is passed to it at the place being used in child component.

So, my ultimate goal would be to have something similar to this:

```<code>render() {
        const {
            isVisible,
            onConfirmPressed,
            onCancelPressed,
            showDateTimePicker,
            dateTimePickerId } = this.props;

        return (
            <>
            <Button title="Show DatePicker" onPress={this.showDateTimePicker} />
            <DateTimePicker
                isVisible={isVisible}
                onConfirm={onConfirmPressed(dateTimePickerId)}
                onCancel={onCancelPressed}
                mode='datetime'
                is24Hour={false}
                date={new Date()}
            />
        </>
      );
    }
</code>```

So, in this way, in my parent component I could have a single method which can handle the updates for a number of date time pickers in my container (This is actually my use-case). Instead of having the same type of handlers (with different property name) for pretty much the same thing.

UPDATE: Snack expo

答:
You can capture 'onConfirm' of DateTimePickerComponent, then call parent function and pass in the dateTimePickerId.

TemporaryCardRequestScreen

```<code>// Modify to accept 2 arguments
handleDatePicked = (id, date) => {
    if (id == "1") {
        // code here
    }
    else if (id == "2") {
        // code here
    }
};
render() {
    return (
        <div>
            <DateTimePickerComponent
                isVisible={this.state.fromDateTime.isVisible}
                onConfirmPressed={this.handleDatePicked}
                onCancelPressed={this.hideDateTimePicker}
                showDateTimePicker={this.showDateTimePicker}
                value={this.state.fromDateTime.value}
                dateTimePickerId="1"
            />
            <DateTimePickerComponent
                isVisible={this.state.fromDateTime.isVisible}
                onConfirmPressed={this.handleDatePicked}
                onCancelPressed={this.hideDateTimePicker}
                showDateTimePicker={this.showDateTimePicker}
                value={this.state.fromDateTime.value}
                dateTimePickerId="2}
            />
        </div>

        );
    }
</code>```

DateTimePickerComponent

```<code>onMyCustomConfirmPressed = (date) => {
    // Parent onConfirmPressed() shall accept 2 arguments
    this.props.onConfirmPressed(this.props.dateTimePickerId, date)
}

render() {
    const {
        isVisible,
        onConfirmPressed,
        onCancelPressed,
        showDateTimePicker,
        dateTimePickerId } = this.props;

    return (
        <>
        <Button title="Show DatePicker" onPress={this.showDateTimePicker} />
        <DateTimePicker
            isVisible={isVisible}
            onConfirm={this.onMyCustomConfirmPressed}
            onCancel={onCancelPressed}
            mode='datetime'
            is24Hour={false}
            date={new Date()}
        />
        </>
    );
}
</code>```

Body:
I am still new to React Native and I struggle a bit with the programming paradigm. What I am trying to do (by following the structure of another React.js project) is to create a container (parent component) which contains a number of other components. My ultimate goal is to pass and handle all of the props in the parent component. Child component only shows them. My structure looks something like this:

export default class TemporaryCardRequestScreen extends React.Component {
    constructor(props) {
        super(props);
        this.showDateTimePicker = this.showDateTimePicker.bind(this);
        this.hideDateTimePicker = this.hideDateTimePicker.bind(this);
        this.handleDatePicked = this.handleDatePicked.bind(this);

        this.state.fromDateTime = {
            isVisible: false,
            value: new Date()
        }
    }

    showDateTimePicker = () => { /*body*/ };

    hideDateTimePicker = () => { /*body*/ };

    handleDatePicked = date => { /*body*/ };

    render() {
        return (
            <DateTimePickerComponent
                isVisible={this.state.fromDateTime.isVisible}
                onConfirmPressed={this.handleDatePicked}
                onCancelPressed={this.hideDateTimePicker}
                showDateTimePicker={this.showDateTimePicker}
                value={this.state.fromDateTime.value}
            />
        );
    }
}

and the, my child component looks something like this:

// npm ref.: https://github.com/mmazzarolo/react-native-modal-datetime-picker
export default class DateTimePickerComponent extends Component {
    constructor(props) {
      super(props);
    }

    render() {
        const {
            isVisible,
            onConfirmPressed,
            onCancelPressed,
            showDateTimePicker } = this.props;

        return (
            <>
            <Button title="Show DatePicker" onPress={showDateTimePicker} />
            <DateTimePicker
                isVisible={isVisible}
                onConfirm={onConfirmPressed}
                onCancel={onCancelPressed}
                mode='datetime'
                is24Hour={false}
                date={new Date()}
            />
        </>
      );
    }
  }

My focus now is on

onConfirmPressed={this.handleDatePicked}

currently, this.handleDatePicked accepts a single argument but I'd like it to accept one additional which is passed to it at the place being used in child component.

So, my ultimate goal would be to have something similar to this:

render() {
        const {
            isVisible,
            onConfirmPressed,
            onCancelPressed,
            showDateTimePicker,
            dateTimePickerId } = this.props;

        return (
            <>
            <Button title="Show DatePicker" onPress={this.showDateTimePicker} />
            <DateTimePicker
                isVisible={isVisible}
                onConfirm={onConfirmPressed(dateTimePickerId)}
                onCancel={onCancelPressed}
                mode='datetime'
                is24Hour={false}
                date={new Date()}
            />
        </>
      );
    }

So, in this way, in my parent component I could have a single method which can handle the updates for a number of date time pickers in my container (This is actually my use-case). Instead of having the same type of handlers (with different property name) for pretty much the same thing.

UPDATE: Snack expo

Body:
You can capture 'onConfirm' of DateTimePickerComponent, then call parent function and pass in the dateTimePickerId.

TemporaryCardRequestScreen

// Modify to accept 2 arguments
handleDatePicked = (id, date) => {
    if (id == "1") {
        // code here
    }
    else if (id == "2") {
        // code here
    }
};
render() {
    return (
        <div>
            <DateTimePickerComponent
                isVisible={this.state.fromDateTime.isVisible}
                onConfirmPressed={this.handleDatePicked}
                onCancelPressed={this.hideDateTimePicker}
                showDateTimePicker={this.showDateTimePicker}
                value={this.state.fromDateTime.value}
                dateTimePickerId="1"
            />
            <DateTimePickerComponent
                isVisible={this.state.fromDateTime.isVisible}
                onConfirmPressed={this.handleDatePicked}
                onCancelPressed={this.hideDateTimePicker}
                showDateTimePicker={this.showDateTimePicker}
                value={this.state.fromDateTime.value}
                dateTimePickerId="2}
            />
        </div>

        );
    }

DateTimePickerComponent

onMyCustomConfirmPressed = (date) => {
    // Parent onConfirmPressed() shall accept 2 arguments
    this.props.onConfirmPressed(this.props.dateTimePickerId, date)
}

render() {
    const {
        isVisible,
        onConfirmPressed,
        onCancelPressed,
        showDateTimePicker,
        dateTimePickerId } = this.props;

    return (
        <>
        <Button title="Show DatePicker" onPress={this.showDateTimePicker} />
        <DateTimePicker
            isVisible={isVisible}
            onConfirm={this.onMyCustomConfirmPressed}
            onCancel={onCancelPressed}
            mode='datetime'
            is24Hour={false}
            date={new Date()}
        />
        </>
    );
}


来源: stackexchange

问:
How to Deploy Angular 7 Project to Google Cloud
I have built an Angular 7 application that works nicely when I do the ng serve command from my local mac or from a remote centos server.

This application is using php files that access MySQL data base both served on my google cloud.

Now after doing the gcloud app deploy the last thing I see on the screen is the message:

nebula@0.0.0 start /app
  ng serve

sh: 1: ng: not found

and I am dead in the water.

I have tried so many different versions of app.yaml and cloudbuild.yaml file that I feel like i have not learned anything.

I have tried the same thing by starting with the very basic "Hero's" app and get the same issue.

i.e.

ng new xxx
  cd xxx
  npm install
  ng serve

Then I see the default Heros screen in my browser.

I then create this app.yaml file

```<code>runtime: nodejs
env: flex

manual_scaling:
  instances: 1
resources:
  cpu: 1
  memory_gb: 0.5
  disk_size_gb: 10

service:
  xxx
</code>```

I then try to deploy using:

gcloud app deploy

When this finishes I get the message

Deployed service [xxx] to [https://xxx-dot-project.appspot.com]

When I go to that url, I get:

Error: Server Error

The server encountered an error and could not complete your request.
Please try again in 30 seconds.

The log file for this run is:

```<code>    gcloud app logs tail -s xxx
    Waiting for new log entries...
    2019-05-04 15:27:35 xxx[20190504t102436]  "GET / HTTP/1.1" 404
    2019-05-04 15:27:35 xxx[20190504t102436]  "GET /favicon.ico HTTP/1.1" 404
    2019-05-04 15:28:56 xxx[20190504t102436]  "GET / HTTP/1.1" 404
    2019-05-04 15:32:45 xxx[prod]  "GET / HTTP/1.1" 404
    2019-05-04 15:32:50 xxx[prod]  "GET / HTTP/1.1" 404
    2019-05-04 15:33:06 xxx[prod]  "GET / HTTP/1.1" 404
    2019-05-04 15:33:10 xxx[prod]  "GET /run HTTP/1.1" 404
    2019-05-04 15:33:10 xxx[prod]  "GET /favicon.ico HTTP/1.1" 404
    2019-05-04 15:33:16 xxx[prod]  "GET /run HTTP/1.1" 404
    2019-05-04 15:33:16 xxx[prod]  "GET / HTTP/1.1" 404
    2019-05-04 15:33:19 xxx[prod]  "GET /login HTTP/1.1" 404
    2019-05-04 15:33:19 xxx[prod]  "GET /favicon.ico HTTP/1.1" 404
    2019-05-04 15:40:43 xxx[prod]  "GET /login HTTP/1.1" 404
    2019-05-04 15:40:46 xxx[prod]  "GET /login HTTP/1.1" 404
    2019-05-04 15:40:50 xxx[prod]  "GET /login HTTP/1.1" 404
    2019-05-04 15:40:50 xxx[prod]  "GET / HTTP/1.1" 404
    2019-05-04 15:40:53 xxx[prod]  "GET / HTTP/1.1" 404
    2019-05-04 16:01:50 xxx[20190504t105955]  "GET / HTTP/1.1" 500
    2019-05-04 16:01:51 xxx[20190504t105955]  /bin/sh: 1: ng: not found
    2019-05-04 16:06:19 xxx[20190504t105955]  "GET / HTTP/1.1" 500
    2019-05-04 16:06:20 xxx[20190504t105955]  /bin/sh: 1: ng: not found
</code>```

My question is can someone provide a trivial example of this process where the application runs in the google cloud?

答:
Looks like the suggestion to go to firebase was the most useable option.

I am a lot closer to where I want to be and I now see a lot of useful extras.

ContentLicense: CC BY-SA 4.0

Body:
I have built an Angular 7 application that works nicely when I do the ng serve command from my local mac or from a remote centos server.

This application is using php files that access MySQL data base both served on my google cloud.

Now after doing the gcloud app deploy the last thing I see on the screen is the message:

nebula@0.0.0 start /app
  ng serve

sh: 1: ng: not found

and I am dead in the water.

I have tried so many different versions of app.yaml and cloudbuild.yaml file that I feel like i have not learned anything.

I have tried the same thing by starting with the very basic "Hero's" app and get the same issue.

i.e.

ng new xxx
  cd xxx
  npm install
  ng serve

Then I see the default Heros screen in my browser.

I then create this app.yaml file

runtime: nodejs
env: flex

manual_scaling:
  instances: 1
resources:
  cpu: 1
  memory_gb: 0.5
  disk_size_gb: 10

service:
  xxx

I then try to deploy using:

gcloud app deploy

When this finishes I get the message

Deployed service [xxx] to [https://xxx-dot-project.appspot.com]

When I go to that url, I get:

Error: Server Error

The server encountered an error and could not complete your request.
Please try again in 30 seconds.

The log file for this run is:

    gcloud app logs tail -s xxx
    Waiting for new log entries...
    2019-05-04 15:27:35 xxx[20190504t102436]  "GET / HTTP/1.1" 404
    2019-05-04 15:27:35 xxx[20190504t102436]  "GET /favicon.ico HTTP/1.1" 404
    2019-05-04 15:28:56 xxx[20190504t102436]  "GET / HTTP/1.1" 404
    2019-05-04 15:32:45 xxx[prod]  "GET / HTTP/1.1" 404
    2019-05-04 15:32:50 xxx[prod]  "GET / HTTP/1.1" 404
    2019-05-04 15:33:06 xxx[prod]  "GET / HTTP/1.1" 404
    2019-05-04 15:33:10 xxx[prod]  "GET /run HTTP/1.1" 404
    2019-05-04 15:33:10 xxx[prod]  "GET /favicon.ico HTTP/1.1" 404
    2019-05-04 15:33:16 xxx[prod]  "GET /run HTTP/1.1" 404
    2019-05-04 15:33:16 xxx[prod]  "GET / HTTP/1.1" 404
    2019-05-04 15:33:19 xxx[prod]  "GET /login HTTP/1.1" 404
    2019-05-04 15:33:19 xxx[prod]  "GET /favicon.ico HTTP/1.1" 404
    2019-05-04 15:40:43 xxx[prod]  "GET /login HTTP/1.1" 404
    2019-05-04 15:40:46 xxx[prod]  "GET /login HTTP/1.1" 404
    2019-05-04 15:40:50 xxx[prod]  "GET /login HTTP/1.1" 404
    2019-05-04 15:40:50 xxx[prod]  "GET / HTTP/1.1" 404
    2019-05-04 15:40:53 xxx[prod]  "GET / HTTP/1.1" 404
    2019-05-04 16:01:50 xxx[20190504t105955]  "GET / HTTP/1.1" 500
    2019-05-04 16:01:51 xxx[20190504t105955]  /bin/sh: 1: ng: not found
    2019-05-04 16:06:19 xxx[20190504t105955]  "GET / HTTP/1.1" 500
    2019-05-04 16:06:20 xxx[20190504t105955]  /bin/sh: 1: ng: not found

My question is can someone provide a trivial example of this process where the application runs in the google cloud?


问:
how would you explain following javascript snippet?

function d() {
  console.log(j)
}

let e = () => console.log(j);

(function() {
  let j = 3;
  d();
  e();
})();```

It will log 3 for both function execution.

So can we assume, that whenever a javascript function executes, it will try to resolve the variable from parent scope, if not in current scope?

答:
A closure is formed when a function is declared inside another function not when the function is called inside another function.

Or you can say.

The variables available to function are the those which are declared in their parent function where they are declared not where they are called.

Body:
function d() {
  console.log(j)
}

let e = () => console.log(j);

(function() {
  let j = 3;
  d();
  e();
})();

It will log 3 for both function execution.

So can we assume, that whenever a javascript function executes, it will try to resolve the variable from parent scope, if not in current scope?


问:
Are different boto3 versions better suited for different Python versions?
According to the boto3 documentation, boto3 is backwards compatible with Python 2.7 & Python 3. I've been running into a few issues that some Python versions weren't completely compatible with certain versions of boto3.

I was wondering if there is:

a boto3 version that is best suited for Python 2.7

a boto3 version that is best suited for Python 3.6

a boto3 version that is best suited for Python 3.7

or if the latest boto3 version should technically work for all versions of Python?

I've read through the boto3 documentation and repository to see if any information is given on this, but could not find any relative information other than it should be compatible to all versions.

答: No, you always want the latest version of Boto3 so you will have access to all the latest Amazon services and features.</p>


问:
Why Sleuth doesn't work with Log4j2 in my Spring Boot service
I have one question - why Sleuth doesn't work with Log4j2? I have excluded default logging library and added Log4j2 to use some other features like these in application.properties filr"

```<code>logging.file=myservice.log
logging.file.max-size= 500MB
logging.file.max-history=14
logging.level.pl.utlimo.*=INFO
</code>```

My pom:

```<code>   <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>Greenwich.RELEASE</spring-cloud.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-sleuth</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-log4j2</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
        </repository>
    </repositories>

</project>
</code>```

I really spent many hours to find solution for my problem. What should I do to use Log4j2 with Sleuth? Now Sleuth doesn't trace anything.

Thank you very much for your help.
Matthew

答:
In your log4j2.xml, try to add following.

```<code><PatternLayout pattern="[%d{yyy-MM-dd HH:mm:ss:SSS}] [%X{X-B3-TraceId},%X{X-B3-SpanId},%X{X-B3-ParentSpanId},%X{X-Span-Export}] [%p] - %l - %m%n"/>
</code>```

Then for some reason, specify the log4j2.xml path in your application.yml

```<code>logging.config=path/to/log4j2.xml
</code>```

Good luck!

Body:
I have one question - why Sleuth doesn't work with Log4j2? I have excluded default logging library and added Log4j2 to use some other features like these in application.properties filr"

logging.file=myservice.log
logging.file.max-size= 500MB
logging.file.max-history=14
logging.level.pl.utlimo.*=INFO

My pom:

   <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.2.RELEASE</version>
        <relativePath/>
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>Greenwich.RELEASE</spring-cloud.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-sleuth</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-log4j2</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
        </repository>
    </repositories>

</project>

I really spent many hours to find solution for my problem. What should I do to use Log4j2 with Sleuth? Now Sleuth doesn't trace anything.

Thank you very much for your help.
Matthew

Body:
In your log4j2.xml, try to add following.

<PatternLayout pattern="[%d{yyy-MM-dd HH:mm:ss:SSS}] [%X{X-B3-TraceId},%X{X-B3-SpanId},%X{X-B3-ParentSpanId},%X{X-Span-Export}] [%p] - %l - %m%n"/>

Then for some reason, specify the log4j2.xml path in your application.yml

logging.config=path/to/log4j2.xml

Good luck!


问:
SQL: count last equal values
I need to solve this problem in pure SQL:
I have to count all the records with a specific value:
In my table there is a column flag with values 0 or 1. I need to count all the 1 after last 0 and sum the amount column values of those records.

Example:

```<code>Flag | Amount

0    | 5
1    | 8
0    | 10
1    | 20
1    | 30
</code>```

Output:

```<code>2    | 50
</code>```

If last value is 0 I don't need to do anything.
I hasten that I need to perform a fast query (possibly accessing just one time).

答:
If your table may not contain any zeros, then you are safer with:

```<code>select count(*) as cnt, sum(Amount) as Amount
from t
where Amount > all (select Amount from t where Flag = 0)
</code>```

Or, using window functions:

```<code>select count(*) as cnt, sum(amount) as amount
from (select t.*, max(case when flag = 0 then amount end) as flag0_amount
      from t
     ) t
where flag0_amount is null or amount > flag0_amount
</code>```

Title: SQL: count last equal values

Body:
I need to solve this problem in pure SQL:
I have to count all the records with a specific value:
In my table there is a column flag with values 0 or 1. I need to count all the 1 after last 0 and sum the amount column values of those records.

Example:

Flag | Amount

0    | 5
1    | 8
0    | 10
1    | 20
1    | 30

Output:

2    | 50

If last value is 0 I don't need to do anything.
I hasten that I need to perform a fast query (possibly accessing just one time).

Body:
If your table may not contain any zeros, then you are safer with:

select count(*) as cnt, sum(Amount) as Amount
from t
where Amount > all (select Amount from t where Flag = 0)

Or, using window functions:

select count(*) as cnt, sum(amount) as amount
from (select t.*, max(case when flag = 0 then amount end) as flag0_amount
      from t
     ) t
where flag0_amount is null or amount > flag0_amount


问:
Multiple Spring profiles with different names
I have a Spring Boot application and I have application.yml for properties. I have multiple profiles in the same file like below:

```<code>spring:
  profiles: dev
property:
  one: bla
  two: blabla

---

spring:
  profiles: preProd, prod
another-property:
  fist: bla
  secong: blabla

---

spring:
  profiles: prod
property:
  one: prod-bla
  two: prod-blabla
</code>```

So my question is when I run applicaiton with prod profile only does Spring merge both profiles and I can see both property and another-propertyin the app?

答:
Merging works perfectly!

given:

```<code>@SpringBootApplication
public class SoYamlSpringProfileMergeApplication {

    private final Data data;

    public SoYamlSpringProfileMergeApplication(Data data) {
        this.data = data;
    }

    @EventListener(ApplicationReadyEvent.class)
    public void showData() {
      System.err.println(data.getOne());
      System.err.println(data.getTwo());
      System.err.println(data.getThree());
    }

    public static void main(String[] args) {
        SpringApplication.run(SoYamlSpringProfileMergeApplication.class, args);
    }

}

@Component
@ConfigurationProperties(prefix = "data")
class Data {

    private String one = "one default";

    private String two = "two default";

    private String three = "three default";

    public String getOne() {
        return one;
    }

    public String getTwo() {
        return two;
    }

    public String getThree() {
        return three;
    }

    public void setOne(String one) {
        this.one = one;
    }

    public void setTwo(String two) {
        this.two = two;
    }

    public void setThree(String three) {
        this.three = three;
    }
}
</code>```

and

```<code>spring:
  profiles:
    active: "other"

---

spring:
  profiles: dev

data:
  one: one dev
  two: two dev

---

spring:
  profiles: prod

data:
  one: one prod
  two: two prod

---

spring:
  profiles: other

data:
  three: three other
</code>```

will print:

```<code>one dev
two dev
three other
</code>```

and with:

```<code>spring:
  profiles:
    active: "other,prod"
</code>```

```<code>one prod
two prod
three other
</code>```

important the order of active:"other,prod" matters!

using

```<code>spring:
  profiles:
    active: "prod,other"
</code>```

will output

```<code>one dev
two dev
three other
</code>```

load props from 'prod'

merge with props 'other' merges the dev-values

Body:
I have a Spring Boot application and I have application.yml for properties. I have multiple profiles in the same file like below:

spring:
  profiles: dev
property:
  one: bla
  two: blabla

---

spring:
  profiles: preProd, prod
another-property:
  fist: bla
  secong: blabla

---

spring:
  profiles: prod
property:
  one: prod-bla
  two: prod-blabla

So my question is when I run applicaiton with prod profile only does Spring merge both profiles and I can see both property and another-propertyin the app?

Body:
Merging works perfectly!

given:

@SpringBootApplication
public class SoYamlSpringProfileMergeApplication {

    private final Data data;

    public SoYamlSpringProfileMergeApplication(Data data) {
        this.data = data;
    }

    @EventListener(ApplicationReadyEvent.class)
    public void showData() {
      System.err.println(data.getOne());
      System.err.println(data.getTwo());
      System.err.println(data.getThree());
    }

    public static void main(String[] args) {
        SpringApplication.run(SoYamlSpringProfileMergeApplication.class, args);
    }

}

@Component
@ConfigurationProperties(prefix = "data")
class Data {

    private String one = "one default";

    private String two = "two default";

    private String three = "three default";

    public String getOne() {
        return one;
    }

    public String getTwo() {
        return two;
    }

    public String getThree() {
        return three;
    }

    public void setOne(String one) {
        this.one = one;
    }

    public void setTwo(String two) {
        this.two = two;
    }

    public void setThree(String three) {
        this.three = three;
    }
}

and

spring:
  profiles:
    active: "other"

---

spring:
  profiles: dev

data:
  one: one dev
  two: two dev

---

spring:
  profiles: prod

data:
  one: one prod
  two: two prod

---

spring:
  profiles: other

data:
  three: three other

will print:

one dev
two dev
three other

and with:

spring:
  profiles:
    active: "other,prod"

one prod
two prod
three other

important the order of active:"other,prod" matters!

using

spring:
  profiles:
    active: "prod,other"

will output

one dev
two dev
three other

load props from 'prod'

merge with props 'other' merges the dev-values


问:
how to choose dynamic fetchSize in MyBatis
We would like to set the fetchSize on particular query dynamically so that size-value can be passed at run-time based on the preconditions like total threads open etc..

Currently we are using MyBatis 3.4 ilbrary.

Below is the snapshot of query we are using in our application.

```<code><select id="fetchDetails" resultType="ItemInformation" useCache="true" timeout="100000" fetchSize="50" statementType="PREPARED">

  SELECT * FROM PR_STAGE
  where 1=1
    AND release_date >= sys_extract_utc(FROM_TZ(cast(TO_DATE(#{fromDate}, 'DD-MON-YYYY HH24:MI:SS')as timestamp),'America/Los_Angeles') )
    AND release_date <= sys_extract_utc(FROM_TZ(cast(TO_DATE(#{toDate}, 'DD-MON-YYYY HH24:MI:SS')as timestamp),'America/Los_Angeles') )

</select>
</code>```

答:
You can write a plugin.

import java.sql.Statement;
import java.util.Properties;

import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;

@Intercepts(@Signature(
  type = StatementHandler.class,
  method = "query",
  args = {
    Statement.class,
    ResultHandler.class }))
public class FetchSizePlugin implements Interceptor {

  private static final ThreadLocal<Integer> FETCH_SIZE =
      ThreadLocal.withInitial(() -> 100);

  public static void setFetchSize(int fetchSize) {
    FETCH_SIZE.set(Integer.valueOf(fetchSize));
  }

  @Override
  public Object intercept(Invocation invocation) throws Throwable {
    Statement statement = (Statement) invocation.getArgs()[0];
    statement.setFetchSize(FETCH_SIZE.get());
    return invocation.proceed();
  }

  @Override
  public Object plugin(Object target) {
    return Plugin.wrap(target, this);
  }

  @Override
  public void setProperties(Properties properties) {
  }
}
```

<p>To register the plugin, add the following entry to the XML config ...</p>

<pre class="lang-xml prettyprint-override"><code><plugins>
  <plugin interceptor="pkg.FetchSizePlugin" />
</plugins>
</code>```

... or call org.apache.ibatis.session.Configuration#addInterceptor().

Once the plugin is registered, you can set the fetch size by calling FetchSizePlugin.setFetchSize() before executing a query.

If you don't call the method, the value set via withInitial() will be used.

As it uses ThreadLocal, the fetch size you set will be applied to all the subsequent queries in the same thread unless you re-set another value.

Body:
We would like to set the fetchSize on particular query dynamically so that size-value can be passed at run-time based on the preconditions like total threads open etc..

Currently we are using MyBatis 3.4 ilbrary.

Below is the snapshot of query we are using in our application.

<select id="fetchDetails" resultType="ItemInformation" useCache="true" timeout="100000" fetchSize="50" statementType="PREPARED">

  SELECT * FROM PR_STAGE
  where 1=1
    AND release_date >= sys_extract_utc(FROM_TZ(cast(TO_DATE(#{fromDate}, 'DD-MON-YYYY HH24:MI:SS')as timestamp),'America/Los_Angeles') )
    AND release_date <= sys_extract_utc(FROM_TZ(cast(TO_DATE(#{toDate}, 'DD-MON-YYYY HH24:MI:SS')as timestamp),'America/Los_Angeles') )

</select>

Body:
You can write a plugin.

import java.sql.Statement;
import java.util.Properties;

import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;

@Intercepts(@Signature(
  type = StatementHandler.class,
  method = "query",
  args = {
    Statement.class,
    ResultHandler.class }))
public class FetchSizePlugin implements Interceptor {

  private static final ThreadLocal<Integer> FETCH_SIZE =
      ThreadLocal.withInitial(() -> 100);

  public static void setFetchSize(int fetchSize) {
    FETCH_SIZE.set(Integer.valueOf(fetchSize));
  }

  @Override
  public Object intercept(Invocation invocation) throws Throwable {
    Statement statement = (Statement) invocation.getArgs()[0];
    statement.setFetchSize(FETCH_SIZE.get());
    return invocation.proceed();
  }

  @Override
  public Object plugin(Object target) {
    return Plugin.wrap(target, this);
  }

  @Override
  public void setProperties(Properties properties) {
  }
}

To register the plugin, add the following entry to the XML config ...

<plugins>
  <plugin interceptor="pkg.FetchSizePlugin" />
</plugins>

... or call org.apache.ibatis.session.Configuration#addInterceptor().

Once the plugin is registered, you can set the fetch size by calling FetchSizePlugin.setFetchSize() before executing a query.

If you don't call the method, the value set via withInitial() will be used.

As it uses ThreadLocal, the fetch size you set will be applied to all the subsequent queries in the same thread unless you re-set another value.


问:
how to order column in Multi-columns index for best performance in Mysql
Let's say I have transactions table in a mysql database, I want to create a multi-column index on 3 columns reference, kind and status.
I have this request that I am trying to speed up :
Transaction.where(parent_ref: merchant_ref, kind: 'OFFER',status: 1)                                which performs the following SQL :

```<code>SELECT `merchant_transactions`.* FROM `merchant_transactions`
WHERE `merchant_transactions`.`parent_ref` = '1-0001'
 AND `merchant_transactions`.`kind` = 'BATCH_BET'
 AND `merchant_transactions`.`status` = 1
</code>```

The parent_ref column can take a really wide variety of values so if I have 1M records in that table I will have 500K different references. Status can only take 6 different values and kind only 3.
What will be the best order for the columns in my index for optimal performance.
Does the spread of values in my columns have an impact ? intuitively I would say that I would need to start with the column with the lowest spread of values. In that example I would thus do index(kind, status, reference).
Are there any other factors related to the values in my tables to take into account when figuring out the order of columns for my index ?

答:
Okay, now that you've shared the query, we can see that you reference all three columns in your WHERE clause, all three predicates are doing equality comparisons, and the expression in the WHERE clause uses only AND operations.

There are no more exotic parts of the query like JOIN, GROUP BY, ORDER BY, DISTINCT, etc. to complicate the optimization of this query.

Given these conditions, my experience is that the order of columns hardly matters. If there's any difference, it's barely perceptible.

I'd put the column that is unique first, based on some assumption that it's most selective and therefore narrows down the search most effectively. But I'm not sure it would make any noticeable difference either way.

Body:
Let's say I have transactions table in a mysql database, I want to create a multi-column index on 3 columns reference, kind and status.
I have this request that I am trying to speed up :
Transaction.where(parent_ref: merchant_ref, kind: 'OFFER',status: 1)                                which performs the following SQL :

SELECT `merchant_transactions`.* FROM `merchant_transactions`
WHERE `merchant_transactions`.`parent_ref` = '1-0001'
 AND `merchant_transactions`.`kind` = 'BATCH_BET'
 AND `merchant_transactions`.`status` = 1

The parent_ref column can take a really wide variety of values so if I have 1M records in that table I will have 500K different references. Status can only take 6 different values and kind only 3.
What will be the best order for the columns in my index for optimal performance.
Does the spread of values in my columns have an impact ? intuitively I would say that I would need to start with the column with the lowest spread of values. In that example I would thus do index(kind, status, reference).
Are there any other factors related to the values in my tables to take into account when figuring out the order of columns for my index ?


问:
Replace shutdown with hibernate
Tl;dr: Is it possible to catch system shutdown messages (and alter/remove them) before they are being processed?

Preliminary

I am working on a cluster management software. Right now, idle machines in the cluster are being shut down by a third party software. In the environment my software is tested with, it is not acceptable to lose a lot of time on shutting down, booting up and starting all the programs. As a result, the point at which a machine is considered to be idle has been set to something like 3 hours. This is not really "power saving".

The idea is to replace the systems shutdown message with a hibernate message.
The OS is Windows XP but an update to Windows 7 is planned. So ideally, the solution should work on both.

Ideas so far

Replace shutdown.exe

This is how I did it with the UNIX clients. However, I don't think that common Windows applications just calls exec() on shutdown.exe to get the system to shut down. Instead, they probably call ExitWindowsEx(). I want to catch the messages resulting from this call as well.

Handling WM_QUERYENDSESSION

This is not a solution, either, for two reasons:

This message is delivered to all running programs in an unpredictable order. Even if I cancel the shutdown by returning FALSE, some programs might have gotten the message earlier and exited already.

Since Vista, returning FALSE does not result in a silent cancellation of the shutdown. Instead, the whole screen is blocked and the user is informed about the program(s) blocking the shutdown. So even if I manage to go into hibernate at this point, at the next startup the whole screen is blocked.

Especially the first point is crucial. I can only justify shutting down the machines if it doesn't cost precious time. Not having to restart the programs when returning from hibernate is a big part of that.

SetWindowsHookEx()

I thought about hooks. However, this method seems quite painful, since this MSDN article states, that I would have to deliver both my program and the DLL containing the hook in both flavors (x86_64 and x86). This is bound to fail.

But let's assume I manage to get this to work, I cannot seem to catch the system's shutdown message before it's being dispatched to other windows, let alone alter or delete that message.

Restrictions

There are basically no restrictions. Since the Windows running on those machine is being installed by myself, anything goes. If a hand-crafted mouse driver, which simulates mouse movement to click the "Ok, don't shutdown" button is the solution, so be it (another indicator, that I'm not trying to do evil ;) ). The more general the solution (e.g. being able to intercept and alter any message), the better!

Any hints and links (untested, experimental stuff) are appreciated.

答:
Here are the steps you need to do to prevent the shutdown

Write a DLL that captures and redirects the ExitWindowsEx() function. You can accomplish this using Microsoft Detours Library. Test this dll in your test process.

Once you have tested your dll, have that DLL load into every process by default using AppInit_Dlls registry value or use the utilities provided by detours package to selectively load the DLL into any process you want.

Write a process that uses one of the IPC mechanism to communicate with your DLL loaded in all the process to allow/deny/redirect the shutdown.

ContentLicense: CC BY-SA 2.5

Title: Replace shutdown with hibernate


问:
Chrome DevTools Devices does not detect device when plugged in
I cannot seem to get the DevTools Devices feature to work on my Samsung Galaxy S4 even after following the steps outlined at https://developer.chrome.com/docs/devtools/remote-debugging/

My device has Chrome v32 and Chrome Beta v33, while my PC has Chrome v33 and Chrome Canary v35.

USB debugging is enabled on my device and device driver has been installed. I have never got the prompt as outline in step 3 from the above link to approve the RSA key fingerprint yet the device does connect to my PC to allow media transfer. I have even revoked all USB debugging authorizations as per the link above.

I don't have any thing extra installed on my PC for Android development which may perhaps be the issue. I wish to utilise this feature to inspect web pages from the devices point of view.

答:
Had a nightmare with this today Samsung Galaxy Note 9 and a Windows 10 Laptop without Android Studio. Here are working steps to get debugging.

1) Enable developer mode on the phone in the usual manner and turn on "USB Debugging".

2) On your computer install the Samsung USB Drivers for Windows https://developer.samsung.com/galaxy/others/android-usb-driver-for-windows

3) Open Chrome on your Computer - bring up Remote Devices in dev console (at the moment it will say no devices detected).

4) Connect your phone to your computer via USB cable.

5) Accept any prompts for authorisation and wait until the computer says "your device is ready.." etc.

6) On your phone, swipe down the top menu and tap "P Android system" - select "MIDI" under "Use USB for".

7) Various setup notifications will appear on your PC, when they are finished you will get the authorisation prompt for debugging on your phone. Accept it! Wait a few more second and you will find the phone now appears in Chrome Dev tools on the computer, and will be connected in a few more seconds.

You're welcome.


问:
How to select drop-down value in Protractor using framework: 'jasmine',
I am trying to select drop down list using protractor. None of this code works.

```<code>it("Select Block from District", function() {

    const selectElement={}
    selectElement.selectElementDropdown =function(element,index,milliseconds){
     console.log("Selecting element by drop down","OK");

     element.all(by.tagName('option')).then(function(options){

         options[2].click();
    //here index 2 is hardcoded, which can be changed to options[index]
     });

     if(typeof milliseconds!=='undefined'){
         browser.sleep(milliseconds);
     }

    }

    module.exports =selectElement;

    const methodDropDown = {} //require('../Src/SelectElement.js');

    var DistrictDetails = function(){

    this.DistrictName = element.all(by.xpath("//label[text()='Select Block']")).get(7).element(by.xpath("//option[contains(text(),'Ambabhona')]"));
    //the selector is clicked to open the drop down
</code>```

I have already gone through pass the value using send keys to text box

```<code><div _ngcontent-c9="" class="col-sm-6">
    <label _ngcontent-c9="" class="col-md-5 control-label">District
        <span _ngcontent-c9="" class="err-msg">*</span>
    </label>
    <div _ngcontent-c9="" class="col-md-7">
        <p-dropdown _ngcontent-c9="" formcontrolname="districtId" placeholder="Select District"
            class="ng-tns-c6-189 ng-pristine ng-invalid ng-touched">
            <div class="ng-tns-c6-189 ui-dropdown ui-widget ui-state-default ui-corner-all ui-helper-clearfix"
                style="width: 138px;">
                <!---->
                <div class="ui-helper-hidden-accessible ng-tns-c6-189 ng-star-inserted">
                    <select class="ng-tns-c6-189" aria-hidden="true" tabindex="-1" aria-label=" ">
                        <!---->
                        <option class="ng-tns-c6-189 ng-star-inserted">Select District</option>
                        <!---->
                        <!---->
                        <!---->
                        <!---->
                        <option class="ng-tns-c6-189 ng-star-inserted" value="390" style="">Bargarh</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="391" style="">Jharsuguda</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="392" style="">Sambalpur</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="393" style="">Deogarh</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="394" style="">Sundergarh</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="395" style="">Keonjhar</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="396" style="">Mayurbhanj</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="397" style="">Balasore</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="398" style="">Bhadrak</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="399" style="">Kendrapara</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="400" style="">Jagatsinghpur</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="401" style="">Cuttack</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="402" style="">Jajpur</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="403" style="">Dhenkanal</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="404" style="">Angul</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="405" style="">Nayagarh</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="406" style="">Khordha</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="407" style="">Puri</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="408" style="">Ganjam</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="409" style="">Gajapati</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="410" style="">Kandhamal</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="411" style="">Boudh</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="412" style="">Sonepur</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="413" style="">Bolangir</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="414" style="">Nuapada</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="415" style="">Kalahandi</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="416" style="">Rayagada</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="417" style="">Nabarangpur</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="418" style="">Koraput</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="419" style="">Malkangiri</option>
                        <!---->
                    </select>
                </div>
                <div class="ui-helper-hidden-accessible">
                    <input class="ng-tns-c6-189" readonly="" role="listbox" type="text" aria-label=" ">
                </div>
                <!---->
                <!----><label
                    class="ng-tns-c6-189 ui-dropdown-label ui-inputtext ui-corner-all ui-placeholder ng-star-inserted">
                    Select District
                </label>
                <!---->
                <!---->
                <div class="ui-dropdown-trigger ui-state-default ui-corner-right"><span
                        class="ui-dropdown-trigger-icon ui-clickable pi pi-caret-down"></span>
                </div>
                <div class="ng-tns-c6-189 ui-dropdown-panel ui-widget-content ui-corner-all ui-shadow ng-trigger ng-trigger-panelState"
                    style="display: none; z-index: 1181; top: 27px; left: 0px; opacity: 0;">
                    <!---->
                    <div class="ui-dropdown-items-wrapper" style="max-height: 200px;">
                        <!---->
                    </div>
                </div>
            </div>
        </p-dropdown>
        <!---->
    </div>
</div>
</code>```

Want to select value form drop-down list like  Deogarh

答:
You can do that using filters:

```<code>this.DDOptions = element.all(by.css('.ng-star-inserted'));

exports.SelectDDOption = function (option){
this.DDOptions.filter(function (elem, index) {
    return elem.getText().then(function (text) {
      return text.toUpperCase() === option.toUpperCase();
    });
  }).then(function (filteredElements) {
    filteredElements[0].click();
  });
};
</code>```

Now call this function and pass option which you want to select:

```<code>this.SelectDDOption('Jharsuguda');
</code>```

Body:
I am trying to select drop down list using protractor. None of this code works.

it("Select Block from District", function() {

    const selectElement={}
    selectElement.selectElementDropdown =function(element,index,milliseconds){
     console.log("Selecting element by drop down","OK");

     element.all(by.tagName('option')).then(function(options){

         options[2].click();
    //here index 2 is hardcoded, which can be changed to options[index]
     });

     if(typeof milliseconds!=='undefined'){
         browser.sleep(milliseconds);
     }

    }

    module.exports =selectElement;

    const methodDropDown = {} //require('../Src/SelectElement.js');

    var DistrictDetails = function(){

    this.DistrictName = element.all(by.xpath("//label[text()='Select Block']")).get(7).element(by.xpath("//option[contains(text(),'Ambabhona')]"));
    //the selector is clicked to open the drop down

I have already gone through pass the value using send keys to text box

    District
        *

                    <select class="ng-tns-c6-189" aria-hidden="true" tabindex="-1" aria-label=" ">

                        <option class="ng-tns-c6-189 ng-star-inserted">Select District</option>

                        <option class="ng-tns-c6-189 ng-star-inserted" value="390" style="">Bargarh</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="391" style="">Jharsuguda</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="392" style="">Sambalpur</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="393" style="">Deogarh</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="394" style="">Sundergarh</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="395" style="">Keonjhar</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="396" style="">Mayurbhanj</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="397" style="">Balasore</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="398" style="">Bhadrak</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="399" style="">Kendrapara</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="400" style="">Jagatsinghpur</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="401" style="">Cuttack</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="402" style="">Jajpur</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="403" style="">Dhenkanal</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="404" style="">Angul</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="405" style="">Nayagarh</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="406" style="">Khordha</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="407" style="">Puri</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="408" style="">Ganjam</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="409" style="">Gajapati</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="410" style="">Kandhamal</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="411" style="">Boudh</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="412" style="">Sonepur</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="413" style="">Bolangir</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="414" style="">Nuapada</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="415" style="">Kalahandi</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="416" style="">Rayagada</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="417" style="">Nabarangpur</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="418" style="">Koraput</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="419" style="">Malkangiri</option>

                    </select>

                    <input class="ng-tns-c6-189" readonly="" role="listbox" type="text" aria-label=" ">

                    Select District

Want to select value form drop-down list like  Deogarh

Body:
You can do that using filters:

this.DDOptions = element.all(by.css('.ng-star-inserted'));

exports.SelectDDOption = function (option){
this.DDOptions.filter(function (elem, index) {
    return elem.getText().then(function (text) {
      return text.toUpperCase() === option.toUpperCase();
    });
  }).then(function (filteredElements) {
    filteredElements[0].click();
  });
};

Now call this function and pass option which you want to select:

this.SelectDDOption('Jharsuguda');


问:
Check if record exists in python. If exists then skip else process
I have a function for extracting frames from videos. I have a csv file which has the names of the videos already processed. I want to check if the name of a newly added video file is present in the csv file. If present then exit the code else process the function to extract frames from the new video

```<code>def extractFrames(m):
    global vid_name

    vid_files=glob(m)

    for v_f in range(len(vid_files)):
        print("path of video========>>>>.",vid_files[v_f])

        #latest_file=max(vid_files, key=os.path.getctime)

        #print(latest_file)

        v1=os.path.basename(vid_files[v_f])
        try:
            vid_name = os.path.splitext(v1)[0]

            vidcap = cv2.VideoCapture(vid_files[v_f])
        except cv2.error as e:
            print(e)
        except:
                print('error')
        #condition
        fsize=os.stat(vid_files[v_f])
        print('=============size of video ===================:' , fsize.st_size)
        try:

            if (fsize.st_size > 1000):

                fps = vidcap.get(cv2.CAP_PROP_FPS)      # OpenCV2 version 2 used "CV_CAP_PROP_FPS"
                frameCount = int(vidcap.get(cv2.CAP_PROP_FRAME_COUNT))
                duration = frameCount/fps
                minutes = int(duration/60)
                print('fps = ' + str(fps))
                print('number of frames = ' + str(frameCount))
                print('duration (S) = ' + str(duration))
                if (duration > 1):
                    success,image = vidcap.read()

                    count=0

                    success=True

                    while success:

                        img_name = vid_name + '_f' + str(count) + ".jpg"

                        success,image = vidcap.read()
                        if count % 10 == 0 or count ==0:
                            target_non_target(img_name, image)

                        count+=1

                    vidcap.release()

                    cv2.destroyAllWindows()
        except:
            print("error")

        print('finished processing video ', vid_files[v_f])
        with open("C:\\multi_cat_3\\models\\research\\object_detection\\my_imgs"+'/video_info.csv', 'a') as csv_file:
            fieldnames = ['Video_Name','Process']
            file_is_empty = os.stat("C:\\multi_cat_3\\models\\research\\object_detection\\my_imgs"+'/video_info.csv').st_size == 0
            writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
            if file_is_empty:
                writer.writeheader()
            writer.writerow({'Video_Name':vid_name,'Process':'done'})

if __name__ == "__main__":

    x="C:\\Python36\\videos\\*.mp4"

    extractFrames(x)
</code>```

Suppose a folder has 2 videos V1 and V2 from which frames have already been extracted and the names V1 and V2 are added in the csv file. Now when i add video V3 the code should check if V3 exists already in the csv. If it exists then the code should be skipped else frames from V3 should be processed and V3 should be added in the csv file after extraction of the frames

答:
```<code>def extractFrames(m,done):
    global vid_name

    vid_files=glob(m)

    for v_f in range(len(vid_files)):
        print("path of video========>>>>.",vid_files[v_f])

        v1=os.path.basename(vid_files[v_f])
        vid_name = os.path.splitext(v1)[0]

        if vid_name not in done:
            try:
                vidcap = cv2.VideoCapture(vid_files[v_f])
            except cv2.error as e:
                print(e)
            except:
                print('error')
        #condition
            fsize=os.stat(vid_files[v_f])
            print('=============size of video ===================:' , fsize.st_size)
            try:

                if (fsize.st_size > 1000):

                    fps = vidcap.get(cv2.CAP_PROP_FPS)      # OpenCV2 version 2 used "CV_CAP_PROP_FPS"
                    frameCount = int(vidcap.get(cv2.CAP_PROP_FRAME_COUNT))
                    duration = frameCount/fps
                    minutes = int(duration/60)
                    print('fps = ' + str(fps))
                    print('number of frames = ' + str(frameCount))
                    print('duration (S) = ' + str(duration))
                    if (duration > 1):
                        success,image = vidcap.read()

                        count=0

                        success=True

                        while success:

                            img_name = vid_name + '_f' + str(count) + ".jpg"

                            success,image = vidcap.read()
                            if count % 10 == 0 or count ==0:
                                target_non_target(img_name, image)

                            count+=1

                        vidcap.release()

                        cv2.destroyAllWindows()
            except:
                print("error")

            print('finished processing video ', vid_files[v_f])
            with open("C:\\multi_cat_3\\models\\research\\object_detection\\my_imgs\\"+'video_info.csv', 'a') as csv_file:
                fieldnames = ['Video_Name','Process']
                file_is_empty = os.stat("C:\\multi_cat_3\\models\\research\\object_detection\\my_imgs\\"+'video_info.csv').st_size == 0
                writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
                if file_is_empty:
                    writer.writeheader()
                writer.writerow({'Video_Name':vid_name,'Process':'done'})

if __name__ == "__main__":

    x="C:\\Python36\\videos\\*.mp4"

    y="C:\\multi_cat_3\\models\\research\\object_detection\\my_imgs\\video_info.csv"

    done=list(y)
    extractFrames(x,done)
</code>```

Body:
I have a function for extracting frames from videos. I have a csv file which has the names of the videos already processed. I want to check if the name of a newly added video file is present in the csv file. If present then exit the code else process the function to extract frames from the new video

def extractFrames(m):
    global vid_name

    vid_files=glob(m)

    for v_f in range(len(vid_files)):
        print("path of video========>>>>.",vid_files[v_f])

        #latest_file=max(vid_files, key=os.path.getctime)

        #print(latest_file)

        v1=os.path.basename(vid_files[v_f])
        try:
            vid_name = os.path.splitext(v1)[0]

            vidcap = cv2.VideoCapture(vid_files[v_f])
        except cv2.error as e:
            print(e)
        except:
                print('error')
        #condition
        fsize=os.stat(vid_files[v_f])
        print('=============size of video ===================:' , fsize.st_size)
        try:

            if (fsize.st_size > 1000):

                fps = vidcap.get(cv2.CAP_PROP_FPS)      # OpenCV2 version 2 used "CV_CAP_PROP_FPS"
                frameCount = int(vidcap.get(cv2.CAP_PROP_FRAME_COUNT))
                duration = frameCount/fps
                minutes = int(duration/60)
                print('fps = ' + str(fps))
                print('number of frames = ' + str(frameCount))
                print('duration (S) = ' + str(duration))
                if (duration > 1):
                    success,image = vidcap.read()

                    count=0

                    success=True

                    while success:

                        img_name = vid_name + '_f' + str(count) + ".jpg"

                        success,image = vidcap.read()
                        if count % 10 == 0 or count ==0:
                            target_non_target(img_name, image)

                        count+=1

                    vidcap.release()

                    cv2.destroyAllWindows()
        except:
            print("error")

        print('finished processing video ', vid_files[v_f])
        with open("C:\\multi_cat_3\\models\\research\\object_detection\\my_imgs"+'/video_info.csv', 'a') as csv_file:
            fieldnames = ['Video_Name','Process']
            file_is_empty = os.stat("C:\\multi_cat_3\\models\\research\\object_detection\\my_imgs"+'/video_info.csv').st_size == 0
            writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
            if file_is_empty:
                writer.writeheader()
            writer.writerow({'Video_Name':vid_name,'Process':'done'})

if __name__ == "__main__":

    x="C:\\Python36\\videos\\*.mp4"

    extractFrames(x)

Suppose a folder has 2 videos V1 and V2 from which frames have already been extracted and the names V1 and V2 are added in the csv file. Now when i add video V3 the code should check if V3 exists already in the csv. If it exists then the code should be skipped else frames from V3 should be processed and V3 should be added in the csv file after extraction of the frames


答: Both console.log(j) use j from the scope where it is defined, not from where the functions are called.

Title: how would you explain following javascript snippet?


问:
How to know how often an external link is clicked?
This page: http://funds.ft.com/CityofLondon/investmentmanagement/HCEWUR contains a number of links under the section "Annual Reports & Factsheets". The content these links point at is hosted at fundslibrary.co.uk, a 3rd party supplier.

Is there any way for us to track how often these links are clicked? We don't have access to the 3rd party web server logs.

One way I'm thinking is to POST an instruction to increment a count with jQuery every time the link is clicked, but that would mean us having to maintain the count.

Is there any functionality in Google Analytics that could give us this info?

答:
You could use jQuery to send an event to Google Analytics when a link is clicked upon if you are using the Google Analytics asynchronous tracking snippet.
Something like:

```<code>$(document).ready(function(){
  $("a").click(function(){
     _gaq.push(['_trackEvent', 'Links', 'Followed', $(this).attr("href")]);
     return true;
  });
});
</code>```

Here is the guide to tracking events with Google Analytics.

ContentLicense: CC BY-SA 3.0

Body:
You could use jQuery to send an event to Google Analytics when a link is clicked upon if you are using the Google Analytics asynchronous tracking snippet.
Something like:

$(document).ready(function(){
  $("a").click(function(){
     _gaq.push(['_trackEvent', 'Links', 'Followed', $(this).attr("href")]);
     return true;
  });
});

Here is the guide to tracking events with Google Analytics.


问:
Having Trouble comparing output (Which is the result of running a C program)with expected
I have written a c program, which works, it works on the terminal. And I wanted to run a shell script to test my code. The issue is I can't seem to figure out how to get the output of my q1_sequence to match with my expected value.

#!/bin/sh

OUTPUT="$(./q1_sequence 5 1 3 2 1)"
echo $OUTPUT

EXPECTED="5 1 3 2 1 : returns a value of 99 and 15 iterations"

if [ "$OUTPUT" == "$EXPECTED" ]
then
    echo "Test was true"
else
    echo "Test was not true"
fi

```

I expected this to be true, and for the console to state that this was true.
however I don't get that at all.

What I get is:

sh testing.sh

5 1 3 2 1 : returns a value of 99 and 15 iterations
testing.sh: 8: [: 5 1 3 2 1 : returns a value of 99 and 15 iterations: unexpected operator
Test was not true

I'm not sure what I'm doing wrong, or what the unexpected operator is or was. I've tried a lot of different things, and I think I'm missing something but I can't for the life of me figure it out. I've done OUTPUT == "5 1 3 2 1 : returns a value of 99 and 15 iterations"

I've tried a lot of different sort of combinations, but I can't just figure it out so any help would be helpful.

答:
Use a single equal sign. if [ "$OUTPUT" = "$EXPECTED" ]

sh uses a single equal sign for comparison of strings and not, like in C, == Alternatively, use #!/bin/bash or bash testing.sh.

Body:
I have written a c program, which works, it works on the terminal. And I wanted to run a shell script to test my code. The issue is I can't seem to figure out how to get the output of my q1_sequence to match with my expected value.

#!/bin/sh

OUTPUT="$(./q1_sequence 5 1 3 2 1)"
echo $OUTPUT

EXPECTED="5 1 3 2 1 : returns a value of 99 and 15 iterations"

if [ "$OUTPUT" == "$EXPECTED" ]
then
    echo "Test was true"
else
    echo "Test was not true"
fi

I expected this to be true, and for the console to state that this was true.
however I don't get that at all.

What I get is:

sh testing.sh

5 1 3 2 1 : returns a value of 99 and 15 iterations
testing.sh: 8: [: 5 1 3 2 1 : returns a value of 99 and 15 iterations: unexpected operator
Test was not true

I'm not sure what I'm doing wrong, or what the unexpected operator is or was. I've tried a lot of different things, and I think I'm missing something but I can't for the life of me figure it out. I've done OUTPUT == "5 1 3 2 1 : returns a value of 99 and 15 iterations"

I've tried a lot of different sort of combinations, but I can't just figure it out so any help would be helpful.


问:
Columns not working in both Bootstrap 3 and 4
I'm trying to set up a new internal web page using bootstrap (both versions 3.3.6 and 4.0.0-alpha.6) columns, but for some reason they don't show up in Internet Explorer 11 (company-mandated). Instead of columns, the text is stacked vertically (see examples).

I have tried everything from complex code to the simple code I have attached to this question. Nothing has worked. I have also looked at every single web page I could find on this, and likewise nothing has worked. I have also tried using xs, sm, md, lg and xl column sizes, and they don't make any difference.

```<code><!DOCTYPE html>
<html lang="en-US">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link href="css/bootstrap.min.css" rel="stylesheet" />
<link href="css/style.css" rel="stylesheet" />
<script src="js/bootstrap.min.js"></script>
<title>Test 4</title>
</head>
<body>
<div class="container-fluid">
<div class="row">
  <div class="col-lg-4">lg-4</div>
  <div class="col-lg-4">lg-4</div>
</div>
<div class="row">
  <div class="col-lg-3">lg-3</div>
  <div class="col-lg-3">lg-3</div>
  <div class="col-lg-3">lg-3</div>
</div>
<div class="container">
<div class="row">
  <div class="col-3">variable</div>
  <div class="col-3">variable</div>
  <div class="col-3">variable</div>
</div>
</div>
</code>```

The above code results in:

lg-4

lg-4

lg-3

lg-3

lg-3

variable

variable

variable

Instead of:

lg-4     lg-4     lg-3     lg-3     lg-3

variable     variable     variable

答:
```<code><div class="col-lg-12">
   <div class="row">
      <div class="col-lg-3">Column 1-a</div>
      <div class="col-lg-3">Column 1-b</div>
      <div class="col-lg-3">Column 1-b</div>
      <div class="col-lg-3">Column 1-b</div>
   </div>
</div>
</code>```

Body:
I'm trying to set up a new internal web page using bootstrap (both versions 3.3.6 and 4.0.0-alpha.6) columns, but for some reason they don't show up in Internet Explorer 11 (company-mandated). Instead of columns, the text is stacked vertically (see examples).

I have tried everything from complex code to the simple code I have attached to this question. Nothing has worked. I have also looked at every single web page I could find on this, and likewise nothing has worked. I have also tried using xs, sm, md, lg and xl column sizes, and they don't make any difference.

<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link href="css/bootstrap.min.css" rel="stylesheet" />
<link href="css/style.css" rel="stylesheet" />

<title>Test 4</title>

lg-4

lg-4

lg-3

lg-3

lg-3

variable

variable

variable

The above code results in:

lg-4

lg-4

lg-3

lg-3

lg-3

variable

variable

variable

Instead of:

lg-4     lg-4     lg-3     lg-3     lg-3

variable     variable     variable


问:
Is it safe to keep nonce/hash codes in .htacces file or creating random nonce/hash codes separately for each webpage visited by user?
I'm setting up content-security-policy on my website. And after much exploration i m little confused as to where do i put CSP code. Should i place it individually on every web page which is heavy work or should i put the nonce/hash code in .htaccess file? And how can i generate random nonces/hash code each time somebody is on the website?

I have already tried placing the CSP in every web page and it takes a lot of time to get it working, not to mention the edits on every script link and inline elements.

Following is the code that i have used: (example)
...
script-src 'nonce-4AEemGb0xJptoIGFP3Nd'

...
Should i keep the nonce code in .htaccess file or keep separate for each individual pages on the site.

答:
A random nonce must, by definition, be generated on every page load; nonce means "number used once".  So you must generate the page programmatically, not use raw .html files.  A static nonce (a "nmany"?) defeats the purpose of nonces, and provides no security whatsoever.

A hash, on the other hand, is static, because it's a representation of a specific script.


问:
Use multiple rows as column header for pandas
I have a dataframe that I've imported as follows.

```<code>df = pd.read_excel("./Data.xlsx", sheet_name="Customer Care", header=None)
</code>```

I would like to set the first three rows as column headers but can't figure out how to do this.  I gave the following a try:

```<code>df.columns = df.iloc[0:3,:]
</code>```

but that doesn't seem to work.

I saw something similar in this answer.  But it only applies if all sub columns are going to be named the same way, which is not necessarily the case.

Any recommendations would be appreciated.

答:
```<code>df = pd.read_excel(
    "./Data.xlsx",
    sheet_name="Customer Care",
    header=[0,1,2]
)
</code>```

This will tell pandas to read the first three rows of the excel file as multiindex column labels.

If you want to modify the rows after you load them then set them as columns

```<code>#set the first three rows as columns
df.columns=pd.MultiIndex.from_arrays(df.iloc[0:3].values)
#delete the first three rows (because they are also the columns
df=df.iloc[3:]
</code>```

Body:
I have a dataframe that I've imported as follows.

df = pd.read_excel("./Data.xlsx", sheet_name="Customer Care", header=None)

I would like to set the first three rows as column headers but can't figure out how to do this.  I gave the following a try:

df.columns = df.iloc[0:3,:]

but that doesn't seem to work.

I saw something similar in this answer.  But it only applies if all sub columns are going to be named the same way, which is not necessarily the case.

Any recommendations would be appreciated.

Body:
df = pd.read_excel(
    "./Data.xlsx",
    sheet_name="Customer Care",
    header=[0,1,2]
)

This will tell pandas to read the first three rows of the excel file as multiindex column labels.

If you want to modify the rows after you load them then set them as columns

#set the first three rows as columns
df.columns=pd.MultiIndex.from_arrays(df.iloc[0:3].values)
#delete the first three rows (because they are also the columns
df=df.iloc[3:]


问:
C# creating a form for given size
I want to draw a rectangle on the screen. I guess the most appropriate way is use a form without boarder.

```<code>Form frm = new Form();
frm.StartPosition = FormStartPosition.Manual;
frm.Location = new Point(GlobalPosX, GlobalPosY);
frm.Size = new Size(101, 30);
frm.BackColor = System.Drawing.Color.Yellow;
frm.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
frm.Show();
</code>```

The created from is not as the given size. It's size is similar to the window having boarder. The displayed window is bit larger as I given and the position is also moved little bit upper and left.
Is there another way to achieve my goal?

答: If you want to draw rectangle on the screen, you can draw it directly: http://bytes.com/topic/c-sharp/answers/263740-draw-directly-screen</p>

Title: C# creating a form for given size

Body:
I want to draw a rectangle on the screen. I guess the most appropriate way is use a form without boarder.

Form frm = new Form();
frm.StartPosition = FormStartPosition.Manual;
frm.Location = new Point(GlobalPosX, GlobalPosY);
frm.Size = new Size(101, 30);
frm.BackColor = System.Drawing.Color.Yellow;
frm.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
frm.Show();

The created from is not as the given size. It's size is similar to the window having boarder. The displayed window is bit larger as I given and the position is also moved little bit upper and left.
Is there another way to achieve my goal?


问:
var output = 1 + 2 + 3 + "4" + 5 + "90"; Output : 64590;; Just want to know why?
Need to know the logical reason behind the stated output

```<code>var output = 1 + 2 + 3 + "4" + 5 + "90";
</code>```

Output : "64590"

答:
The + operator has several overloads. Relevant for your piece of code are

```<code>// Integer addition
int operator +(int x, int y); // A

// String concatenation
string operator +(string x, string y); // B
string operator +(string x, object y); // C
string operator +(object x, string y); // D
</code>```

For cases C and B, note the relevant part of the C# 6.0 specification (§7.8.4 Addition operator)

These overloads of the binary + operator perform string concatenation.
  If an operand of string concatenation is null, an empty string is
  substituted. Otherwise, any non-string argument is converted to its
  string representation by invoking the virtual ToString method
  inherited from type object. If ToString returns null, an empty string
  is substituted.

Thus, your expression

```<code>var output = 1 + 2 + 3 + "4" + 5 + "90";
</code>```

is evaluated left to right with the operators used as follows:

```<code>var output = ((((1 + 2) + 3) + "4") + 5) + "90";
                 --A--
                 -----A-----
                 ---------D--------
                 ------------C----------
                 ------------------B-----------
</code>```

Body:
Need to know the logical reason behind the stated output

var output = 1 + 2 + 3 + "4" + 5 + "90";

Output : "64590"

Body:
The + operator has several overloads. Relevant for your piece of code are

// Integer addition
int operator +(int x, int y); // A

// String concatenation
string operator +(string x, string y); // B
string operator +(string x, object y); // C
string operator +(object x, string y); // D

For cases C and B, note the relevant part of the C# 6.0 specification (§7.8.4 Addition operator)

These overloads of the binary + operator perform string concatenation.
  If an operand of string concatenation is null, an empty string is
  substituted. Otherwise, any non-string argument is converted to its
  string representation by invoking the virtual ToString method
  inherited from type object. If ToString returns null, an empty string
  is substituted.

Thus, your expression

var output = 1 + 2 + 3 + "4" + 5 + "90";

is evaluated left to right with the operators used as follows:

var output = ((((1 + 2) + 3) + "4") + 5) + "90";
                 --A--
                 -----A-----
                 ---------D--------
                 ------------C----------
                 ------------------B-----------


问:
Migrating Oracle query to PostgreSQL
Can you please help me with this? How can I convert below query to PostgreSQL.

The query below gives different output when executed in PostgreSQL than when executed in Oracle.

```<code>SELECT
  to_char(to_date('01011970','ddmmyyyy') + 1/24/60/60 * 4304052,'dd-mon-yyyy hh24:mi:ss')
from dual;
</code>```

答:
I think you want:

```<code>select '1970-01-01'::date + 4304052 * interval '1 second';
</code>```

You can use to_char() to convert this back to a string, if you really want:

```<code>select to_char('1970-01-01'::date + 4304052 * interval '1 second', 'YYYY-MM-SS HH24:MI:SS');
</code>```

Title: Migrating Oracle query to PostgreSQL

Body:
Can you please help me with this? How can I convert below query to PostgreSQL.

The query below gives different output when executed in PostgreSQL than when executed in Oracle.

SELECT
  to_char(to_date('01011970','ddmmyyyy') + 1/24/60/60 * 4304052,'dd-mon-yyyy hh24:mi:ss')
from dual;

Body:
I think you want:

select '1970-01-01'::date + 4304052 * interval '1 second';

You can use to_char() to convert this back to a string, if you really want:

select to_char('1970-01-01'::date + 4304052 * interval '1 second', 'YYYY-MM-SS HH24:MI:SS');


答:
Because 1,2,3, and 5 are integers while "4" and "9" are strings. 1+2+3 = 6. 6 + "4" = 64 (it's being concatenated, the + operator doesn't JUST do math additions, it also concatenates. eg.

```<code>string concat = "dog" + "cat"; //
 //concat will now be assigned with "dogcat"
</code>```

Moving forward, "4" + 5 will come out to 45.. so right now we have 645 and add a "90" in there and it will be 64590

Title: var output = 1 + 2 + 3 + "4" + 5 + "90"; Output : 64590;; Just want to know why?

Body:
Because 1,2,3, and 5 are integers while "4" and "9" are strings. 1+2+3 = 6. 6 + "4" = 64 (it's being concatenated, the + operator doesn't JUST do math additions, it also concatenates. eg.

string concat = "dog" + "cat"; //
 //concat will now be assigned with "dogcat"

Moving forward, "4" + 5 will come out to 45.. so right now we have 645 and add a "90" in there and it will be 64590


问:
Rename a jar file removing the version number
I am trying to rename a jar file name with a version embedded in it like
test-java-1.0.0.jar to test-java.jar

Tried below approach but this will not workout if the version is changed to something like

test-java-11.0.0.jar or test-compile-1.0.12.jar

```<code>Set test=test-java-1.0.0.jar
set test1=%test:~0,-10%
rename %test% %test1%.jar
</code>```

Looking for something like:

Input string: test-java-1.0.0.jar

Expected output: test-java.jar

答:
This method works removing the last part of the file name separated by hypen:

EDIT 2019/05/31: Support for filenames with spaces added

```<code>@echo off

for %%f in (
  test-java-1.0.0.jar
  compile-java-1.11.1.jar
  poc-java-1.2.22.jar
  compile-java-code-1.11.1.jar
  poc-java-compile-1.2.22.jar
  some-thing-like-1.2.32.jar
  "test java-1.0.0.jar"
  "compile java test-1.2.22.jar"
) do call :Rename %%f
goto :EOF

:Rename name

setlocal EnableDelayedExpansion
set "old=%~1"
set "new=" & set "x=%old:-=" & set "new=!new!-!x!" & set "x=%"
echo REN "%old%" "%new:~1%.jar"
exit /B
</code>```

Sample output:

```<code>REN "test-java-1.0.0.jar" "test-java.jar"
REN "compile-java-1.11.1.jar" "compile-java.jar"
REN "poc-java-1.2.22.jar" "poc-java.jar"
REN "compile-java-code-1.11.1.jar" "compile-java-code.jar"
REN "poc-java-compile-1.2.22.jar" "poc-java-compile.jar"
REN "some-thing-like-1.2.32.jar" "some-thing-like.jar"
REN "test java-1.0.0.jar" "test java.jar"
REN "compile java test-1.2.22.jar" "compile java test.jar"
</code>```

To really rename the files, remove the echo command before REN part.

Body:
I am trying to rename a jar file name with a version embedded in it like
test-java-1.0.0.jar to test-java.jar

Tried below approach but this will not workout if the version is changed to something like

test-java-11.0.0.jar or test-compile-1.0.12.jar

Set test=test-java-1.0.0.jar
set test1=%test:~0,-10%
rename %test% %test1%.jar

Looking for something like:

Input string: test-java-1.0.0.jar

Expected output: test-java.jar

Body:
This method works removing the last part of the file name separated by hypen:

EDIT 2019/05/31: Support for filenames with spaces added

@echo off

for %%f in (
  test-java-1.0.0.jar
  compile-java-1.11.1.jar
  poc-java-1.2.22.jar
  compile-java-code-1.11.1.jar
  poc-java-compile-1.2.22.jar
  some-thing-like-1.2.32.jar
  "test java-1.0.0.jar"
  "compile java test-1.2.22.jar"
) do call :Rename %%f
goto :EOF

:Rename name

setlocal EnableDelayedExpansion
set "old=%~1"
set "new=" & set "x=%old:-=" & set "new=!new!-!x!" & set "x=%"
echo REN "%old%" "%new:~1%.jar"
exit /B

Sample output:

REN "test-java-1.0.0.jar" "test-java.jar"
REN "compile-java-1.11.1.jar" "compile-java.jar"
REN "poc-java-1.2.22.jar" "poc-java.jar"
REN "compile-java-code-1.11.1.jar" "compile-java-code.jar"
REN "poc-java-compile-1.2.22.jar" "poc-java-compile.jar"
REN "some-thing-like-1.2.32.jar" "some-thing-like.jar"
REN "test java-1.0.0.jar" "test java.jar"
REN "compile java test-1.2.22.jar" "compile java test.jar"

To really rename the files, remove the echo command before REN part.


问:
Quartz cron expression to run at a different time on Saturday
I understand how to generate a cron expression to run at certain times for each day, and I have it right now go at noon and 15:30 MON-SAT. However I would like it to be at 15:00 on Saturday instead of 15:30. Is there some method to writing this out as a cron expression? Or do I need to do a separate trigger for Saturday?</p>

答: I assume that you know how to create cron expression, as per the question, you already have a scheduler to run the job at 15.30 from Mon to SAT. If you have a requirement to run a scheduler only on Saturday at 15.00 time, I will suggest you to create another one. It will be cohesive and it makes sensible for each time what is happening. If you want to change the time from Mon to Sat, you can change the cron expression from 15.30 to 15.00.</p>


答:
Use the ClientSize property instead of Size:

```<code>frm.ClientSize = new Size(101,30);
</code>```

Title: C# creating a form for given size

Body:
Use the ClientSize property instead of Size:

frm.ClientSize = new Size(101,30);


问:
Is there anyway to reset multi index in pandas?
I want to obtain stock data using pandas_datareader. I have the data, but the index I got is multiIndex.
_data.columns

```<code>MultiIndex(levels=[['High', 'Low', 'Open', 'Close', 'Volume', 'Adj Close'], ['MSFT']],
           codes=[[0, 1, 2, 3, 4, 5], [0, 0, 0, 0, 0, 0]],
           names=['Attributes', 'Symbols'])

from pandas_datareader import data as pdr
import yfinance
_data = pdr.get_data_yahoo(['MSFT'], start='2019-01-01', end='2019-05-30')
</code>```

The format I want to get is single index.So that i can use that data to plot

```<code>    symbol  date            price
0   MSFT    2000-01-01  39.81
1   MSFT    2000-02-01  36.35
2   MSFT    2000-03-01  43.22
3   MSFT    2000-04-01  28.37
4   MSFT    2000-05-01  25.45
</code>```

答:
There are several "Price" Columns to choose from.  I chose 'Adj Close'.  This is mostly the same as ChrisA's comment.

```<code>_data.stack()['Adj Close'].reset_index(name='Price')

          Date Symbols       Price
0   2019-01-02    MSFT  100.318642
1   2019-01-03    MSFT   96.628120
2   2019-01-04    MSFT  101.122223
3   2019-01-07    MSFT  101.251190
4   2019-01-08    MSFT  101.985329
..         ...     ...         ...
</code>```

Body:
I want to obtain stock data using pandas_datareader. I have the data, but the index I got is multiIndex.
_data.columns

MultiIndex(levels=[['High', 'Low', 'Open', 'Close', 'Volume', 'Adj Close'], ['MSFT']],
           codes=[[0, 1, 2, 3, 4, 5], [0, 0, 0, 0, 0, 0]],
           names=['Attributes', 'Symbols'])

from pandas_datareader import data as pdr
import yfinance
_data = pdr.get_data_yahoo(['MSFT'], start='2019-01-01', end='2019-05-30')

The format I want to get is single index.So that i can use that data to plot

    symbol  date            price
0   MSFT    2000-01-01  39.81
1   MSFT    2000-02-01  36.35
2   MSFT    2000-03-01  43.22
3   MSFT    2000-04-01  28.37
4   MSFT    2000-05-01  25.45

Body:
There are several "Price" Columns to choose from.  I chose 'Adj Close'.  This is mostly the same as ChrisA's comment.

_data.stack()['Adj Close'].reset_index(name='Price')

          Date Symbols       Price
0   2019-01-02    MSFT  100.318642
1   2019-01-03    MSFT   96.628120
2   2019-01-04    MSFT  101.122223
3   2019-01-07    MSFT  101.251190
4   2019-01-08    MSFT  101.985329
..         ...     ...         ...


问:
How to disable a linting rule inline in flutter
Is there a way to disable a linting rule for a line in flutter?

I have a specific use case where I want to disable linting for two lines.
I have a lot of business logic already written so I cannot change the code.

abstract class ReviewName {
  static final NEW = 'NEW';
  static final OLD = 'OLD';
}
```

The above code will have linting errors: Name non-constant identifiers using lowerCamelCase.dart(non_constant_identifier_names)

Is there any way I avoid the lint error for only the two lines?

答:
Use the // ignore: syntax, for example:

```<code>abstract class ReviewName {
  // ignore: non_constant_identifier_names
  static final NEW = 'NEW';

  // ignore: non_constant_identifier_names
  static final OLD = 'OLD';
}
</code>```

The list of rule names is here.

Body:
Is there a way to disable a linting rule for a line in flutter?

I have a specific use case where I want to disable linting for two lines.
I have a lot of business logic already written so I cannot change the code.

abstract class ReviewName {
  static final NEW = 'NEW';
  static final OLD = 'OLD';
}

The above code will have linting errors: Name non-constant identifiers using lowerCamelCase.dart(non_constant_identifier_names)

Is there any way I avoid the lint error for only the two lines?

Body:
Use the // ignore: syntax, for example:

abstract class ReviewName {
  // ignore: non_constant_identifier_names
  static final NEW = 'NEW';

  // ignore: non_constant_identifier_names
  static final OLD = 'OLD';
}

The list of rule names is here.


问:
Nested axios requests from different web services
I have a problem (using NodeJS + Express) trying to retrieve in 'users' information from 3 different requests (2 domains) and I can't get what I want. I'd like a function getAllUsers() to return something like this:

```<code>[
    {
        "username": "joe_example",
        "plays": 178,
        "friends": 7,
        "uri": "/users/joe_example"
    },
    ...snip additional users...
]
</code>```

Here's my main function:

```<code>async function getAllUsers() {
    let users = await axios.get('http://localhost:8000/friends')
        .then(response => {
            response.data["friends"].map(user => {
                user = getUser(user.username)
            })
        })
        .catch(error => console.log(error))
    return users
}

async function getUser(name) {
    let user = await axios.all(
        [
            axios.get('http://localhost:8000/friends/' + name),
            axios.get('http://localhost:8001/plays/' + name)
        ]).then(axios.spread((res1, res2) => {
            user["username"] = name
            user["friends"] = res1.data["friends"].length
            user["plays"] = res2.data["plays"].length
            user["uri"] = "/users/" + name
        })).catch(error => { console.log(error) })
    return user
}
</code>```

Yes, it may sounds crazy...Friends service has user names and you have to call /friends/<username> in order to retrieve the amount of friends each user has, same with /plays/<username>

Any ideas or suggestions ? I've tried all I know :(

答:
It works charmly, here is the right solution, nice help using Promise.all. I didn't know how useful is. I made some minors changes too:

```<code>async function getUser(username) {
    let user = {}
    await axios.all(
        [
            axios.get('http://localhost:8000/friends/' + username),
            axios.get('http://localhost:8001/plays/' + username)
        ]).then(axios.spread((res1, res2) => {
            user["username"] = username
            user["friends"] = res1.data["friends"].length
            user["plays"] = res2.data["plays"].length
            user["uri"] = "/users/" + username
        })).catch(error => { console.log(error) })
    return user
}

async function getAllUsers() {
    let users = []
    try{
        const { data } = await axios.get('http://localhost:8000/friends')
        const friends = data["friends"].map(user => getUser(user.username))
        users = await Promise.all(friends)
    } catch(error) { console.log(error) }
    return users
}
</code>```

Thanks everyone by your attention !!

Body:
I have a problem (using NodeJS + Express) trying to retrieve in 'users' information from 3 different requests (2 domains) and I can't get what I want. I'd like a function getAllUsers() to return something like this:

[
    {
        "username": "joe_example",
        "plays": 178,
        "friends": 7,
        "uri": "/users/joe_example"
    },
    ...snip additional users...
]

Here's my main function:

async function getAllUsers() {
    let users = await axios.get('http://localhost:8000/friends')
        .then(response => {
            response.data["friends"].map(user => {
                user = getUser(user.username)
            })
        })
        .catch(error => console.log(error))
    return users
}

async function getUser(name) {
    let user = await axios.all(
        [
            axios.get('http://localhost:8000/friends/' + name),
            axios.get('http://localhost:8001/plays/' + name)
        ]).then(axios.spread((res1, res2) => {
            user["username"] = name
            user["friends"] = res1.data["friends"].length
            user["plays"] = res2.data["plays"].length
            user["uri"] = "/users/" + name
        })).catch(error => { console.log(error) })
    return user
}

Yes, it may sounds crazy...Friends service has user names and you have to call /friends/<username> in order to retrieve the amount of friends each user has, same with /plays/<username>

Any ideas or suggestions ? I've tried all I know :(

Body:
It works charmly, here is the right solution, nice help using Promise.all. I didn't know how useful is. I made some minors changes too:

async function getUser(username) {
    let user = {}
    await axios.all(
        [
            axios.get('http://localhost:8000/friends/' + username),
            axios.get('http://localhost:8001/plays/' + username)
        ]).then(axios.spread((res1, res2) => {
            user["username"] = username
            user["friends"] = res1.data["friends"].length
            user["plays"] = res2.data["plays"].length
            user["uri"] = "/users/" + username
        })).catch(error => { console.log(error) })
    return user
}

async function getAllUsers() {
    let users = []
    try{
        const { data } = await axios.get('http://localhost:8000/friends')
        const friends = data["friends"].map(user => getUser(user.username))
        users = await Promise.all(friends)
    } catch(error) { console.log(error) }
    return users
}

Thanks everyone by your attention !!