问:
git diff renamed/moved and modified files but skip renamed/moved and identical files
I'm using:

```<code>git diff HEAD --diff-filter=R -M
</code>```

with the meld external diff tool to show files that have been both renamed/moved and modified. I always do a git diff before doing a commit to both check my work and to properly assemble the commit message. Often times I'll rename/move files, which will also require some path changes within files that reference some renamed/moved files.

My problem is that in order to show the diff of a file that has been renamed and then modified, git diff also pops up a bunch of meld windows for files that have been renamed, but not modified. This can be very annoying. How to get git diff to skip the renamed but not modified files? I'm going to see all those files listed as being renamed/moved when I type git status in a much cleaner way, so I don't want the pop ups for identical files with git diff.

答:
I'm having the same problem and came up with an alias that did the trick (I'm using git 2.8.3)

```<code>[alias]
    difftoolr = "!git difftool \"$@\" -- .  $((git diff \"$1\" -M100% --diff-filter=R --name-only & git diff \"$1\" -M100% --diff-filter=R --name-only -R) | sed 's/\\(.*\\)/:(exclude)\\1/g') #"
</code>```

How to use:

```<code>difftoolr commit1..commit2 -M
</code>```

(see at the bottom for more examples)

How it works:

Imagine you have three files that have been renamed. One of them has its content actually changed (so you want to examine it using your difftool) but the other two are identical except for the path or name (and you want to ignore them).

```<code>(different) path/file.old  -> newPath/file.new
(identical) path/fileB.old -> newPath/fileB.new
(identical) path/fileC.old -> newPath/fileC.new
</code>```

What the alias does is generating path specs that explicitly exclude fileB and fileC, i.e. those files that despite the renaming have the content unaltered.

In other words we are generating these filespecs:

```<code>-- . :(exclude)path/fileB.old :(exclude)newPath/fileB.new :(exclude)path/fileC.old :(exclude)newPath/fileC.new
</code>```

Notice the (perhaps trickiest) part: the old file path and the new file path must be both explicitly excluded.

To do so, we issue a git diff with the following directives:

-M100%: follow the renames. Which means that git is is assuming that some renaming was done, and will take this info into account to do pairwise comparisons. The threshold is 100%, which instructs git to consider renamed those files which have exactly the same content, but not the ones that were altered.

--diff-filter=R: list only the files that git considers renamed, omit the others.

--names-only: just output the file names, no other info

-R: Reverse. In one piece of the script we swap the order of comparison (sort of switching left and right sides), so it will also output the old file names. For instance the -R directive lists the file newPath/fileB.new as path/fileB.old.

...sed...: and finally we append the exclusion directive :(exclude) to the beginning of all filenames.

To deal with other cases I created three different aliases (not really elegant, I'd like something more flexible) so it can be used to specify the different kinds of comparison.

```<code>git difftoolr0 -M
git difftoolr1 HEAD~1..HEAD -M
git difftoolr2 HEAD --cached -M
</code>```

In all cases the "sides of the comparisons" (commits, --cached or whatever) must be specified as the first parameter(s). For instance git difftoolr2 -M HEAD --cached won't work (because -M comes first).

```<code>[alias]
# takes no parameter: sample usage:  git difftoolr0  -M
difftoolr0 = "!git difftool \"$@\" -- .  $((git diff -M100% --diff-filter=R --name-only & git diff -M100% --diff-filter=R --name-only -R) | sed 's/\\(.*\\)/:(exclude)\\1/g') #"

# takes 1 parameter in first position: sample usage:  git difftoolr1 HEAD~1..HEAD -M
difftoolr1 = "!git difftool \"$@\" -- .  $((git diff \"$1\" -M100% --diff-filter=R --name-only & git diff \"$1\" -M100% --diff-filter=R --name-only -R) | sed 's/\\(.*\\)/:(exclude)\\1/g') #"

# takes 2 parameters in first positions: sample usage:  git difftoolr2 HEAD --cached  -M
difftoolr2 = "!git difftool \"$@\" -- .  $((git diff \"$1\" \"$2\" -M100% --diff-filter=R --name-only & git diff \"$1\" \"$2\" -M100% --diff-filter=R --name-only -R) | sed 's/\\(.*\\)/:(exclude)\\1/g') #"
</code>```

Finally, BeyondCompare may suit your needs as well (and mine).

It easily allows to switch the side-by-side diff into an "unstructured" diff.

The latter strips off the folders and leaves just the names. If the filename is the same (but the paths may differ) they are considered two versions of the same file (for instance path/file.png and newPath/file.png). In this case, if the content has not changed, they can be omitted easily using a button on the upper bar.

In case "naming" conflicts occurs (several files on the same side of the comparison have the same name, under different paths), it would choose just one of them for the comparison, and ignore the others.

Body:
I'm using:

git diff HEAD --diff-filter=R -M

with the meld external diff tool to show files that have been both renamed/moved and modified. I always do a git diff before doing a commit to both check my work and to properly assemble the commit message. Often times I'll rename/move files, which will also require some path changes within files that reference some renamed/moved files.

My problem is that in order to show the diff of a file that has been renamed and then modified, git diff also pops up a bunch of meld windows for files that have been renamed, but not modified. This can be very annoying. How to get git diff to skip the renamed but not modified files? I'm going to see all those files listed as being renamed/moved when I type git status in a much cleaner way, so I don't want the pop ups for identical files with git diff.

Body:
I'm having the same problem and came up with an alias that did the trick (I'm using git 2.8.3)

[alias]
    difftoolr = "!git difftool \"$@\" -- .  $((git diff \"$1\" -M100% --diff-filter=R --name-only & git diff \"$1\" -M100% --diff-filter=R --name-only -R) | sed 's/\\(.*\\)/:(exclude)\\1/g') #"

How to use:

difftoolr commit1..commit2 -M

(see at the bottom for more examples)

How it works:

Imagine you have three files that have been renamed. One of them has its content actually changed (so you want to examine it using your difftool) but the other two are identical except for the path or name (and you want to ignore them).

(different) path/file.old  -> newPath/file.new
(identical) path/fileB.old -> newPath/fileB.new
(identical) path/fileC.old -> newPath/fileC.new

What the alias does is generating path specs that explicitly exclude fileB and fileC, i.e. those files that despite the renaming have the content unaltered.

In other words we are generating these filespecs:

-- . :(exclude)path/fileB.old :(exclude)newPath/fileB.new :(exclude)path/fileC.old :(exclude)newPath/fileC.new

Notice the (perhaps trickiest) part: the old file path and the new file path must be both explicitly excluded.

To do so, we issue a git diff with the following directives:

-M100%: follow the renames. Which means that git is is assuming that some renaming was done, and will take this info into account to do pairwise comparisons. The threshold is 100%, which instructs git to consider renamed those files which have exactly the same content, but not the ones that were altered.

--diff-filter=R: list only the files that git considers renamed, omit the others.

--names-only: just output the file names, no other info

-R: Reverse. In one piece of the script we swap the order of comparison (sort of switching left and right sides), so it will also output the old file names. For instance the -R directive lists the file newPath/fileB.new as path/fileB.old.

...sed...: and finally we append the exclusion directive :(exclude) to the beginning of all filenames.

To deal with other cases I created three different aliases (not really elegant, I'd like something more flexible) so it can be used to specify the different kinds of comparison.

git difftoolr0 -M
git difftoolr1 HEAD~1..HEAD -M
git difftoolr2 HEAD --cached -M

In all cases the "sides of the comparisons" (commits, --cached or whatever) must be specified as the first parameter(s). For instance git difftoolr2 -M HEAD --cached won't work (because -M comes first).

[alias]
# takes no parameter: sample usage:  git difftoolr0  -M
difftoolr0 = "!git difftool \"$@\" -- .  $((git diff -M100% --diff-filter=R --name-only & git diff -M100% --diff-filter=R --name-only -R) | sed 's/\\(.*\\)/:(exclude)\\1/g') #"

# takes 1 parameter in first position: sample usage:  git difftoolr1 HEAD~1..HEAD -M
difftoolr1 = "!git difftool \"$@\" -- .  $((git diff \"$1\" -M100% --diff-filter=R --name-only & git diff \"$1\" -M100% --diff-filter=R --name-only -R) | sed 's/\\(.*\\)/:(exclude)\\1/g') #"

# takes 2 parameters in first positions: sample usage:  git difftoolr2 HEAD --cached  -M
difftoolr2 = "!git difftool \"$@\" -- .  $((git diff \"$1\" \"$2\" -M100% --diff-filter=R --name-only & git diff \"$1\" \"$2\" -M100% --diff-filter=R --name-only -R) | sed 's/\\(.*\\)/:(exclude)\\1/g') #"

Finally, BeyondCompare may suit your needs as well (and mine).

It easily allows to switch the side-by-side diff into an "unstructured" diff.

The latter strips off the folders and leaves just the names. If the filename is the same (but the paths may differ) they are considered two versions of the same file (for instance path/file.png and newPath/file.png). In this case, if the content has not changed, they can be omitted easily using a button on the upper bar.

In case "naming" conflicts occurs (several files on the same side of the comparison have the same name, under different paths), it would choose just one of them for the comparison, and ignore the others.


来源: stackexchange

问:
Jenkins pipeline shell step
Trying to get this pipeline working..
I need to prepare some variables (list or string) in groovy, and iterate over it in bash. As I understand, groovy scripts run on jenkins master, but I need to download some files into build workspace, that's why I try to download them in SH step.

```<code>import groovy.json.JsonSlurper
import hudson.FilePath
pipeline {
    agent { label 'xxx' }
    parameters {
 ...
    }
    stages {
        stage ('Get rendered images') {
            steps {
                script {
                    //select grafana API url based on environment
                    if ( params.grafana_env == "111" ) {
                        grafana_url = "http://xxx:3001"
                    } else if ( params.grafana_env == "222" ) {
                        grafana_url = "http://yyy:3001"
                    }

                    //get available grafana dashboards
                    def grafana_url = "${grafana_url}/api/search"
                    URL apiUrl = grafana_url.toURL()
                    List json = new JsonSlurper().parse(apiUrl.newReader())
                    def workspace = pwd()
                    List dash_names = []
                    // save png for each available dashboard
                    for ( dash in json ) {
                        def dash_name = dash['uri'].split('/')
                        dash_names.add(dash_name[1])
                    }
                    dash_names_string = dash_names.join(" ")
                }
                sh "echo $dash_names_string"
                sh """
                    for dash in $dash_names_string;
                    do
                        echo $dash
                    done
                    """
            }
        }
    }
}
</code>```

I get this error when run..

```<code>[Pipeline] End of Pipeline
groovy.lang.MissingPropertyException: No such property: dash for class: WorkflowScript
    at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:53)
    at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.getProperty(ScriptBytecodeAdapter.java:458)
    at com.cloudbees.groovy.cps.sandbox.DefaultInvoker.getProperty(DefaultInvoker.java:33)
    at com.cloudbees.groovy.cps.impl.PropertyAccessBlock.rawGet(PropertyAccessBlock.java:20)
    at WorkflowScript.run(WorkflowScript:42)
</code>```

Looks like I'm missing something obvious...

答:
Escape the $ for the shell variable with a backslash, that should help:</p>

```<code>    for dash in $dash_names_string;
    do
        echo \$dash
    done
</code>```

ContentLicense: CC BY-SA 3.0

Title: Jenkins pipeline shell step

Body:
Trying to get this pipeline working..
I need to prepare some variables (list or string) in groovy, and iterate over it in bash. As I understand, groovy scripts run on jenkins master, but I need to download some files into build workspace, that's why I try to download them in SH step.

import groovy.json.JsonSlurper
import hudson.FilePath
pipeline {
    agent { label 'xxx' }
    parameters {
 ...
    }
    stages {
        stage ('Get rendered images') {
            steps {
                script {
                    //select grafana API url based on environment
                    if ( params.grafana_env == "111" ) {
                        grafana_url = "http://xxx:3001"
                    } else if ( params.grafana_env == "222" ) {
                        grafana_url = "http://yyy:3001"
                    }

                    //get available grafana dashboards
                    def grafana_url = "${grafana_url}/api/search"
                    URL apiUrl = grafana_url.toURL()
                    List json = new JsonSlurper().parse(apiUrl.newReader())
                    def workspace = pwd()
                    List dash_names = []
                    // save png for each available dashboard
                    for ( dash in json ) {
                        def dash_name = dash['uri'].split('/')
                        dash_names.add(dash_name[1])
                    }
                    dash_names_string = dash_names.join(" ")
                }
                sh "echo $dash_names_string"
                sh """
                    for dash in $dash_names_string;
                    do
                        echo $dash
                    done
                    """
            }
        }
    }
}

I get this error when run..

[Pipeline] End of Pipeline
groovy.lang.MissingPropertyException: No such property: dash for class: WorkflowScript
    at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:53)
    at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.getProperty(ScriptBytecodeAdapter.java:458)
    at com.cloudbees.groovy.cps.sandbox.DefaultInvoker.getProperty(DefaultInvoker.java:33)
    at com.cloudbees.groovy.cps.impl.PropertyAccessBlock.rawGet(PropertyAccessBlock.java:20)
    at WorkflowScript.run(WorkflowScript:42)

Looks like I'm missing something obvious...

Body:
Escape the $ for the shell variable with a backslash, that should help:

    for dash in $dash_names_string;
    do
        echo \$dash
    done


问:
Find number of vowels in a word
How can a find all the vowels for a word in bash?

```<code>grep -o "a"  <<<$1 | wc l
</code>```

This command finds only a, and I want to find aeiou.

For example:

for car I want the output to be 1

for computer I want the output to be 3

答:
try:

```<code>echo "computer" | awk '{print gsub(/[aeiou]/,"")}'
</code>```

So I am using echo here to print the word, sending its standard output to awk by pipe (|) as standard input, then performing global substitution of letters a,e,i, o,u with the empty string ("").

Since gsub returns the count of substitutions performed, it tells us how many vowel letters are present in the string.

Title: Find number of vowels in a word

Body:
How can a find all the vowels for a word in bash?

grep -o "a"  <<<$1 | wc l

This command finds only a, and I want to find aeiou.

For example:

for car I want the output to be 1

for computer I want the output to be 3

Body:
try:

echo "computer" | awk '{print gsub(/[aeiou]/,"")}'

So I am using echo here to print the word, sending its standard output to awk by pipe (|) as standard input, then performing global substitution of letters a,e,i, o,u with the empty string ("").

Since gsub returns the count of substitutions performed, it tells us how many vowel letters are present in the string.


问:
TensorFlow: how to classify a binary sequence using RNN?
I get the following piece of code for TensorFlow Sequence Classification (See the code at the end of this quesiton):

https://gist.github.com/danijar/c7ec9a30052127c7a1ad169eeb83f159

I need to modify the code to solve my binary sequence classification problem.

My training input is a csv file (very large), the format of the csv file is:

```<code>binary_sequence(fixed sequence length of 100),result
1>0>1>1>0>0>0>0>...>0,1
0>1>0>1>0>0>0>0>...>0,0
...
0>1>0>1>0>0>0>0>...>0,0
</code>```

I need to train a classifier to classify new binary_sequences.

My test input is also a csv file in the similar format.

Anyone who can give suggestions on modifying the following code for my problem is much appreciated!

```<code># Example for my blog post at:
# https://danijar.com/introduction-to-recurrent-networks-in-tensorflow/
import functools
import sets
import tensorflow as tf

def lazy_property(function):
    attribute = '_' + function.__name__

    @property
    @functools.wraps(function)
    def wrapper(self):
        if not hasattr(self, attribute):
            setattr(self, attribute, function(self))
        return getattr(self, attribute)
    return wrapper

class SequenceClassification:

    def __init__(self, data, target, dropout, num_hidden=200, num_layers=3):
        self.data = data
        self.target = target
        self.dropout = dropout
        self._num_hidden = num_hidden
        self._num_layers = num_layers
        self.prediction
        self.error
        self.optimize

    @lazy_property
    def prediction(self):
        # Recurrent network.
        network = tf.contrib.rnn.GRUCell(self._num_hidden)
        network = tf.contrib.rnn.DropoutWrapper(
            network, output_keep_prob=self.dropout)
        network = tf.contrib.rnn.MultiRNNCell([network] * self._num_layers)
        output, _ = tf.nn.dynamic_rnn(network, self.data, dtype=tf.float32)
        # Select last output.
        output = tf.transpose(output, [1, 0, 2])
        last = tf.gather(output, int(output.get_shape()[0]) - 1)
        # Softmax layer.
        weight, bias = self._weight_and_bias(
            self._num_hidden, int(self.target.get_shape()[1]))
        prediction = tf.nn.softmax(tf.matmul(last, weight) + bias)
        return prediction

    @lazy_property
    def cost(self):
        cross_entropy = -tf.reduce_sum(self.target * tf.log(self.prediction))
        return cross_entropy

    @lazy_property
    def optimize(self):
        learning_rate = 0.003
        optimizer = tf.train.RMSPropOptimizer(learning_rate)
        return optimizer.minimize(self.cost)

    @lazy_property
    def error(self):
        mistakes = tf.not_equal(
            tf.argmax(self.target, 1), tf.argmax(self.prediction, 1))
        return tf.reduce_mean(tf.cast(mistakes, tf.float32))

    @staticmethod
    def _weight_and_bias(in_size, out_size):
        weight = tf.truncated_normal([in_size, out_size], stddev=0.01)
        bias = tf.constant(0.1, shape=[out_size])
        return tf.Variable(weight), tf.Variable(bias)

def main():
    # We treat images as sequences of pixel rows.
    train, test = sets.Mnist()
    _, rows, row_size = train.data.shape
    num_classes = train.target.shape[1]
    data = tf.placeholder(tf.float32, [None, rows, row_size])
    target = tf.placeholder(tf.float32, [None, num_classes])
    dropout = tf.placeholder(tf.float32)
    model = SequenceClassification(data, target, dropout)
    sess = tf.Session()
    sess.run(tf.global_variables_initializer())
    for epoch in range(10):
        for _ in range(100):
            batch = train.sample(10)
            sess.run(model.optimize, {
                data: batch.data, target: batch.target, dropout: 0.5})
        error = sess.run(model.error, {
            data: test.data, target: test.target, dropout: 1})
        print('Epoch {:2d} error {:3.1f}%'.format(epoch + 1, 100 * error))

if __name__ == '__main__':
    main()
</code>```

答:
Most of the code can be reused directly. The only thing you have to do is modify part of it to fit your data format. For instance,

```<code>num_classes = 2
data = tf.placeholder(tf.float32, [None, your_seq_length, your_feature_length])
batch = make_your_own_batch
</code>```

Look into the tutorial of your code. It is here. And if you're not familiar with RNN, here is a good introduction for you.

Body:
I get the following piece of code for TensorFlow Sequence Classification (See the code at the end of this quesiton):

https://gist.github.com/danijar/c7ec9a30052127c7a1ad169eeb83f159

I need to modify the code to solve my binary sequence classification problem.

My training input is a csv file (very large), the format of the csv file is:

binary_sequence(fixed sequence length of 100),result
1>0>1>1>0>0>0>0>...>0,1
0>1>0>1>0>0>0>0>...>0,0
...
0>1>0>1>0>0>0>0>...>0,0

I need to train a classifier to classify new binary_sequences.

My test input is also a csv file in the similar format.

Anyone who can give suggestions on modifying the following code for my problem is much appreciated!

# Example for my blog post at:
# https://danijar.com/introduction-to-recurrent-networks-in-tensorflow/
import functools
import sets
import tensorflow as tf

def lazy_property(function):
    attribute = '_' + function.__name__

    @property
    @functools.wraps(function)
    def wrapper(self):
        if not hasattr(self, attribute):
            setattr(self, attribute, function(self))
        return getattr(self, attribute)
    return wrapper

class SequenceClassification:

    def __init__(self, data, target, dropout, num_hidden=200, num_layers=3):
        self.data = data
        self.target = target
        self.dropout = dropout
        self._num_hidden = num_hidden
        self._num_layers = num_layers
        self.prediction
        self.error
        self.optimize

    @lazy_property
    def prediction(self):
        # Recurrent network.
        network = tf.contrib.rnn.GRUCell(self._num_hidden)
        network = tf.contrib.rnn.DropoutWrapper(
            network, output_keep_prob=self.dropout)
        network = tf.contrib.rnn.MultiRNNCell([network] * self._num_layers)
        output, _ = tf.nn.dynamic_rnn(network, self.data, dtype=tf.float32)
        # Select last output.
        output = tf.transpose(output, [1, 0, 2])
        last = tf.gather(output, int(output.get_shape()[0]) - 1)
        # Softmax layer.
        weight, bias = self._weight_and_bias(
            self._num_hidden, int(self.target.get_shape()[1]))
        prediction = tf.nn.softmax(tf.matmul(last, weight) + bias)
        return prediction

    @lazy_property
    def cost(self):
        cross_entropy = -tf.reduce_sum(self.target * tf.log(self.prediction))
        return cross_entropy

    @lazy_property
    def optimize(self):
        learning_rate = 0.003
        optimizer = tf.train.RMSPropOptimizer(learning_rate)
        return optimizer.minimize(self.cost)

    @lazy_property
    def error(self):
        mistakes = tf.not_equal(
            tf.argmax(self.target, 1), tf.argmax(self.prediction, 1))
        return tf.reduce_mean(tf.cast(mistakes, tf.float32))

    @staticmethod
    def _weight_and_bias(in_size, out_size):
        weight = tf.truncated_normal([in_size, out_size], stddev=0.01)
        bias = tf.constant(0.1, shape=[out_size])
        return tf.Variable(weight), tf.Variable(bias)

def main():
    # We treat images as sequences of pixel rows.
    train, test = sets.Mnist()
    _, rows, row_size = train.data.shape
    num_classes = train.target.shape[1]
    data = tf.placeholder(tf.float32, [None, rows, row_size])
    target = tf.placeholder(tf.float32, [None, num_classes])
    dropout = tf.placeholder(tf.float32)
    model = SequenceClassification(data, target, dropout)
    sess = tf.Session()
    sess.run(tf.global_variables_initializer())
    for epoch in range(10):
        for _ in range(100):
            batch = train.sample(10)
            sess.run(model.optimize, {
                data: batch.data, target: batch.target, dropout: 0.5})
        error = sess.run(model.error, {
            data: test.data, target: test.target, dropout: 1})
        print('Epoch {:2d} error {:3.1f}%'.format(epoch + 1, 100 * error))

if __name__ == '__main__':
    main()

Body:
Most of the code can be reused directly. The only thing you have to do is modify part of it to fit your data format. For instance,

num_classes = 2
data = tf.placeholder(tf.float32, [None, your_seq_length, your_feature_length])
batch = make_your_own_batch

Look into the tutorial of your code. It is here. And if you're not familiar with RNN, here is a good introduction for you.


问:
Set integer value in a column for threshold integer in another column?
The objective is to set an integer threshold using values from Column B and recording those thresholds in Column C. The thresholds are -1 and 1 in Column B  concluding upon crossing 0, to record values of -1 and 1 in Column C. The resulting DataFrame will be:

```<code>    A     B      C
 1  D   0.25     0
 2  D   0.50     0
 3  D   0.75     0
 4  D   1.00     1
 5  D   1.25     1
 6  D   1.75     1
 7  D   0.50     1
 8  D  -0.25     0
 9  D   1.25     1
10  D   0.75     1
11  D  -0.75     0
12  D  -1.00    -1
13  D  -1.50    -1
14  D  -2.00    -1
14  D  -0.75    -1
14  D   0.00     0
</code>```

So far I have tried an implementation with .bins() for the DataFrame, but it does not really iterate through or comprehend the series, rather just setting values for bins. This code is:

```<code>df['C'] = 0

bins = [-1,0, 1] #with values from df['B']

group_names = [-1,0, 1] #with values from df['B']

g = pd.cut(group_em['B'], bins, labels = group_names)
g= g.fillna(0)
</code>```

Body:
The objective is to set an integer threshold using values from Column B and recording those thresholds in Column C. The thresholds are -1 and 1 in Column B  concluding upon crossing 0, to record values of -1 and 1 in Column C. The resulting DataFrame will be:

    A     B      C
 1  D   0.25     0
 2  D   0.50     0
 3  D   0.75     0
 4  D   1.00     1
 5  D   1.25     1
 6  D   1.75     1
 7  D   0.50     1
 8  D  -0.25     0
 9  D   1.25     1
10  D   0.75     1
11  D  -0.75     0
12  D  -1.00    -1
13  D  -1.50    -1
14  D  -2.00    -1
14  D  -0.75    -1
14  D   0.00     0

So far I have tried an implementation with .bins() for the DataFrame, but it does not really iterate through or comprehend the series, rather just setting values for bins. This code is:

df['C'] = 0

bins = [-1,0, 1] #with values from df['B']

group_names = [-1,0, 1] #with values from df['B']

g = pd.cut(group_em['B'], bins, labels = group_names)
g= g.fillna(0)

Body:
You might try something like this, use numpy.where:

import numpy as np
df['C'] = np.where(df.B >= 1, 1,              # if B >= 1 then C is 1
          np.where(df.B <= -1, -1,            # if B <= -1 then C is -1
          np.where(np.sign(df.B).diff() != 0, 0, np.nan)))    # else if B changes sign
          # (cross zero) then C is 0 otherwise C is nan

df.ffill()                                    # fill nan with previous values

#   A       B      C
#1  D    0.25    0.0
#2  D    0.50    0.0
#3  D    0.75    0.0
#4  D    1.00    1.0
#5  D    1.25    1.0
#6  D    1.75    1.0
#7  D    0.50    1.0
#8  D   -0.25    0.0
#9  D    1.25    1.0
#10 D    0.75    1.0
#11 D   -0.75    0.0
#12 D   -1.00   -1.0
#13 D   -1.50   -1.0
#14 D   -2.00   -1.0
#14 D   -0.75   -1.0
#14 D    0.00    0.0


问:
Can I post an inline image using file field in a form
I have an IMG loaded inside the HTML document, and I would like to upload it using the "file" field from a form. The form is in the same document, so I shouldn't have any security issues.

Is it possible to upload the image to a server?

I managed to upload images choosing a file from my hard drive, but I have no clue about doing it using the IMG inside the HTML document.

答:
No, that is not possible, as the HTML form will only upload files from your computer.

If you can display the image on your form page, why can't you reference its url in a hidden form field an access this field later.

So, your image would for example be , then you could insert a field in your form that goes something like:

```<code><input type="hidden" value="URL" name="my_image"/>
</code>```

Upon submission of the form, you can access the URL of the image through the POST or GET parameters, in PHP or any language you're using. It would be best to URL-encode the URL to the image beforehand.

ContentLicense: CC BY-SA 2.5

Body:
No, that is not possible, as the HTML form will only upload files from your computer.

If you can display the image on your form page, why can't you reference its url in a hidden form field an access this field later.

So, your image would for example be <img src="URL"/>, then you could insert a field in your form that goes something like:

<input type="hidden" value="URL" name="my_image"/>

Upon submission of the form, you can access the URL of the image through the POST or GET parameters, in PHP or any language you're using. It would be best to URL-encode the URL to the image beforehand.


问:
NodeJS unable to read default CAs in ubuntu
On our testing environment we are connecting to another server with SSL signed by our company. Every time connection is made nodejs throws
UNABLE_TO_VERIFY_LEAF_SIGNATURE.
I have found workarounds by setting rejectUnauthorized: false, but this is not aplicable in our case.

The certificates are added to /etc/ssl/certs and tested with the environment variable SSL_CERT_DIR to be either /etc/ssl anb /etc/ssl/certs, but no result.

Also, it is not preferable to add somewhere in our files the certificate and add it to every request.

答:
You can also add a path to your certificates in PEM file format using the NODE_EXTRA_CA_CERTS environment variable starting with node v7.3.0

https://nodejs.org/api/cli.html#cli_node_extra_ca_certs_file

This has the benefit of not requiring any code changes, just change the environment of your node process. Hope this helps!

Edit:

Also check out --use-openssl-ca https://nodejs.org/api/cli.html#cli_use_openssl_ca_use_bundled_ca

That's what I ended up using to solve my problem. I copied my .crt files to /usr/local/share/ca-certificates then ran sudo update-ca-certificates and then run node with --use-openssl-ca and now node finds my certificates properly.


问:
How do I change text within
 tags with Javascript?

I need some help on editing elements which are in HTML with JavaScript. Is it possible to change the "text" with javascript? I've tried using document.getElementById but I don't think I'm doing it correctly.

答:
Simple example with "press me" button that calls a function to change text

```<code><html>
<script>
    function changeText(){
        document.getElementById("header").innerHTML = "changed text";
    };
</script>
<body>
    <div id="header">text</div>
    <button onclick="changeText()">press me</button>
</body>
</code>```

text

  <button onclick="changeText()">press me</button>

```

Title: How do I change text within <div> tags with Javascript?

Body:
Simple example with "press me" button that calls a function to change text

<html>
<script>
    function changeText(){
        document.getElementById("header").innerHTML = "changed text";
    };
</script>
<body>
    <div id="header">text</div>
    <button onclick="changeText()">press me</button>
</body>

<html>
 <script>
  function changeText(){
   document.getElementById("header").innerHTML = "changed text";
  };
 </script>
 <body>
  <div id="header">text</div>
  <button onclick="changeText()">press me</button>
 </body>
</html>


问:
Excel Time to SQL Time
I am having some trouble inserting time into SQLServer

The data type in SQLServer is time(0). I have the time in excel as 10:29:42. (It is in 24-hour format)When I insert it into SQL the actual value being inserted is 0.4372917

I get an error and the insert fails.Is there any way in VBA to have the actual value as `10:29:42'? This is my current code I use to copy from one sheet to another:

```<code>Test Time
Dim tt As String
tt = raw.Range("A7")
master.Range("F2") = tt
</code>```

My insert Code is such:

```<code>Insert into Date_t( Date) Values(ActiveSheet.Range("F2"))
</code>```

答:
In SSMS this works fine:</p>

```<code>select cast('10:21:50' as time)
</code>```

Title: Excel Time to SQL Time

Body:
I am having some trouble inserting time into SQLServer

The data type in SQLServer is time(0). I have the time in excel as 10:29:42. (It is in 24-hour format)When I insert it into SQL the actual value being inserted is 0.4372917

I get an error and the insert fails.Is there any way in VBA to have the actual value as `10:29:42'? This is my current code I use to copy from one sheet to another:

Test Time
Dim tt As String
tt = raw.Range("A7")
master.Range("F2") = tt

My insert Code is such:

Insert into Date_t( Date) Values(ActiveSheet.Range("F2"))

Body:
In SSMS this works fine:

select cast('10:21:50' as time)


问:
OperationCanceledException when sending to Service Bus
I am getting OperationCanceledException when I am sending a message to a topic queue (I am running my code from within an Azure function).
The version I am using is:  "WindowsAzure.ServiceBus": "4.1.1" (latest)
and I am getting this exception when I am doing load testing which means many messages are being sent in this service bus (which contains several topics).
I was told to use a retry mechanism as:

```<code>client.RetryPolicy = new RetryExponential(minBackoff: TimeSpan.FromSeconds(0.1),
                                            maxBackoff: TimeSpan.FromSeconds(30),
                                            maxRetryCount: 3);
</code>```

But I thought this is already done by default, doesn't it?

Would appropriate your help here - Why am I getting this exception and what can I do to resolve this?

Here is the exception:

```<code>Exception System.OperationCanceledException: The operation cannot be performed because the entity has been closed or aborted. ---> System.ServiceModel.CommunicationObjectAbortedException: Internal Server Error: The server did not provide a meaningful reply; this might be caused by a premature session shutdown. TrackingId:88386cb1-a4e6-42e2-a8e1-bad3a2403329, Timestamp:6/6/2017 7:55:23 AM
   at Microsoft.ServiceBus.Common.AsyncResult.End[TAsyncResult](IAsyncResult result)
   at Microsoft.ServiceBus.Messaging.Sbmp.DuplexRequestBindingElement.DuplexRequestSessionChannel.EndRequest(IAsyncResult result)
   at Microsoft.ServiceBus.Messaging.Channels.ReconnectBindingElement.ReconnectChannelFactory`1.RequestSessionChannel.RequestAsyncResult.<>c.<GetAsyncSteps>b__9_3(RequestAsyncResult thisPtr, IAsyncResult r)
   at Microsoft.ServiceBus.Messaging.IteratorAsyncResult`1.StepCallback(IAsyncResult result)
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.ServiceBus.Common.AsyncResult.End[TAsyncResult](IAsyncResult result)
   at Microsoft.ServiceBus.Messaging.Channels.ReconnectBindingElement.ReconnectChannelFactory`1.RequestSessionChannel.EndRequest(IAsyncResult result)
   at Microsoft.ServiceBus.Messaging.Sbmp.RedirectBindingElement.RedirectContainerChannelFactory`1.RedirectContainerSessionChannel.RequestAsyncResult.<>c__DisplayClass8_1.<GetAsyncSteps>b__4(RequestAsyncResult thisPtr, IAsyncResult r)
   at Microsoft.ServiceBus.Messaging.IteratorAsyncResult`1.StepCallback(IAsyncResult result)
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.ServiceBus.Common.AsyncResult.End[TAsyncResult](IAsyncResult result)
   at Microsoft.ServiceBus.Messaging.Sbmp.RedirectBindingElement.RedirectContainerChannelFactory`1.RedirectContainerSessionChannel.EndRequest(IAsyncResult result)
   at Microsoft.ServiceBus.Messaging.Channels.ReconnectBindingElement.ReconnectChannelFactory`1.RequestSessionChannel.RequestAsyncResult.<>c.<GetAsyncSteps>b__9_3(RequestAsyncResult thisPtr, IAsyncResult r)
   at Microsoft.ServiceBus.Messaging.IteratorAsyncResult`1.StepCallback(IAsyncResult result)
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.ServiceBus.Common.AsyncResult.End[TAsyncResult](IAsyncResult result)
   at Microsoft.ServiceBus.Messaging.Channels.ReconnectBindingElement.ReconnectChannelFactory`1.RequestSessionChannel.EndRequest(IAsyncResult result)
   at Microsoft.ServiceBus.Messaging.Sbmp.SbmpTransactionalAsyncResult`1.<>c.<GetAsyncSteps>b__18_3(TIteratorAsyncResult thisPtr, IAsyncResult a)
   at Microsoft.ServiceBus.Messaging.IteratorAsyncResult`1.StepCallback(IAsyncResult result)
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.ServiceBus.Common.AsyncResult.End[TAsyncResult](IAsyncResult result)
   at Microsoft.ServiceBus.Messaging.Sbmp.SbmpMessageSender.EndSendCommand(IAsyncResult result)
   --- End of inner exception stack trace ---
   at Microsoft.ServiceBus.Messaging.Sbmp.SbmpMessageSender.EndSendCommand(IAsyncResult result)
   at Microsoft.ServiceBus.Messaging.Sbmp.SbmpMessageSender.OnEndSend(IAsyncResult result)
   at Microsoft.ServiceBus.Messaging.IteratorAsyncResult`1.StepCallback(IAsyncResult result)
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.ServiceBus.Common.AsyncResult.End[TAsyncResult](IAsyncResult result)
   at Microsoft.ServiceBus.Messaging.MessageSender.OnSend(TrackingContext trackingContext, IEnumerable`1 messages, TimeSpan timeout)
   at Microsoft.ServiceBus.Messaging.MessageSender.Send(TrackingContext trackingContext, IEnumerable`1 messages, TimeSpan timeout)
</code>```

答:
Retry policy is enabled by the ASB client by default. You don't nee to do it yourself.

Exception you get is OperationCanceledException and according to documentation:

Retry will not help.

Which is categorized as "User coding error". Looking at the exception stack trace, this is happening during send operation and the error is

Internal Server Error: The server did not provide a meaningful reply; this might be caused by a premature session shutdown. TrackingId:88386cb1-a4e6-42e2-a8e1-bad3a2403329...

I'm quite sure this is not user code error, but something that took place on the broker side. The TrackingId supplied with the error should allow you to open a support case with Microsoft to at least have an idea what happened on the broker when that command failed.

Edit

Meanwhile what I would suggest it to implement your operation with an additional retry/backoff logic. Something that would not retry in a tight loop and would not depend on the client's RetryPolicy.

Body:
I am getting OperationCanceledException when I am sending a message to a topic queue (I am running my code from within an Azure function).
The version I am using is:  "WindowsAzure.ServiceBus": "4.1.1" (latest)
and I am getting this exception when I am doing load testing which means many messages are being sent in this service bus (which contains several topics).
I was told to use a retry mechanism as:

client.RetryPolicy = new RetryExponential(minBackoff: TimeSpan.FromSeconds(0.1),
                                            maxBackoff: TimeSpan.FromSeconds(30),
                                            maxRetryCount: 3);

But I thought this is already done by default, doesn't it?

Would appropriate your help here - Why am I getting this exception and what can I do to resolve this?

Here is the exception:

Exception System.OperationCanceledException: The operation cannot be performed because the entity has been closed or aborted. ---> System.ServiceModel.CommunicationObjectAbortedException: Internal Server Error: The server did not provide a meaningful reply; this might be caused by a premature session shutdown. TrackingId:88386cb1-a4e6-42e2-a8e1-bad3a2403329, Timestamp:6/6/2017 7:55:23 AM
   at Microsoft.ServiceBus.Common.AsyncResult.End[TAsyncResult](IAsyncResult result)
   at Microsoft.ServiceBus.Messaging.Sbmp.DuplexRequestBindingElement.DuplexRequestSessionChannel.EndRequest(IAsyncResult result)
   at Microsoft.ServiceBus.Messaging.Channels.ReconnectBindingElement.ReconnectChannelFactory`1.RequestSessionChannel.RequestAsyncResult.<>c.<GetAsyncSteps>b__9_3(RequestAsyncResult thisPtr, IAsyncResult r)
   at Microsoft.ServiceBus.Messaging.IteratorAsyncResult`1.StepCallback(IAsyncResult result)
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.ServiceBus.Common.AsyncResult.End[TAsyncResult](IAsyncResult result)
   at Microsoft.ServiceBus.Messaging.Channels.ReconnectBindingElement.ReconnectChannelFactory`1.RequestSessionChannel.EndRequest(IAsyncResult result)
   at Microsoft.ServiceBus.Messaging.Sbmp.RedirectBindingElement.RedirectContainerChannelFactory`1.RedirectContainerSessionChannel.RequestAsyncResult.<>c__DisplayClass8_1.<GetAsyncSteps>b__4(RequestAsyncResult thisPtr, IAsyncResult r)
   at Microsoft.ServiceBus.Messaging.IteratorAsyncResult`1.StepCallback(IAsyncResult result)
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.ServiceBus.Common.AsyncResult.End[TAsyncResult](IAsyncResult result)
   at Microsoft.ServiceBus.Messaging.Sbmp.RedirectBindingElement.RedirectContainerChannelFactory`1.RedirectContainerSessionChannel.EndRequest(IAsyncResult result)
   at Microsoft.ServiceBus.Messaging.Channels.ReconnectBindingElement.ReconnectChannelFactory`1.RequestSessionChannel.RequestAsyncResult.<>c.<GetAsyncSteps>b__9_3(RequestAsyncResult thisPtr, IAsyncResult r)
   at Microsoft.ServiceBus.Messaging.IteratorAsyncResult`1.StepCallback(IAsyncResult result)
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.ServiceBus.Common.AsyncResult.End[TAsyncResult](IAsyncResult result)
   at Microsoft.ServiceBus.Messaging.Channels.ReconnectBindingElement.ReconnectChannelFactory`1.RequestSessionChannel.EndRequest(IAsyncResult result)
   at Microsoft.ServiceBus.Messaging.Sbmp.SbmpTransactionalAsyncResult`1.<>c.<GetAsyncSteps>b__18_3(TIteratorAsyncResult thisPtr, IAsyncResult a)
   at Microsoft.ServiceBus.Messaging.IteratorAsyncResult`1.StepCallback(IAsyncResult result)
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.ServiceBus.Common.AsyncResult.End[TAsyncResult](IAsyncResult result)
   at Microsoft.ServiceBus.Messaging.Sbmp.SbmpMessageSender.EndSendCommand(IAsyncResult result)
   --- End of inner exception stack trace ---
   at Microsoft.ServiceBus.Messaging.Sbmp.SbmpMessageSender.EndSendCommand(IAsyncResult result)
   at Microsoft.ServiceBus.Messaging.Sbmp.SbmpMessageSender.OnEndSend(IAsyncResult result)
   at Microsoft.ServiceBus.Messaging.IteratorAsyncResult`1.StepCallback(IAsyncResult result)
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.ServiceBus.Common.AsyncResult.End[TAsyncResult](IAsyncResult result)
   at Microsoft.ServiceBus.Messaging.MessageSender.OnSend(TrackingContext trackingContext, IEnumerable`1 messages, TimeSpan timeout)
   at Microsoft.ServiceBus.Messaging.MessageSender.Send(TrackingContext trackingContext, IEnumerable`1 messages, TimeSpan timeout)


问:
How can I change Angular Material button background color on hover state?
I have an Angular button:

```<code><button md-button class="link-btn" >Cancel</button>

.link-btn {
  background-color: transparent;
  background-repeat: no-repeat;
  border: none;
  cursor:pointer;
  overflow: hidden;
  outline:none;
  font-size: 0.8em;
  padding: 0px;
}

.link-btn:hover {
  background-color: transparent;
  background-repeat: no-repeat;
  border: none;
  cursor:pointer;
  overflow: hidden;
  outline:none;
  font-size: 0.8em;
  padding: 0px;
}
</code>```

Normally it is setting transparent background, but in hover state, gray background is shown? How to remove that?

答:
Try adding the following to your css...

```<code>.mat-button-focus-overlay {
    background-color:transparent;
}
</code>```

Or

```<code>.mat-menu-item:hover {
     background-color:transparent;
}
</code>```

Body:
I have an Angular button:

<button md-button class="link-btn" >Cancel</button>

.link-btn {
  background-color: transparent;
  background-repeat: no-repeat;
  border: none;
  cursor:pointer;
  overflow: hidden;
  outline:none;
  font-size: 0.8em;
  padding: 0px;
}

.link-btn:hover {
  background-color: transparent;
  background-repeat: no-repeat;
  border: none;
  cursor:pointer;
  overflow: hidden;
  outline:none;
  font-size: 0.8em;
  padding: 0px;
}

Normally it is setting transparent background, but in hover state, gray background is shown? How to remove that?

Body:
Try adding the following to your css...

.mat-button-focus-overlay {
    background-color:transparent;
}

Or

.mat-menu-item:hover {
     background-color:transparent;
}


问:
How to sleep for five seconds in a batch file/cmd
Windows's Snipping tool can capture the screen, but sometimes I want to capture the screen after five seconds, such as taking an image being displayed by the webcam. (Run the script and smile at the camera, for example.)

How do I sleep for 5 seconds in a batch file?

答:
I wrote a powerbasic program wait.exe, where you pass a millisecond parameter to it in your batch file

```<code>wait 3000
system('c:/windows/system32/SnippingTool.exe')
</code>```

the code for the EXE:

```<code>FUNCTION PBMAIN()
  c$ = Command$
  s! = Val(c$)*1000
  Sleep s!
END FUNCTION
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I wrote a powerbasic program wait.exe, where you pass a millisecond parameter to it in your batch file

wait 3000
system('c:/windows/system32/SnippingTool.exe')

the code for the EXE:

FUNCTION PBMAIN()
  c$ = Command$
  s! = Val(c$)*1000
  Sleep s!
END FUNCTION


问:
Consistent JSR-303 validation with optional properties in Spring controllers and Spring webflow?
Let's say I have a Model Bean "Vendor" with the mandatory property "name" and an optional property "email".

```<code>class Vendor {

    @Email
    private String email;

    @NotNull
    private String name;

}
</code>```

@Email allows Null!

I want to use hibernate-validation in my @Controller and in my flows as well. I have in both scenarios the problem that a posted form with an empty field for email binds with "" and not NULL.

StringTrimmerEditor seems to solve my problem by converting "" into NULL. For my @Controller I found SPR-7077 which suggests implementing StringTrimmerEditor globally with @ControllerAdvice. But this doesn't work for my flows.

How do I achieve that globally empty Strings ("") are converted into NULL for JSR-303 validation in spring webflow?

答:
you can create annotation contains @ConstraintComposition if you want to using optional field.
For example:

```<code>import org.hibernate.validator.constraints.ConstraintComposition;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotBlank;
@ConstraintComposition
@Target({METHOD, FIELD, ANNOTATION_TYPE})
@Retention(RUNTIME)
@Constraint(validatedBy = {})
@Documented

@NotBlank
@Length(min = 1, max = 5)
@Pattern(regexp = "[A-Z]*")
public @interface SpecialField {
    String message() default "{}";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}
</code>```

and

```<code>@ConstraintComposition(OR)
@Target({METHOD, FIELD, ANNOTATION_TYPE})
@Retention(RUNTIME)
@Constraint(validatedBy = {})
@Documented

@Null
@SpecialField
public @interface OptionalSpecialField {

    String message() default "{}";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}
</code>```

and after that mark optional filed that:

```<code>class NewUser {

    @OptionalSpecialField
    private String firstName;

    @SpecialField
    private String lastName;

    @Min(18)
    private Integer age;
}
</code>```

First name is not required but if is not null then have to be not blank, match pattern, etc.

All example is on here: https://github.com/lukaszguz/optional-field-validation/tree/master/src/main/java/pl/guz/domain/validation

Body:
Let's say I have a Model Bean "Vendor" with the mandatory property "name" and an optional property "email".

class Vendor {

    @Email
    private String email;

    @NotNull
    private String name;

}

@Email allows Null!

I want to use hibernate-validation in my @Controller and in my flows as well. I have in both scenarios the problem that a posted form with an empty field for email binds with "" and not NULL.

StringTrimmerEditor seems to solve my problem by converting "" into NULL. For my @Controller I found SPR-7077 which suggests implementing StringTrimmerEditor globally with @ControllerAdvice. But this doesn't work for my flows.

How do I achieve that globally empty Strings ("") are converted into NULL for JSR-303 validation in spring webflow?

Body:
you can create annotation contains @ConstraintComposition if you want to using optional field.
For example:

import org.hibernate.validator.constraints.ConstraintComposition;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotBlank;
@ConstraintComposition
@Target({METHOD, FIELD, ANNOTATION_TYPE})
@Retention(RUNTIME)
@Constraint(validatedBy = {})
@Documented

@NotBlank
@Length(min = 1, max = 5)
@Pattern(regexp = "[A-Z]*")
public @interface SpecialField {
    String message() default "{}";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

and

@ConstraintComposition(OR)
@Target({METHOD, FIELD, ANNOTATION_TYPE})
@Retention(RUNTIME)
@Constraint(validatedBy = {})
@Documented

@Null
@SpecialField
public @interface OptionalSpecialField {

    String message() default "{}";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

and after that mark optional filed that:

class NewUser {

    @OptionalSpecialField
    private String firstName;

    @SpecialField
    private String lastName;

    @Min(18)
    private Integer age;
}

First name is not required but if is not null then have to be not blank, match pattern, etc.

All example is on here: https://github.com/lukaszguz/optional-field-validation/tree/master/src/main/java/pl/guz/domain/validation


问:
eclipse settings for editor tabs
Java class editing - In IntelliJ I am able to set preferences so only one editor tab at a time is open. I use command-O to type in the next class and only one tab stays open.

In STS (eclipse), I would like cntl-shift-R to open a new class and not leave the last class tab editor open. Only one editor tab stays open is my preference.

To be clear, I have searched extensively through the Eclipse doc and Googled for it, but I just can't find the right setting reference.

Any ideas?

答:
Eclipse has an option to automatically close non-dirty editors. Find it in the Preferences under General > Editors, the setting is labeled Close editors automatically.

When you enable that, you can choose the max number of editor tabs to keep open; to satisfy your need, set it to 1.

The Help docs for that are here.

Title: eclipse settings for editor tabs


问:
How to scroll softly not rapidly at once
I am begginer in html and want to ask how to move to an id in html which is targeted by an anchor tag for example:

When I run this code, it rapidly goes to targeted id although I want to go with animations. How can I do this?

答:
You can achieve this using jQuery.

Here's the code to perform a smooth page scroll to an anchor on the same page. It has some logic built in to identify those jump links, and not target other links.

```<code>// Select all links with hashes
$('a[href*="#"]')
  // Remove links that don't actually link to anything
  .not('[href="#"]')
  .not('[href="#0"]')
  .click(function(event) {
    // On-page links
    if (
      location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '')
      &&
      location.hostname == this.hostname
    ) {
      // Figure out element to scroll to
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
      // Does a scroll target exist?
      if (target.length) {
        // Only prevent default if animation is actually gonna happen
        event.preventDefault();
        $('html, body').animate({
          scrollTop: target.offset().top
        }, 1000, function() {
          // Callback after animation
          // Must change focus!
          var $target = $(target);
          $target.focus();
          if ($target.is(":focus")) { // Checking if the target was focused
            return false;
          } else {
            $target.attr('tabindex','-1'); // Adding tabindex for elements not focusable
            $target.focus(); // Set focus again
          };
        });
      }
    }
  });
</code>```

Body:
You can achieve this using jQuery.

Here's the code to perform a smooth page scroll to an anchor on the same page. It has some logic built in to identify those jump links, and not target other links.

// Select all links with hashes
$('a[href*="#"]')
  // Remove links that don't actually link to anything
  .not('[href="#"]')
  .not('[href="#0"]')
  .click(function(event) {
    // On-page links
    if (
      location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '')
      &&
      location.hostname == this.hostname
    ) {
      // Figure out element to scroll to
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
      // Does a scroll target exist?
      if (target.length) {
        // Only prevent default if animation is actually gonna happen
        event.preventDefault();
        $('html, body').animate({
          scrollTop: target.offset().top
        }, 1000, function() {
          // Callback after animation
          // Must change focus!
          var $target = $(target);
          $target.focus();
          if ($target.is(":focus")) { // Checking if the target was focused
            return false;
          } else {
            $target.attr('tabindex','-1'); // Adding tabindex for elements not focusable
            $target.focus(); // Set focus again
          };
        });
      }
    }
  });


问:
retrieve cross sell product in woocommerce
I have been here for the last 5 hours trying to figure out something. I need to be able to fetch the cross sell id of a product in the woo commerce in the order confirmation email. Up to now I have

```<code>         $items = $order->get_items();
        foreach ( $items as $item ) {
            $product_id = $item['product_id'];
            }
</code>```

And this retrive the id of the product. As there is always just going to be one cross sell product how can I get the id of that product in a variable?

This will be the last part of an affiliated program I am building for a guy but I now if fetches the purchased product id and I need the cross-sell one.

答:
```<code><?php global $product;
$cross_sell_ids = $product->get_cross_sell_ids(); ?>
</code>```

Body:
I have been here for the last 5 hours trying to figure out something. I need to be able to fetch the cross sell id of a product in the woo commerce in the order confirmation email. Up to now I have

         $items = $order->get_items();
        foreach ( $items as $item ) {
            $product_id = $item['product_id'];
            }

And this retrive the id of the product. As there is always just going to be one cross sell product how can I get the id of that product in a variable?

This will be the last part of an affiliated program I am building for a guy but I now if fetches the purchased product id and I need the cross-sell one.


答:
if querySelectorAll or getElementsbyClassName there are many ways to alter the text.

My answer is that you must think about your structure of the HTML Document.

You can use every ID only once. It is better to use data-lb="detail" etc. and classes for the div´s

Please see this not as an answer only as an tip.

Body: I need some help on editing elements which are in HTML with JavaScript. Is it possible to change the "text" with javascript? I've tried using document.getElementById but I don't think I'm doing it correctly.


问:
Zurb Foundation javascript reInit module not working
i'm ajaxifying a website. My menu should always be sticky (using the sticky module provided by Foundation). But it is only sticky on a regular page load, and not on ajax reload (aka when navigating on the website)
I'm trying to re-initialise the module when the event ajaxComplete happens, using the line provided in the documentation of Foundation 6:

```<code>$(document).ajaxComplete(function () {
    Foundation.reInit($('.sticky'));
    //other code
});
</code>```

But it doesn't seem to work, because I get this error in the console :

```<code>TypeError: Cannot read property '_init' of undefined
    at HTMLElement.<anonymous> (foundation.core.js:103)
    at Function.each (jquery.min.js?ver=2.1.0:2)
    at o.fn.init.each (jquery.min.js?ver=2.1.0:2)
    at Object.reInit (foundation.core.js:102)
    at HTMLDocument.<anonymous> (stickyfooter.js:28)
    at HTMLDocument.dispatch (jquery.min.js?ver=2.1.0:3)
    at HTMLDocument.r.handle (jquery.min.js?ver=2.1.0:3)
    at Object.trigger (jquery.min.js?ver=2.1.0:3)
    at x (jquery.min.js?ver=2.1.0:4)
    at XMLHttpRequest.<anonymous> (jquery.min.js?ver=2.1.0:4)
</code>```

Which I don't understand. What does it mean ? How can I make the module work after an ajax reload ?
The website in action : http://lesdeuxvagues.com/demo

答:
Ok, so it's apparently a known issue in zurb-foundation, the sticky module doesn't work after being destroyed (though I don't know why it's destroyed in my case because i'm only reloading other content with AJAX), all the other foundation js plugin seem to be working though. (see : https://github.com/zurb/foundation-sites/issues/9047)

The solution that I will try is to just find another sticky library to take care of this particular issue.

Body:
i'm ajaxifying a website. My menu should always be sticky (using the sticky module provided by Foundation). But it is only sticky on a regular page load, and not on ajax reload (aka when navigating on the website)
I'm trying to re-initialise the module when the event ajaxComplete happens, using the line provided in the documentation of Foundation 6:

$(document).ajaxComplete(function () {
    Foundation.reInit($('.sticky'));
    //other code
});

But it doesn't seem to work, because I get this error in the console :

TypeError: Cannot read property '_init' of undefined
    at HTMLElement.<anonymous> (foundation.core.js:103)
    at Function.each (jquery.min.js?ver=2.1.0:2)
    at o.fn.init.each (jquery.min.js?ver=2.1.0:2)
    at Object.reInit (foundation.core.js:102)
    at HTMLDocument.<anonymous> (stickyfooter.js:28)
    at HTMLDocument.dispatch (jquery.min.js?ver=2.1.0:3)
    at HTMLDocument.r.handle (jquery.min.js?ver=2.1.0:3)
    at Object.trigger (jquery.min.js?ver=2.1.0:3)
    at x (jquery.min.js?ver=2.1.0:4)
    at XMLHttpRequest.<anonymous> (jquery.min.js?ver=2.1.0:4)

Which I don't understand. What does it mean ? How can I make the module work after an ajax reload ?
The website in action : http://lesdeuxvagues.com/demo


问:
CSS: element should get max-width before breaking words
There are CSS tooltips (codepen is given below). They have min-width and max-width. They contain sometimes short phrases, sometimes very long words without breaks. This is what happens if there is white-space: nowrap => Short tooltips are rendered perfectly, but long ones, obviously, are not wrapped and are not fully visible:

This is what happens when I add white-space: normal and word-break: break-word => Now short ones and long ones get wrapped long before getting to the max-width:

What I would like to achieve is:
Tooltips don't wrap before getting to the max-width. And start wrapping only if they don't get into the max-width. Like here:

Is it possible to get this behaviour just with CSS (no javascript)?

Here is the codepen: https://codepen.io/anon/pen/bWXobM
(Uncomment lines 58-59 to change the behaviour.)

I didn't manage to achieve this with any of the found solutions. If you know how to apply them in this case, please share!

Update: apparently some kind of solution to this problem has just been added to the wg draft: https://github.com/w3c/csswg-drafts/issues/1171. It is still interesting if someone found a workaround for now.

答: Don't use word-break: break-word as it is breaking every word to new line, instead use overflow-wrap: break-word; and white-space: normal.


问:
htaccess 301 redirect not redirecting
tried several ways to make redirect, but not successfull

```<code>Redirect 301 /ru/pages/portfolio/ /ru/pages/portfolio/3/ [END,R=301]
</code>```

or

```<code>Redirect 301 http://myssite/en/pages/portfolio http://myssite/en/pages/portfolio/3
</code>```

and many others from internet, but all of them not working.
Need to redirect pages/portfolio to pages/portfolio/3 (for all languages - en, ru)

This is content of file

```<code><IfModule mod_rewrite.c>

  # Turn Off mod_dir Redirect For Existing Directories
  DirectorySlash Off
  # Rewrite For Public Folder
  RewriteEngine on

 Redirect 301 /ru/pages/portfolio/ /ru/pages/portfolio/3/ [END,R=301]

  RewriteCond $1 !^(pma)
  RewriteRule ^(.*)$ public/$1 [L]
</IfModule>
</code>```

答:
Since you are already using mod_rewrite (for an internal rewrite) you should also use mod_rewrite for this redirect, rather than using a mod_alias Redirect. Different modules execute at different times during the request, despite the apparent order of the directives in the config file.

However, your example is unclear. The first example includes a trailing slash; the second does not? Is there a trailing slash or not?

Try something like the following instead after the RewriteEngine directive:

```<code>RewriteRule ^(en|ru)/pages/portfolio$ /$1/pages/portfolio/3 [R,L]
</code>```

This excludes the trailing slash. And assumes "all languages" are just en and ru. This is also a temporary (302) redirect. Change to a permanent (301) redirect (if that is the intention) only when you are sure it's working OK, since 301s are cached by the browser. You will need to clear your browser cache before testing.

```<code>Redirect 301 /ru/pages/portfolio/ /ru/pages/portfolio/3/ [END,R=301]
:
Redirect 301 http://myssite/en/pages/portfolio http://myssite/en/pages/portfolio/3
</code>```

Aside: Neither of these would have worked anyway. End flags like [END,R=301] are a mod_rewrite syntax, and do not relate to mod_alias (Redirect). And the URL-path matched by the Redirect directive should be a root-relative path beginning with a slash, not an absolute URL. See the Apache docs... https://httpd.apache.org/docs/current/mod/mod_alias.html#redirect

Title: htaccess 301 redirect not redirecting

Body:
tried several ways to make redirect, but not successfull

Redirect 301 /ru/pages/portfolio/ /ru/pages/portfolio/3/ [END,R=301]

or

Redirect 301 http://myssite/en/pages/portfolio http://myssite/en/pages/portfolio/3

and many others from internet, but all of them not working.
Need to redirect pages/portfolio to pages/portfolio/3 (for all languages - en, ru)

This is content of file

<IfModule mod_rewrite.c>

  # Turn Off mod_dir Redirect For Existing Directories
  DirectorySlash Off
  # Rewrite For Public Folder
  RewriteEngine on

 Redirect 301 /ru/pages/portfolio/ /ru/pages/portfolio/3/ [END,R=301]

  RewriteCond $1 !^(pma)
  RewriteRule ^(.*)$ public/$1 [L]
</IfModule>

Body:
Since you are already using mod_rewrite (for an internal rewrite) you should also use mod_rewrite for this redirect, rather than using a mod_alias Redirect. Different modules execute at different times during the request, despite the apparent order of the directives in the config file.

However, your example is unclear. The first example includes a trailing slash; the second does not? Is there a trailing slash or not?

Try something like the following instead after the RewriteEngine directive:

RewriteRule ^(en|ru)/pages/portfolio$ /$1/pages/portfolio/3 [R,L]

This excludes the trailing slash. And assumes "all languages" are just en and ru. This is also a temporary (302) redirect. Change to a permanent (301) redirect (if that is the intention) only when you are sure it's working OK, since 301s are cached by the browser. You will need to clear your browser cache before testing.

Redirect 301 /ru/pages/portfolio/ /ru/pages/portfolio/3/ [END,R=301]
:
Redirect 301 http://myssite/en/pages/portfolio http://myssite/en/pages/portfolio/3

Aside: Neither of these would have worked anyway. End flags like [END,R=301] are a mod_rewrite syntax, and do not relate to mod_alias (Redirect). And the URL-path matched by the Redirect directive should be a root-relative path beginning with a slash, not an absolute URL. See the Apache docs... https://httpd.apache.org/docs/current/mod/mod_alias.html#redirect


问:
Bitmap to Mat? android opencv
Hi i have my Bitmap object that i need to convert in Mat object .I saw that somebody used the bitmaptoMat function,but in my Utils package i have a lot of function with points list input to get Mat output but i have my Bitmap file.I tried another solution: Imgcodecs.imread that need string input,and i guess it needs the images path but i tried giving uri.toString() but it doesnt work.What can i do?
This is my Bitmap:</p>

```<code> Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
</code>```

答:
Import

```<code>import org.opencv.android.Utils;
</code>```

And then use the function:

```<code>Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
Mat imgMAT = new Mat (bitmap.getHeight(), bitmap.getWidth(), CvType.CV_8UC1);
Utils.bitmapToMat(bitmap, imgMAT);
</code>```

Title: Bitmap to Mat? android opencv

Body:
Hi i have my Bitmap object that i need to convert in Mat object .I saw that somebody used the bitmaptoMat function,but in my Utils package i have a lot of function with points list input to get Mat output but i have my Bitmap file.I tried another solution: Imgcodecs.imread that need string input,and i guess it needs the images path but i tried giving uri.toString() but it doesnt work.What can i do?
This is my Bitmap:

 Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);

Body:
Import

import org.opencv.android.Utils;

And then use the function:

Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
Mat imgMAT = new Mat (bitmap.getHeight(), bitmap.getWidth(), CvType.CV_8UC1);
Utils.bitmapToMat(bitmap, imgMAT);


问:
firefox: 'NoneType' object has no attribute 'quit'
After upgrading firefox and selenium I experience some issues with some code

I'm not very experienced with python

code

```<code>import sys
import time
import getopt
import urllib
import selenium
from pyvirtualdisplay import Display
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait

class Scrape:
    display = None
    driver = None

    def __init__(self):
        #   Start display
        self.display = Display(visible=0, size=(800, 600))
        self.display.start()

        #   Init args
        query = ''
        try:
            opts, args = getopt.getopt(sys.argv[1:], '', ['query=','proxy='])
            for opt, arg in opts:
                if opt == '--query':
                    query = arg
        except getopt.GetoptError as err:
            self.error(str(err))

        #   Init driver
        try:
            self.driver = webdriver.Firefox()
            self.driver.wait = WebDriverWait(self.driver, 5)
        except selenium.common.exceptions.WebDriverException as err:
            self.error(str(err))
        print('teeeesting...!')

    def error(self, str):
        self.close()

        print>>sys.stderr, str
        sys.exit(1)

    def close(self):
        self.driver.quit()
        self.display.stop()

if __name__ == '__main__':
    Scrape()
</code>```

error

```<code># python selenium_scrape.py --query "test"
Traceback (most recent call last):
  File "selenium_scrape.py", line 48, in <module>
    Scrape()
  File "selenium_scrape.py", line 34, in __init__
    self.error(str(err))
  File "selenium_scrape.py", line 38, in error
    self.close()
  File "selenium_scrape.py", line 44, in close
    self.driver.quit()
AttributeError: 'NoneType' object has no attribute 'quit'
</code>```

答:
The sequence of events seems to be:

You ran into an exception while scraping; your driver was not properly initialized.

The exception handler called error.

error called close.

close tried to call quit, but self (your driver) has a value of None ... which has no method named quit.

Hence the final error trace-back.  Insert a couple of strategic print commands to trace whether your driver ever got initialized (I expect not).  A likely spot would be in the exception handler under Init driver: print the exception you raised, and perhaps one or two useful values surrounding the problem.

Body:
After upgrading firefox and selenium I experience some issues with some code

I'm not very experienced with python

code

import sys
import time
import getopt
import urllib
import selenium
from pyvirtualdisplay import Display
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait

class Scrape:
    display = None
    driver = None

    def __init__(self):
        #   Start display
        self.display = Display(visible=0, size=(800, 600))
        self.display.start()

        #   Init args
        query = ''
        try:
            opts, args = getopt.getopt(sys.argv[1:], '', ['query=','proxy='])
            for opt, arg in opts:
                if opt == '--query':
                    query = arg
        except getopt.GetoptError as err:
            self.error(str(err))

        #   Init driver
        try:
            self.driver = webdriver.Firefox()
            self.driver.wait = WebDriverWait(self.driver, 5)
        except selenium.common.exceptions.WebDriverException as err:
            self.error(str(err))
        print('teeeesting...!')

    def error(self, str):
        self.close()

        print>>sys.stderr, str
        sys.exit(1)

    def close(self):
        self.driver.quit()
        self.display.stop()

if __name__ == '__main__':
    Scrape()

error

# python selenium_scrape.py --query "test"
Traceback (most recent call last):
  File "selenium_scrape.py", line 48, in <module>
    Scrape()
  File "selenium_scrape.py", line 34, in __init__
    self.error(str(err))
  File "selenium_scrape.py", line 38, in error
    self.close()
  File "selenium_scrape.py", line 44, in close
    self.driver.quit()
AttributeError: 'NoneType' object has no attribute 'quit'


问:
Trying to convert inconsistently formatted price strings to cents
I'm migrating data over from one database to another, and am writing the appropriate scripts. I want to start on a clean slate and fix a lot of the inconsistent formatting allowed by the previous app, specifically with prices, the following all being examples of prices currently stored in the previous database:

```<code>-100.00
700.00
0.01
3,200.00
3200
1,750.5
0
500/hour
</code>```

I would like to convert everything into cents, so the above would be:

```<code>-10000
70000
1
320000
320000
175050
0
50000
</code>```

I was hopeful when FORMAT(price, 2) * 100 seemed to work on a lot of them, including (!) 500/hour:

```<code>select format('500/hour', 2) * 100;
-> 50000
</code>```

But for some reason, I'm getting weird results for 3200.00:

```<code>select format('3200.00', 2) * 100;
-> 300
</code>```

While writing this, It appears that it doesn't work for any numeric strings above 1,000, and I'm guessing it has something to do with the presence/lack of a comma. Is there any intelligent way to parse the above examples into cents? If it is simple enough, I'd love to just incorporate it into the select query, but a user defined function is also fine.

答:
You could first remove the comma with this sentence:

```<code>replace(data,',','')
</code>```

This could be because you have a varchar type instead of an int type. If you do

```<code>select cast(replace('3,200.00',',','') as signed) * 100
</code>```

It should work

Body:
I'm migrating data over from one database to another, and am writing the appropriate scripts. I want to start on a clean slate and fix a lot of the inconsistent formatting allowed by the previous app, specifically with prices, the following all being examples of prices currently stored in the previous database:

-100.00
700.00
0.01
3,200.00
3200
1,750.5
0
500/hour

I would like to convert everything into cents, so the above would be:

-10000
70000
1
320000
320000
175050
0
50000

I was hopeful when FORMAT(price, 2) * 100 seemed to work on a lot of them, including (!) 500/hour:

select format('500/hour', 2) * 100;
-> 50000

But for some reason, I'm getting weird results for 3200.00:

select format('3200.00', 2) * 100;
-> 300

While writing this, It appears that it doesn't work for any numeric strings above 1,000, and I'm guessing it has something to do with the presence/lack of a comma. Is there any intelligent way to parse the above examples into cents? If it is simple enough, I'd love to just incorporate it into the select query, but a user defined function is also fine.

Body:
You could first remove the comma with this sentence:

replace(data,',','')

This could be because you have a varchar type instead of an int type. If you do

select cast(replace('3,200.00',',','') as signed) * 100

It should work


问:
ggplot strange ordering of stacked bar
I am attempting to create a diverging stacked bar like here, and am experiencing a similar issue to this SO question. My approach is slightly different though as I am managing it all via a single dataset, rather than two and my colours are independent of my data.

Reprex as follows:

```<code>library(tidyverse)
library(RColorBrewer)
x <- tribble(
  ~response, ~count,
  0,         -27,
  1,          -9,
  2,         -41,
  3,         -43,
  4,         -58,
  5,        -120,
  5,         120,
  6,         233,
  7,         379,
  8,         388,
  9,         145,
  10,         61
) %>%
  mutate(response = factor(response))

ggplot(x, aes(x = 1, y = count, fill = response)) +
  geom_col() +
  scale_fill_brewer(palette = "RdBu") +
  coord_flip()
</code>```

This gives me an image like this:

The issue is to do with the ordering of the stacked data on the right hand side of the zero where they stacking appears to be in descending order. Any thoughts on how to fix this would be greatly appreciated (expected ordering would be 0-10, not 0-5,10-5)

答:
You can use position_stack(reverse=TRUE):

```<code>ggplot(x, aes(x = 1, y = count, fill = response)) +
  geom_col(position = position_stack(reverse=TRUE)) +
  scale_fill_brewer(palette = "RdBu") +
  coord_flip()
</code>```

Title: ggplot strange ordering of stacked bar

Body:
I am attempting to create a diverging stacked bar like here, and am experiencing a similar issue to this SO question. My approach is slightly different though as I am managing it all via a single dataset, rather than two and my colours are independent of my data.

Reprex as follows:

library(tidyverse)
library(RColorBrewer)
x <- tribble(
  ~response, ~count,
  0,         -27,
  1,          -9,
  2,         -41,
  3,         -43,
  4,         -58,
  5,        -120,
  5,         120,
  6,         233,
  7,         379,
  8,         388,
  9,         145,
  10,         61
) %>%
  mutate(response = factor(response))

ggplot(x, aes(x = 1, y = count, fill = response)) +
  geom_col() +
  scale_fill_brewer(palette = "RdBu") +
  coord_flip()

This gives me an image like this:

The issue is to do with the ordering of the stacked data on the right hand side of the zero where they stacking appears to be in descending order. Any thoughts on how to fix this would be greatly appreciated (expected ordering would be 0-10, not 0-5,10-5)

Body:
You can use position_stack(reverse=TRUE):

ggplot(x, aes(x = 1, y = count, fill = response)) +
  geom_col(position = position_stack(reverse=TRUE)) +
  scale_fill_brewer(palette = "RdBu") +
  coord_flip()


问:
How to check whether string a is a substring of but not equal to string b?
I know that if we would like to know whether string a is contained in b we can use:

```<code>a in b
</code>```

When a equals to b, the above express still returns True. I would like an expression that would return False when a == b and return True when a is a substring of b. So I used the following expression:

```<code>a in b and a != b
</code>```

I just wonder is there a simpler expression in Python that works in the same way?

答:
Not sure how efficient direct string comparisons are in Python, but assuming they are O(n) this should be reasonably efficient and still readable :

```<code>len(a) < len(b) and a in b
</code>```

Likes the other answers it's also O(n), but the length operation should be O(1). It should also be better suited for edge cases (e.g. a being bigger than b)

Body:
I know that if we would like to know whether string a is contained in b we can use:

a in b

When a equals to b, the above express still returns True. I would like an expression that would return False when a == b and return True when a is a substring of b. So I used the following expression:

a in b and a != b

I just wonder is there a simpler expression in Python that works in the same way?

Body:
Not sure how efficient direct string comparisons are in Python, but assuming they are O(n) this should be reasonably efficient and still readable :

len(a) < len(b) and a in b

Likes the other answers it's also O(n), but the length operation should be O(1). It should also be better suited for edge cases (e.g. a being bigger than b)


问:
"open/close" SqlConnection or keep open?
I have my business-logic implemented in simple static classes with static methods. Each of these methods opens/closes SQL connection when called:

```<code>public static void DoSomething()
{
    using (SqlConnection connection = new SqlConnection("..."))
    {
        connection.Open();

        // ...

        connection.Close();
    }
}
</code>```

But I think passing the connection object around and avoiding opening and closing a connection saves performance. I made some tests long time ago with OleDbConnection class (not sure about SqlConnection), and it definitely helped to work like this (as far as I remember):

```<code>//pass around the connection object into the method
public static void DoSomething(SqlConnection connection)
{
    bool openConn = (connection.State == ConnectionState.Open);
    if (!openConn)
    {
        connection.Open();
    }

    // ....

    if (openConn)
    {
        connection.Close();
    }
}
</code>```

So the question is - should I choose the method (a) or method (b) ? I read in another stackoverflow question that connection pooling saved performance for me, I don't have to bother at all...

PS. It's an ASP.NET app - connections exist only during a web-request. Not a win-app or service.

答:
Always close connections as soon as you are done with them, so they underlying database connection can go back into the pool and be available for other callers.  Connection pooling is pretty well optimised, so there's no noticeable penalty for doing so.  The advice is basically the same as for transactions - keep them short and close when you're done.

It gets more complicated if you're running into MSDTC issues by using a single transaction around code that uses multiple connections, in which case you actually do have to share the connection object and only close it once the transaction is done with.

However you're doing things by hand here, so you might want to investigate tools that manage connections for you, like DataSets, Linq to SQL, Entity Framework or NHibernate.

Body:
I have my business-logic implemented in simple static classes with static methods. Each of these methods opens/closes SQL connection when called:

public static void DoSomething()
{
    using (SqlConnection connection = new SqlConnection("..."))
    {
        connection.Open();

        // ...

        connection.Close();
    }
}

But I think passing the connection object around and avoiding opening and closing a connection saves performance. I made some tests long time ago with OleDbConnection class (not sure about SqlConnection), and it definitely helped to work like this (as far as I remember):

//pass around the connection object into the method
public static void DoSomething(SqlConnection connection)
{
    bool openConn = (connection.State == ConnectionState.Open);
    if (!openConn)
    {
        connection.Open();
    }

    // ....

    if (openConn)
    {
        connection.Close();
    }
}

So the question is - should I choose the method (a) or method (b) ? I read in another stackoverflow question that connection pooling saved performance for me, I don't have to bother at all...

PS. It's an ASP.NET app - connections exist only during a web-request. Not a win-app or service.


问:
Windows equivalent of the 'tail' command
Is there a way to simulate the *nix tail command on the Windows command line? I have a file and I want a way to snip off the first n lines of text. For example:

```<code>D:\>type file.txt
line one
line two
line three
D:\>*[call to tail]* > result.txt

D:\>type result.txt
line two
line three
</code>```

答:
Powershell:</p>

```<code>Get-Content C:\logs\result.txt -Tail 10

Get-Content C:\logs\result.txt -wait (monitor the tail)
</code>```

Body:
Is there a way to simulate the *nix tail command on the Windows command line? I have a file and I want a way to snip off the first n lines of text. For example:

D:\>type file.txt
line one
line two
line three
D:\>*[call to tail]* > result.txt

D:\>type result.txt
line two
line three

Body:
Powershell:

Get-Content C:\logs\result.txt -Tail 10

Get-Content C:\logs\result.txt -wait (monitor the tail)


问:
The file which is inside package, not opening from java application
Dear experts this question is associated with

File is not opening in java which is inside jar file

Updated Question

And I used two codes from:

open a pdf file located inside a jar file

Following code works fine if I run application from workspace.

```<code>URL resource = Thread.currentThread().getContextClassLoader().getResource("resources/User_Guide.pdf");
            File userGuideFile = null;
            try {
                userGuideFile = new File(resource.getPath());
                if (Desktop.isDesktopSupported())
                {
                    Desktop desktop = Desktop.getDesktop();
                    desktop.open(userGuideFile);
                }
            } catch (Exception e1) {
                e1.printStackTrace();
            }
</code>```

But If I copy my project.jar to another location it will not opens file and shows in my log as file is not found "c:\workspace\project...pdf". And I used following code from same page , My pdfReader adobe reader shows exception  file is either not supproted or damaged :

Code:

```<code>if (Desktop.isDesktopSupported())
{
    Desktop desktop = Desktop.getDesktop();
    InputStream resource = Thread.currentThread().getContextClassLoader().getResource("resources/User_Guide.pdf");
try
{
    File file = File.createTempFile("User_Guide", ".pdf");
    file.deleteOnExit();
    OutputStream out = new FileOutputStream(file);
    try
    {
        // copy contents from resource to out
    }
    finally
    {
        out.close();
    }
    desktop.open(file);
}
finally
{
    resource.close();
}
}
</code>```

Please give me some idea. Your help will be appreciated. Thank You

Note: I tried to open *.txt file and it is working fine. But not working in PDF and DOC. The main problem is when I run application changing the project work-space directory. Actually I want to make like:  Ntebeans keyboard-short-code documents which is under Help menu

答:
I don't have enough reputation to comment on Joop Eggen's accepted answer, but the line

```<code>InputStream in = getClass().getResource("/resources/User_Guide.pdf");
</code>```

throws the error "Incompatible types: URL cannot be converted to InputStream". Instead use the method getResourceAsStream():

```<code>InputStream in = getClass().getResourceAsStream("/resources/User_Guide.pdf");
</code>```

Body:
Dear experts this question is associated with

File is not opening in java which is inside jar file

Updated Question

And I used two codes from:

open a pdf file located inside a jar file

Following code works fine if I run application from workspace.

URL resource = Thread.currentThread().getContextClassLoader().getResource("resources/User_Guide.pdf");
            File userGuideFile = null;
            try {
                userGuideFile = new File(resource.getPath());
                if (Desktop.isDesktopSupported())
                {
                    Desktop desktop = Desktop.getDesktop();
                    desktop.open(userGuideFile);
                }
            } catch (Exception e1) {
                e1.printStackTrace();
            }

But If I copy my project.jar to another location it will not opens file and shows in my log as file is not found "c:\workspace\project...pdf". And I used following code from same page , My pdfReader adobe reader shows exception  file is either not supproted or damaged :

Code:

if (Desktop.isDesktopSupported())
{
    Desktop desktop = Desktop.getDesktop();
    InputStream resource = Thread.currentThread().getContextClassLoader().getResource("resources/User_Guide.pdf");
try
{
    File file = File.createTempFile("User_Guide", ".pdf");
    file.deleteOnExit();
    OutputStream out = new FileOutputStream(file);
    try
    {
        // copy contents from resource to out
    }
    finally
    {
        out.close();
    }
    desktop.open(file);
}
finally
{
    resource.close();
}
}

Please give me some idea. Your help will be appreciated. Thank You

Note: I tried to open *.txt file and it is working fine. But not working in PDF and DOC. The main problem is when I run application changing the project work-space directory. Actually I want to make like:  Ntebeans keyboard-short-code documents which is under Help menu

Body:
I don't have enough reputation to comment on Joop Eggen's accepted answer, but the line

InputStream in = getClass().getResource("/resources/User_Guide.pdf");

throws the error "Incompatible types: URL cannot be converted to InputStream". Instead use the method getResourceAsStream():

InputStream in = getClass().getResourceAsStream("/resources/User_Guide.pdf");


问:
Concat multiple C++ strings at once?
I'm new to C++ strings. Is there a way to concatenate more than two strings at once? Or I have to concat two strings at the time? My concern is that it probably needs to allocate memory on each operation, instead of only once for the final result.

Remember something like that in java, wonder if there is a method for that somewhere in std. Actually, std::stringstream might be it, but I don't know how exactly it works.

答:
You can reserve the required space beforehand, avoiding reallocations.

```<code>std::string s0{/*...*/}, s1{/*...*/}, s2{/*...*/};
std::string sink;

sink.reserve(s0.size() + s1.size() + s2.size() + 1);
sink += s0;
sink += s1;
sink += s2;
</code>```

You can make this nicer with a variadic string_cat function. Here's a C++17 implementation:

```<code>template <typename... Strings>
std::string string_cat(Strings&&... strings)
{
    std::string result;
    result.reserve((strings.size() + ...) + 1);
    ((result += std::forward<Strings>(strings)), ...);
    return result;
}
</code>```

Usage:

```<code>using namespace std::literals;
auto res = string_cat("a"s, "b"s, "c"s);
</code>```

live example on wandbox

Title: Concat multiple C++ strings at once?

Body:
You can reserve the required space beforehand, avoiding reallocations.

std::string s0{/*...*/}, s1{/*...*/}, s2{/*...*/};
std::string sink;

sink.reserve(s0.size() + s1.size() + s2.size() + 1);
sink += s0;
sink += s1;
sink += s2;

You can make this nicer with a variadic string_cat function. Here's a C++17 implementation:

template <typename... Strings>
std::string string_cat(Strings&&... strings)
{
    std::string result;
    result.reserve((strings.size() + ...) + 1);
    ((result += std::forward<Strings>(strings)), ...);
    return result;
}

Usage:

using namespace std::literals;
auto res = string_cat("a"s, "b"s, "c"s);

live example on wandbox


问:
Angular controller has a unexpected token
So I have a angular controller file where I keep all my controllers.

If I have this code at the bottom of a controller to only print out a part of my object array. Works fine until I put a new controller after the current one, then non of my views are rendered and I get the following error.

Uncaught SyntaxError: Unexpected token >

This is the section of code I have that the error if referring to.

```<code> $scope.formats = [];

    $scope.productTypeChange = function () {
        $scope.formats = $scope.productsandformats.find(ps = > ps.name == $scope.formData.Product.name
    )
    }
</code>```

Is there a easy way to fix this, when ive looked at stck and google but can seem to find answer.
thanks

答:
The error itself tells Uncaught SyntaxError: Unexpected token >. You have space between the arrow operator

```<code>$scope.formats = [];

$scope.productTypeChange = function () {
    $scope.formats = $scope.productsandformats.find(ps => ps.name == $scope.formData.Product.name
)
</code>```

Check Arrow functions for more details.

Body:
So I have a angular controller file where I keep all my controllers.

If I have this code at the bottom of a controller to only print out a part of my object array. Works fine until I put a new controller after the current one, then non of my views are rendered and I get the following error.

Uncaught SyntaxError: Unexpected token >

This is the section of code I have that the error if referring to.

 $scope.formats = [];

    $scope.productTypeChange = function () {
        $scope.formats = $scope.productsandformats.find(ps = > ps.name == $scope.formData.Product.name
    )
    }

Is there a easy way to fix this, when ive looked at stck and google but can seem to find answer.
thanks

Body:
The error itself tells Uncaught SyntaxError: Unexpected token >. You have space between the arrow operator

$scope.formats = [];

$scope.productTypeChange = function () {
    $scope.formats = $scope.productsandformats.find(ps => ps.name == $scope.formData.Product.name
)

Check Arrow functions for more details.


问:
Extension Methods not Recognized
What is necessary to have an extension method honored when it exists in an imported assembly?  I built one in a class library project but it is not recognized in my web project which references the library.  All the other classes and methods in the library are honored and visible but this extension method is not. The extension method is visible when used within the library.</p>

答:
Make sure if using templates, your template declaration matches what is declared in the method signature with, "this"..

So,

```<code>SomeClass<string, string> test = new SomeClass<string, string>();

extensionMethod<key, val>(this SomeClass<key, Lazy<val>>, string val)
{
}
</code>```

the extension method will not show up because of the lazy wrapper.

Title: Extension Methods not Recognized

Body:
Make sure if using templates, your template declaration matches what is declared in the method signature with, "this"..

So,

SomeClass<string, string> test = new SomeClass<string, string>();

extensionMethod<key, val>(this SomeClass<key, Lazy<val>>, string val)
{
}

the extension method will not show up because of the lazy wrapper.


问:
Optimize output when using counter?
I'm trying to optimize my output after I counted all the signs in a file. For example I want to print only signs which appear more often than once.

```<code>from codecs import open as co
from collections import Counter

with co('test.txt', 'r', 'utf-8', 'strict') as fp:
  text = fp.read()

for char, count in Counter(text).most_common():
  if not char.isspace():

    print(char, count)
</code>```

My Output so far:

c 102
a 1
b 1
```

I'm happy for any tips or solution, especially if it is easy to folow.

答:
```<code>output = filter(lambda a: a[1] > 1, Counter(text).most_common())
# output = [('c', 102)]
for char, count in output:
    if not char.isspace():
        print(char, count)
</code>```

Title: Optimize output when using counter?

Body:
I'm trying to optimize my output after I counted all the signs in a file. For example I want to print only signs which appear more often than once.

from codecs import open as co
from collections import Counter

with co('test.txt', 'r', 'utf-8', 'strict') as fp:
  text = fp.read()

for char, count in Counter(text).most_common():
  if not char.isspace():

    print(char, count)

My Output so far:

c 102
a 1
b 1

I'm happy for any tips or solution, especially if it is easy to folow.