问:
Is it okay to treat the prevState argument of setState's function as mutable?
I know this.state is not supposed to be modified directly, instead setState should be used.

From this I inferred that prevState should be also treated as immutable and instead setState should always look something like this:

```<code>this.setState((prevState) => {
  // Create a new object instance to return
  const state = { ...prevState };
  state.counter = state.counter + 1;
  return state;
});
</code>```

Or with deeper nesting:

```<code>this.setState((prevState) => {
  // Create a new object instance to return
  const state = { ...prevState, counter: { ...prevState.counter } };
  state.counter.value = state.counter.value + 1;
  return state;
});
</code>```

Or just a partial update like would be with setState({}) where easier and nicer to use:

```<code>this.setState((prevState) => ({ counter: prevState.counter + 1 }));
</code>```

All of the above are obviously correct because they return a new instance, but then I came across this question where the accepted answer encourages mutating prevState without returning a new object instance (notice the code block in the question).

Something like this:

```<code>this.setState((prevState) => {
  prevState.flag = !prevState.flag;
  return prevState;
});
</code>```

I found this to be a sketchy suggestion so I decided to test if the object instance references of prevState and this.state are the same:

(The JSFiddle)

```<code>class Test extends React.Component {
  state = { counter: 0 };

  onDemonstrateButtonClick = (event) => {
    this.setState((prevState) => {
      if (prevState === this.state) alert(`uh, yep`);
      prevState.counter++;
      return prevState;
    });
  };

  render() {
    return (
      <div>
        <button onClick={this.onDemonstrateButtonClick}>Demonstrate</button>
        {this.state.counter}
      </div>
    );
  }
}
</code>```

Whadayaknow, they are! So which is it? Is the answer wrong and should I return a new object instance or return partial update as a new object or can I go wild and mutate the prevState argument directly? And if yes, how is this any different from mutating this.state directly?

Side note: TypeScript React typings do not mark the argument as ReadOnly which only adds to my confusion.

答:
First Point

Is it okay to treat the prevState argument of setState's function as
  mutable?

The answer is NO you should never mutate prevState, this is also clearly mentioned in react documentation in setState section

prevState is a reference to the previous state. It should not be
  directly mutated. Instead, changes should be represented by building a
  new object based on the input from prevState and props.

Second Point:

You tested prevState and this.state and they are the same, well actually they are not.

To figure out why they are actually different we need to know why prevState actually exist, and the answer is that setState function is asynchronous, thats why react js is giving us access to prevState lets check the example below where prevState != this.state

In the example below we will increment counter twice per click, but we will use 2 setState operations each one of them will increment the counter by 1.

Because setState is async you will notice that the second setState operation started before the first setState is finished this is where prevState is useful and here prevState and this.state are not equal.

I commented each line with a number denoting when this line is executed, this should explain why we need prevState and why it is different from this.state.

```<code>class App extends React.Component{
  constructor(props)
  {
    super(props);
    this.state = {
      counter : 1
    };
  }

  increment = () =>{
    this.setState((prevState , props) => {
      console.log("in first"); //3
      console.log(prevState);  //3
      console.log(this.state); //3
      if(prevState == this.state)
      {
         console.log("in first prevState == this.state");
      }
      return {
        counter : prevState.counter+1
      }
    } , ()=>{
      console.log("done updating first"); //5
    });

    console.log("after first"); //1

    this.setState((prevState, props) => {
      console.log("in second"); //4
      console.log(this.state);  //4
      console.log(prevState);   //4
      if (prevState == this.state) {
        console.log("in second prevState == this.state");
      }
      return {
        counter: prevState.counter + 1
      }
    } , () =>{
      console.log("done updating second"); //6
    });

    console.log("after second"); //2

  }

  render(){
    return (
      <div>
        <span>{this.state.counter}</span>
        <br/>
        <button onClick={this.increment} >increment</button>
      </div>
    )
  }
}
</code>```

The Result from the above code is

```<code>"after first"
"after second"
"in first"
▶Object {counter: 1}
▶Object {counter: 1}
"in first prevState == this.state"
"in second"
▶Object {counter: 1}
▶Object {counter: 2}
"done updating first"
"done updating second"
</code>```

The above code is fully working in this link, you can check the console.log result
https://codesandbox.io/s/k325l485mr

The above example will correctly increment counter twice per click, if you want to break it change return statement in second setState

from

```<code>return {
    counter: prevState.counter + 1
}
</code>```

to

```<code>return {
    counter: this.state.counter + 1
}
</code>```

and you will find that the result is not correct each click will result in 1 increment which is not correct because we have 2 setState , this is because we didn't use prevState and we used an incorrect this.state

Finally

I believe that the correct way to update the counter is

this.setState((prevState) => ({ counter: prevState.counter + 1 }));

Body:
I know this.state is not supposed to be modified directly, instead setState should be used.

From this I inferred that prevState should be also treated as immutable and instead setState should always look something like this:

this.setState((prevState) => {
  // Create a new object instance to return
  const state = { ...prevState };
  state.counter = state.counter + 1;
  return state;
});

Or with deeper nesting:

this.setState((prevState) => {
  // Create a new object instance to return
  const state = { ...prevState, counter: { ...prevState.counter } };
  state.counter.value = state.counter.value + 1;
  return state;
});

Or just a partial update like would be with setState({}) where easier and nicer to use:

this.setState((prevState) => ({ counter: prevState.counter + 1 }));

All of the above are obviously correct because they return a new instance, but then I came across this question where the accepted answer encourages mutating prevState without returning a new object instance (notice the code block in the question).

Something like this:

this.setState((prevState) => {
  prevState.flag = !prevState.flag;
  return prevState;
});

I found this to be a sketchy suggestion so I decided to test if the object instance references of prevState and this.state are the same:

(The JSFiddle)

class Test extends React.Component {
  state = { counter: 0 };

  onDemonstrateButtonClick = (event) => {
    this.setState((prevState) => {
      if (prevState === this.state) alert(`uh, yep`);
      prevState.counter++;
      return prevState;
    });
  };

  render() {
    return (

        <button onClick={this.onDemonstrateButtonClick}>Demonstrate</button>
        {this.state.counter}

    );
  }
}

Whadayaknow, they are! So which is it? Is the answer wrong and should I return a new object instance or return partial update as a new object or can I go wild and mutate the prevState argument directly? And if yes, how is this any different from mutating this.state directly?

Side note: TypeScript React typings do not mark the argument as ReadOnly which only adds to my confusion.

Body:
First Point

Is it okay to treat the prevState argument of setState's function as
  mutable?

The answer is NO you should never mutate prevState, this is also clearly mentioned in react documentation in setState section

prevState is a reference to the previous state. It should not be
  directly mutated. Instead, changes should be represented by building a
  new object based on the input from prevState and props.

Second Point:

You tested prevState and this.state and they are the same, well actually they are not.

To figure out why they are actually different we need to know why prevState actually exist, and the answer is that setState function is asynchronous, thats why react js is giving us access to prevState lets check the example below where prevState != this.state

In the example below we will increment counter twice per click, but we will use 2 setState operations each one of them will increment the counter by 1.

Because setState is async you will notice that the second setState operation started before the first setState is finished this is where prevState is useful and here prevState and this.state are not equal.

I commented each line with a number denoting when this line is executed, this should explain why we need prevState and why it is different from this.state.

class App extends React.Component{
  constructor(props)
  {
    super(props);
    this.state = {
      counter : 1
    };
  }

  increment = () =>{
    this.setState((prevState , props) => {
      console.log("in first"); //3
      console.log(prevState);  //3
      console.log(this.state); //3
      if(prevState == this.state)
      {
         console.log("in first prevState == this.state");
      }
      return {
        counter : prevState.counter+1
      }
    } , ()=>{
      console.log("done updating first"); //5
    });

    console.log("after first"); //1

    this.setState((prevState, props) => {
      console.log("in second"); //4
      console.log(this.state);  //4
      console.log(prevState);   //4
      if (prevState == this.state) {
        console.log("in second prevState == this.state");
      }
      return {
        counter: prevState.counter + 1
      }
    } , () =>{
      console.log("done updating second"); //6
    });

    console.log("after second"); //2

  }

  render(){
    return (
      <div>
        <span>{this.state.counter}</span>
        <br/>
        <button onClick={this.increment} >increment</button>
      </div>
    )
  }
}

The Result from the above code is

"after first"
"after second"
"in first"
▶Object {counter: 1}
▶Object {counter: 1}
"in first prevState == this.state"
"in second"
▶Object {counter: 1}
▶Object {counter: 2}
"done updating first"
"done updating second"

The above code is fully working in this link, you can check the console.log result
https://codesandbox.io/s/k325l485mr

The above example will correctly increment counter twice per click, if you want to break it change return statement in second setState

from

return {
    counter: prevState.counter + 1
}

to

return {
    counter: this.state.counter + 1
}

and you will find that the result is not correct each click will result in 1 increment which is not correct because we have 2 setState , this is because we didn't use prevState and we used an incorrect this.state

Finally

I believe that the correct way to update the counter is

this.setState((prevState) => ({ counter: prevState.counter + 1 }));


来源: stackexchange

问:
Execution skipping getline()
After ending first while with ctrl+d the program skips "cin >> contBuscado"
and goes to the for.
I dont know why this is happening, i've used .ignore and .clear but nothing happens.

```<code> #include <iostream>
 #include<vector>
 using namespace std;

struct Contacto{
string nombre;
int numero;
}contacto;

int main() {

vector<Contacto> listaContactos;

while(cout<<"Nombre:" && getline(cin,contacto.nombre)){
    cout<<"Telefono:";
    cin>>contacto.numero;
    cin.ignore();
    listaContactos.push_back(contacto);
}
cin.clear();

cout << "\nIntroduce el nombre del contacto a buscar: ";
string contBuscado="";
cin >> contBuscado;
cin.ignore();

for(Contacto const& con:listaContactos){
    if(con.nombre==contBuscado){
        cout<<"El telefono de "<<contBuscado<<" es "<<con.numero<<"\n";
        return 0;
    }
}
cout<<"\nEl contacto introducido no se encuentra en la lista\n";

return 0;
</code>```

}

答:
After ending input with CtrlD, you have ended standard input for your program. At this point you cannot supply any more input.

You will need to add a way for the user to exit the while loop, such as by entering a blank line.

Also, you will find it much easier to use std::getline() in all cases instead of cin >>. The use of cin >> is not recommended for interactive input, because its behaviour can be confusing.

ContentLicense: CC BY-SA 3.0

Title: Execution skipping getline()

Body:
After ending first while with ctrl+d the program skips "cin >> contBuscado"
and goes to the for.
I dont know why this is happening, i've used .ignore and .clear but nothing happens.

 #include <iostream>
 #include<vector>
 using namespace std;

struct Contacto{
string nombre;
int numero;
}contacto;

int main() {

vector<Contacto> listaContactos;

while(cout<<"Nombre:" && getline(cin,contacto.nombre)){
    cout<<"Telefono:";
    cin>>contacto.numero;
    cin.ignore();
    listaContactos.push_back(contacto);
}
cin.clear();

cout << "\nIntroduce el nombre del contacto a buscar: ";
string contBuscado="";
cin >> contBuscado;
cin.ignore();

for(Contacto const& con:listaContactos){
    if(con.nombre==contBuscado){
        cout<<"El telefono de "<<contBuscado<<" es "<<con.numero<<"\n";
        return 0;
    }
}
cout<<"\nEl contacto introducido no se encuentra en la lista\n";

return 0;

}


问:
Different threads don't work together while doing different tasks
I'm creating two different threads which will solve same problem with different ways and I will calculate their solving time. I've created a structure like that;

MainController.java

```<code>public static void main(String[] args) throws Exception {
        MainController mc= new MainController();
        mc.setProblem();
        Thread1 thread1 = new Thread1("thread1",problem,approach1);
        Thread2 thread2 = new Thread2("thread2",problem,approach2);
        thread1.start();
        thread2.start();
    }
</code>```

Thread1.java

```<code>class Thread1 implements Runnable{

       public void run() {
          System.out.println("Running " +  threadName );
          try {
             solve(approach);
          } catch (Exception e) {
             System.out.println("Thread " +  threadName + " interrupted.");
          }
          //showTable();
          System.out.println("Thread " +  threadName + " exiting.");
       }

       public void start () {
          System.out.println("Starting " +  threadName );
          if (t == null) {
             t = new Thread (this, threadName);
             t.start ();
          }
       }

       public void solve(approach) throws Exception {

            // Throw an exception to stop the process if the puzzle is solved
            if (didIsolve())  {//true if yes
                    System.out.println("----" + threadName +"----");
                    showResult();
                    System.out.println("--------------------------");
                    throw new Exception("ex");
            }
        }
    }
</code>```

Thread2.java is the same as above code block.

And output like

```<code>    Creating thread1
    Creating thread2
    Starting thread1
    Starting thread2
    Running thread2
    Running thread1
    Thread thread1 exiting.
    ----thread2----
   RESULT METHOD OUTPUT
    --------------------------
    Thread thread2 interrupted.
    Thread thread2 exiting.
</code>```

As you see above, thread1 did not solve problem, at least did not show result.

Also I've checked this topics so far

multiple threads performing different tasks

Java threads to do different tasks?

Edit:

Well, I think I found the problem. I changed MainController class;

```<code>public static void main(String[] args) throws Exception {
        MainController mc= new MainController();
        mc.setProblem();
        MainController mc2 = new MainContoller();
        mc1.setProblem();
        Thread1 thread1 = new Thread1("thread1",mc.problem,approach1);
        Thread2 thread2 = new Thread2("thread2",mc1.problem,approach2);
        thread1.start();
        thread2.start();
    }
</code>```

And it worked, but I don't know why. I will not accept my answer as correct answer for few days, may someone explain this situation?

答: If your goal is to measure the solving time of each approach, doing it in a multithreaded way is not going to give you consistent and reliable results. It would be better to run each approach in a serial fashion, and probably many times, to get an average completion time of each approach. Take care to avoid taxing the CPU with other processes during the test.</p>

Body:
I'm creating two different threads which will solve same problem with different ways and I will calculate their solving time. I've created a structure like that;

MainController.java

public static void main(String[] args) throws Exception {
        MainController mc= new MainController();
        mc.setProblem();
        Thread1 thread1 = new Thread1("thread1",problem,approach1);
        Thread2 thread2 = new Thread2("thread2",problem,approach2);
        thread1.start();
        thread2.start();
    }

Thread1.java

class Thread1 implements Runnable{

       public void run() {
          System.out.println("Running " +  threadName );
          try {
             solve(approach);
          } catch (Exception e) {
             System.out.println("Thread " +  threadName + " interrupted.");
          }
          //showTable();
          System.out.println("Thread " +  threadName + " exiting.");
       }

       public void start () {
          System.out.println("Starting " +  threadName );
          if (t == null) {
             t = new Thread (this, threadName);
             t.start ();
          }
       }

       public void solve(approach) throws Exception {

            // Throw an exception to stop the process if the puzzle is solved
            if (didIsolve())  {//true if yes
                    System.out.println("----" + threadName +"----");
                    showResult();
                    System.out.println("--------------------------");
                    throw new Exception("ex");
            }
        }
    }

Thread2.java is the same as above code block.

And output like

    Creating thread1
    Creating thread2
    Starting thread1
    Starting thread2
    Running thread2
    Running thread1
    Thread thread1 exiting.
    ----thread2----
   RESULT METHOD OUTPUT
    --------------------------
    Thread thread2 interrupted.
    Thread thread2 exiting.

As you see above, thread1 did not solve problem, at least did not show result.

Also I've checked this topics so far

multiple threads performing different tasks

Java threads to do different tasks?

Edit:

Well, I think I found the problem. I changed MainController class;

public static void main(String[] args) throws Exception {
        MainController mc= new MainController();
        mc.setProblem();
        MainController mc2 = new MainContoller();
        mc1.setProblem();
        Thread1 thread1 = new Thread1("thread1",mc.problem,approach1);
        Thread2 thread2 = new Thread2("thread2",mc1.problem,approach2);
        thread1.start();
        thread2.start();
    }

And it worked, but I don't know why. I will not accept my answer as correct answer for few days, may someone explain this situation?


问:
How to remove part of string using R regex with boundary
I have these 3 example strings:

```<code>x <- "AP-1(bZIP)/ThioMac-PU.1-ChIP-Seq(GSE21512)/Homer(0.989)More Information | Similar Motifs Found"
y <- "NeuroG2(bHLH)/Fibroblast-NeuroG2-ChIP-Seq(GSE75910)/Homer(0.828)More Information | Similar Motifs Found"
z <- "SPIB/MA0081.1/Jaspar(0.753)More Information | Similar Motifs Found"
</code>```

What I want to do is to remove strings that comes after first word of the last / delimiter resulting in:

```<code>AP-1(bZIP)/ThioMac-PU.1-ChIP-Seq(GSE21512)/Homer
NeuroG2(bHLH)/Fibroblast-NeuroG2-ChIP-Seq(GSE75910)/Homer
SPIB/MA0081.1/Jaspar
</code>```

I tried this but it doesn't give what I want:

```<code>> sub("\\(.*?\\)More Information | Similar Motifs Found","",x)
[1] "AP-1| Similar Motifs Found"
</code>```

What's the right way to do it?

答:
You can use a greedy pattern (.*/\\w+).* to match until the last /word, then extract the group with back reference:

```<code>v <- c("AP-1(bZIP)/ThioMac-PU.1-ChIP-Seq(GSE21512)/Homer(0.989)More Information | Similar Motifs Found", "NeuroG2(bHLH)/Fibroblast-NeuroG2-ChIP-Seq(GSE75910)/Homer(0.828)More Information | Similar Motifs Found", "SPIB/MA0081.1/Jaspar(0.753)More Information | Similar Motifs Found")

sub("(.*/\\w+).*", "\\1", v)
# [1] "AP-1(bZIP)/ThioMac-PU.1-ChIP-Seq(GSE21512)/Homer"          "NeuroG2(bHLH)/Fibroblast-NeuroG2-ChIP-Seq(GSE75910)/Homer"
# [3] "SPIB/MA0081.1/Jaspar"
</code>```

In (.*/\\w+).*, the first .* is greedy and will match as many as possible, the stop condition is / + a word(matched by \\w+); the second .* matches the remaining part of the string.

Body:
I have these 3 example strings:

x <- "AP-1(bZIP)/ThioMac-PU.1-ChIP-Seq(GSE21512)/Homer(0.989)More Information | Similar Motifs Found"
y <- "NeuroG2(bHLH)/Fibroblast-NeuroG2-ChIP-Seq(GSE75910)/Homer(0.828)More Information | Similar Motifs Found"
z <- "SPIB/MA0081.1/Jaspar(0.753)More Information | Similar Motifs Found"

What I want to do is to remove strings that comes after first word of the last / delimiter resulting in:

AP-1(bZIP)/ThioMac-PU.1-ChIP-Seq(GSE21512)/Homer
NeuroG2(bHLH)/Fibroblast-NeuroG2-ChIP-Seq(GSE75910)/Homer
SPIB/MA0081.1/Jaspar

I tried this but it doesn't give what I want:

> sub("\\(.*?\\)More Information | Similar Motifs Found","",x)
[1] "AP-1| Similar Motifs Found"

What's the right way to do it?

Body:
You can use a greedy pattern (.*/\\w+).* to match until the last /word, then extract the group with back reference:

v <- c("AP-1(bZIP)/ThioMac-PU.1-ChIP-Seq(GSE21512)/Homer(0.989)More Information | Similar Motifs Found", "NeuroG2(bHLH)/Fibroblast-NeuroG2-ChIP-Seq(GSE75910)/Homer(0.828)More Information | Similar Motifs Found", "SPIB/MA0081.1/Jaspar(0.753)More Information | Similar Motifs Found")

sub("(.*/\\w+).*", "\\1", v)
# [1] "AP-1(bZIP)/ThioMac-PU.1-ChIP-Seq(GSE21512)/Homer"          "NeuroG2(bHLH)/Fibroblast-NeuroG2-ChIP-Seq(GSE75910)/Homer"
# [3] "SPIB/MA0081.1/Jaspar"

In (.*/\\w+).*, the first .* is greedy and will match as many as possible, the stop condition is / + a word(matched by \\w+); the second .* matches the remaining part of the string.


问:
must capture output of a function that has no return statement
I'm using the NLTK package and it has a function that tells me whether a given sentence is positive, negative, or neutral:

```<code>from nltk.sentiment.util import demo_liu_hu_lexicon

demo_liu_hu_lexicon('Today is a an awesome, happy day')
>>> Positive
</code>```

Problem is, that function doesn't have a return statement - it just prints "Positive", "Negative", or "Neutral" to stdout. All it returns - implicitly - is a NoneType object. (Here's the function's source code.)

Is there any way I can capture this output (other than messing with the NLTK source code on my machine)?

答:
TL;DR

The demo_liu_hu_lexicon function is a demo function of how you could use the opinion_lexicon. It's used for testing and should not be used directly.

In Long

Let's look at the function and see how we can re-create a similar function https://github.com/nltk/nltk/blob/develop/nltk/sentiment/util.py#L616

```<code>def demo_liu_hu_lexicon(sentence, plot=False):
    """
    Basic example of sentiment classification using Liu and Hu opinion lexicon.
    This function simply counts the number of positive, negative and neutral words
    in the sentence and classifies it depending on which polarity is more represented.
    Words that do not appear in the lexicon are considered as neutral.
    :param sentence: a sentence whose polarity has to be classified.
    :param plot: if True, plot a visual representation of the sentence polarity.
    """
    from nltk.corpus import opinion_lexicon
    from nltk.tokenize import treebank

    tokenizer = treebank.TreebankWordTokenizer()
</code>```

Okay, that's a strange use for imports to exist inside the function but this is because it's a demo function use for simple testing or documentation.

Also, the usage of treebank.TreebankWordTokenizer() is rather odd, we can simply use the nltk.word_tokenize.

Let's move the imports out and rewrite the demo_liu_hu_lexicon as a simple_sentiment function.

```<code>from nltk.corpus import opinion_lexicon
from nltk import word_tokenize

def simple_sentiment(text):
    pass
</code>```

Next, we see

```<code>def demo_liu_hu_lexicon(sentence, plot=False):
    """
    Basic example of sentiment classification using Liu and Hu opinion lexicon.
    This function simply counts the number of positive, negative and neutral words
    in the sentence and classifies it depending on which polarity is more represented.
    Words that do not appear in the lexicon are considered as neutral.
    :param sentence: a sentence whose polarity has to be classified.
    :param plot: if True, plot a visual representation of the sentence polarity.
    """
    from nltk.corpus import opinion_lexicon
    from nltk.tokenize import treebank

    tokenizer = treebank.TreebankWordTokenizer()
    pos_words = 0
    neg_words = 0
    tokenized_sent = [word.lower() for word in tokenizer.tokenize(sentence)]

    x = list(range(len(tokenized_sent))) # x axis for the plot
    y = []
</code>```

The function

first tokenized and lower-cased the sentence

initialize the number of positive and negative words.

x and y is initialized for some plotting later, so let's ignore that.

If we go further down the function:

```<code>def demo_liu_hu_lexicon(sentence, plot=False):
    from nltk.corpus import opinion_lexicon
    from nltk.tokenize import treebank

    tokenizer = treebank.TreebankWordTokenizer()
    pos_words = 0
    neg_words = 0
    tokenized_sent = [word.lower() for word in tokenizer.tokenize(sentence)]

    x = list(range(len(tokenized_sent))) # x axis for the plot
    y = []

    for word in tokenized_sent:
        if word in opinion_lexicon.positive():
            pos_words += 1
            y.append(1) # positive
        elif word in opinion_lexicon.negative():
            neg_words += 1
            y.append(-1) # negative
        else:
            y.append(0) # neutral

    if pos_words > neg_words:
        print('Positive')
    elif pos_words < neg_words:
        print('Negative')
    elif pos_words == neg_words:
        print('Neutral')
</code>```

The loop simply go through each token and check wether the word is in the positive / negative lexicon.

At the end, it checks the no. of positive and negative words and return the tag.

Now lets see whether we can have a better simple_sentiment function, now that we know what demo_liu_hu_lexicon do.

Tokenization in step 1 can't be avoided, so we have:

```<code>from nltk.corpus import opinion_lexicon
from nltk.tokenize import treebank

def simple_sentiment(text):
    tokens = [word.lower() for word in word_tokenize(text)]
</code>```

There's an lazy way out to do step 2-5 is to just copy+paste and change the print() -> return

```<code>from nltk.corpus import opinion_lexicon
from nltk.tokenize import treebank

def simple_sentiment(text):
    tokens = [word.lower() for word in word_tokenize(text)]

    for word in tokenized_sent:
        if word in opinion_lexicon.positive():
            pos_words += 1
            y.append(1) # positive
        elif word in opinion_lexicon.negative():
            neg_words += 1
            y.append(-1) # negative
        else:
            y.append(0) # neutral

    if pos_words > neg_words:
        return 'Positive'
    elif pos_words < neg_words:
        return 'Negative'
    elif pos_words == neg_words:
        return 'Neutral'
</code>```

Now, you have a function that you can do whatever you please.

BTW, the demo is really odd..

When we see a positive word add 1 and when we see a negative we add -1.
And we say something is positive when pos_words > neg_words.

That means that the list of integers comparison follows some Pythonic sequence comparison that might have no linguistic or mathematical logic =(See What happens when we compare list of integers?)

Body:
I'm using the NLTK package and it has a function that tells me whether a given sentence is positive, negative, or neutral:

from nltk.sentiment.util import demo_liu_hu_lexicon

demo_liu_hu_lexicon('Today is a an awesome, happy day')
>>> Positive

Problem is, that function doesn't have a return statement - it just prints "Positive", "Negative", or "Neutral" to stdout. All it returns - implicitly - is a NoneType object. (Here's the function's source code.)

Is there any way I can capture this output (other than messing with the NLTK source code on my machine)?

Body:
TL;DR

The demo_liu_hu_lexicon function is a demo function of how you could use the opinion_lexicon. It's used for testing and should not be used directly.

In Long

Let's look at the function and see how we can re-create a similar function https://github.com/nltk/nltk/blob/develop/nltk/sentiment/util.py#L616

def demo_liu_hu_lexicon(sentence, plot=False):
    """
    Basic example of sentiment classification using Liu and Hu opinion lexicon.
    This function simply counts the number of positive, negative and neutral words
    in the sentence and classifies it depending on which polarity is more represented.
    Words that do not appear in the lexicon are considered as neutral.
    :param sentence: a sentence whose polarity has to be classified.
    :param plot: if True, plot a visual representation of the sentence polarity.
    """
    from nltk.corpus import opinion_lexicon
    from nltk.tokenize import treebank

    tokenizer = treebank.TreebankWordTokenizer()

Okay, that's a strange use for imports to exist inside the function but this is because it's a demo function use for simple testing or documentation.

Also, the usage of treebank.TreebankWordTokenizer() is rather odd, we can simply use the nltk.word_tokenize.

Let's move the imports out and rewrite the demo_liu_hu_lexicon as a simple_sentiment function.

from nltk.corpus import opinion_lexicon
from nltk import word_tokenize

def simple_sentiment(text):
    pass

Next, we see

def demo_liu_hu_lexicon(sentence, plot=False):
    """
    Basic example of sentiment classification using Liu and Hu opinion lexicon.
    This function simply counts the number of positive, negative and neutral words
    in the sentence and classifies it depending on which polarity is more represented.
    Words that do not appear in the lexicon are considered as neutral.
    :param sentence: a sentence whose polarity has to be classified.
    :param plot: if True, plot a visual representation of the sentence polarity.
    """
    from nltk.corpus import opinion_lexicon
    from nltk.tokenize import treebank

    tokenizer = treebank.TreebankWordTokenizer()
    pos_words = 0
    neg_words = 0
    tokenized_sent = [word.lower() for word in tokenizer.tokenize(sentence)]

    x = list(range(len(tokenized_sent))) # x axis for the plot
    y = []

The function

first tokenized and lower-cased the sentence

initialize the number of positive and negative words.

x and y is initialized for some plotting later, so let's ignore that.

If we go further down the function:

def demo_liu_hu_lexicon(sentence, plot=False):
    from nltk.corpus import opinion_lexicon
    from nltk.tokenize import treebank

    tokenizer = treebank.TreebankWordTokenizer()
    pos_words = 0
    neg_words = 0
    tokenized_sent = [word.lower() for word in tokenizer.tokenize(sentence)]

    x = list(range(len(tokenized_sent))) # x axis for the plot
    y = []

    for word in tokenized_sent:
        if word in opinion_lexicon.positive():
            pos_words += 1
            y.append(1) # positive
        elif word in opinion_lexicon.negative():
            neg_words += 1
            y.append(-1) # negative
        else:
            y.append(0) # neutral

    if pos_words > neg_words:
        print('Positive')
    elif pos_words < neg_words:
        print('Negative')
    elif pos_words == neg_words:
        print('Neutral')

The loop simply go through each token and check wether the word is in the positive / negative lexicon.

At the end, it checks the no. of positive and negative words and return the tag.

Now lets see whether we can have a better simple_sentiment function, now that we know what demo_liu_hu_lexicon do.

Tokenization in step 1 can't be avoided, so we have:

from nltk.corpus import opinion_lexicon
from nltk.tokenize import treebank

def simple_sentiment(text):
    tokens = [word.lower() for word in word_tokenize(text)]

There's an lazy way out to do step 2-5 is to just copy+paste and change the print() -> return

from nltk.corpus import opinion_lexicon
from nltk.tokenize import treebank

def simple_sentiment(text):
    tokens = [word.lower() for word in word_tokenize(text)]

    for word in tokenized_sent:
        if word in opinion_lexicon.positive():
            pos_words += 1
            y.append(1) # positive
        elif word in opinion_lexicon.negative():
            neg_words += 1
            y.append(-1) # negative
        else:
            y.append(0) # neutral

    if pos_words > neg_words:
        return 'Positive'
    elif pos_words < neg_words:
        return 'Negative'
    elif pos_words == neg_words:
        return 'Neutral'

Now, you have a function that you can do whatever you please.

BTW, the demo is really odd..

When we see a positive word add 1 and when we see a negative we add -1.
And we say something is positive when pos_words > neg_words.

That means that the list of integers comparison follows some Pythonic sequence comparison that might have no linguistic or mathematical logic =(See What happens when we compare list of integers?)


问:
Faster alternative to $(window).scroll?
I've noticed that the jQuery scroll bind of $(window).scroll tends to lag down pages a significant amount. For example, I have elements on my page change styles when I scroll past them using the following script:

```<code>$(window).scroll(function() {
     var bottom_of_window = $(window).scrollTop() + $(window).height();
     $('.ElementsToBeChanged').each(function() {
            var bottom_of_object = $(this).offset().top + $(this).outerHeight();
            if (bottom_of_window > bottom_of_object) {
                //Add my styles
            }
        });

});
</code>```

It understandably makes the website laggy, since it constantly runs on scroll, but I haven't come across any alternative for triggering events when objects are scrolled past. These kinds of websites that trigger events on scroll seem pretty common; What do they use to bypass this lag?

答:
What slows down your performance is not the scroll function itself but the fact that you're doing a lot of calculations per each item on every scroll event.

But despite that I wasn't able to see any drop in performance with 20 elements on screen.

Try to cache your window object as variable [ex: win = $(window)] and use el from the each function instead of this.

Instead of changing your css directly using jQuery, try adding/removing classes.

Don't use denounce as others have mentioned as it will not fire until you stop scrolling. What you're looking for is called throttling.

Here's what I came up with and it works well with 20 elements on my PC:

var win = $(window);

win.scroll(function() {
     var bottom_of_window = win.scrollTop() + win.height();
     $('.ElementsToBeChanged').each(function(index,el) {
            var bottom_of_object = $(el).offset().top + $(el).outerHeight();
            if (bottom_of_window > bottom_of_object) {
                $(el).addClass('red');
            }else{
              $(el).removeClass('red');
            }
        });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.ElementsToBeChanged{
  margin:100px;
  height:200px;
  border:1px solid black;
  transition:2s;
}

.ElementsToBeChanged.red{
  background:red;
}</code>```

.ElementsToBeChanged

.ElementsToBeChanged

.ElementsToBeChanged

.ElementsToBeChanged

.ElementsToBeChanged

.ElementsToBeChanged

.ElementsToBeChanged

.ElementsToBeChanged

.ElementsToBeChanged

.ElementsToBeChanged

.ElementsToBeChanged

.ElementsToBeChanged

.ElementsToBeChanged

.ElementsToBeChanged

.ElementsToBeChanged

.ElementsToBeChanged

.ElementsToBeChanged

.ElementsToBeChanged

.ElementsToBeChanged

.ElementsToBeChanged
```

Lastly, just use a plugin such as Skrollr.js or ScrollMagic

Title: Faster alternative to $(window).scroll?

Body:
I've noticed that the jQuery scroll bind of $(window).scroll tends to lag down pages a significant amount. For example, I have elements on my page change styles when I scroll past them using the following script:

$(window).scroll(function() {
     var bottom_of_window = $(window).scrollTop() + $(window).height();
     $('.ElementsToBeChanged').each(function() {
            var bottom_of_object = $(this).offset().top + $(this).outerHeight();
            if (bottom_of_window > bottom_of_object) {
                //Add my styles
            }
        });

});

It understandably makes the website laggy, since it constantly runs on scroll, but I haven't come across any alternative for triggering events when objects are scrolled past. These kinds of websites that trigger events on scroll seem pretty common; What do they use to bypass this lag?

Body:
What slows down your performance is not the scroll function itself but the fact that you're doing a lot of calculations per each item on every scroll event.

But despite that I wasn't able to see any drop in performance with 20 elements on screen.

Try to cache your window object as variable [ex: win = $(window)] and use el from the each function instead of this.

Instead of changing your css directly using jQuery, try adding/removing classes.

Don't use denounce as others have mentioned as it will not fire until you stop scrolling. What you're looking for is called throttling.

Here's what I came up with and it works well with 20 elements on my PC:

var win = $(window);

win.scroll(function() {
     var bottom_of_window = win.scrollTop() + win.height();
     $('.ElementsToBeChanged').each(function(index,el) {
            var bottom_of_object = $(el).offset().top + $(el).outerHeight();
            if (bottom_of_window > bottom_of_object) {
                $(el).addClass('red');
            }else{
              $(el).removeClass('red');
            }
        });

});

.ElementsToBeChanged{
  margin:100px;
  height:200px;
  border:1px solid black;
  transition:2s;
}

.ElementsToBeChanged.red{
  background:red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="ElementsToBeChanged">.ElementsToBeChanged</div>
<div class="ElementsToBeChanged">.ElementsToBeChanged</div>
<div class="ElementsToBeChanged">.ElementsToBeChanged</div>
<div class="ElementsToBeChanged">.ElementsToBeChanged</div>
<div class="ElementsToBeChanged">.ElementsToBeChanged</div>
<div class="ElementsToBeChanged">.ElementsToBeChanged</div>
<div class="ElementsToBeChanged">.ElementsToBeChanged</div>
<div class="ElementsToBeChanged">.ElementsToBeChanged</div>
<div class="ElementsToBeChanged">.ElementsToBeChanged</div>
<div class="ElementsToBeChanged">.ElementsToBeChanged</div>
<div class="ElementsToBeChanged">.ElementsToBeChanged</div>
<div class="ElementsToBeChanged">.ElementsToBeChanged</div>
<div class="ElementsToBeChanged">.ElementsToBeChanged</div>
<div class="ElementsToBeChanged">.ElementsToBeChanged</div>
<div class="ElementsToBeChanged">.ElementsToBeChanged</div>
<div class="ElementsToBeChanged">.ElementsToBeChanged</div>
<div class="ElementsToBeChanged">.ElementsToBeChanged</div>
<div class="ElementsToBeChanged">.ElementsToBeChanged</div>
<div class="ElementsToBeChanged">.ElementsToBeChanged</div>
<div class="ElementsToBeChanged">.ElementsToBeChanged</div>

Lastly, just use a plugin such as Skrollr.js or ScrollMagic


问:
qsub: is it possible to use both the "-k" and "-o" parameters?
Recently I had to move from a computing cluster with LSF (bsub) to one that uses Torque (qsub).

On the prevous cluster I was able to check my jobs on the fly with the bpeek command.

On the new cluster this command is not available (neither qpeek). In the PBS documentation I see that the -k parameter allows to retain the output on the execution host  (link). The problem here is the name of the log file cannot be defined by the user (using for example the -o parameter) so a new file is created everytime I submit a job.

Is there a way to define the name of the log file and still keep the -k option?

答: Sorry, you're out of luck. Even the documentation for the current version states that this option overrides the path name for the given stream/s. However, it IS open source, so I'm sure they'd accept a pull request. :-)</p>

ContentLicense: CC BY-SA 4.0


问:
What's wrong with the prime number generator?
I wrote a code. The goal was to find the prime numbers up to 1000. It compiles and runs, but it seems that the table is blank at the end. What is the reason for this? How do I fix it? Thanks.</p>

```<code>#include <iostream>
#include <cmath>
#include <fstream>
using namespace std;

int primes[20];
bool prime;
int main()
{
    int i;
for(i=2;i<=1000;i++){
prime=true;
int ii;
   for (ii=1;ii<=sizeof(primes);ii++){
       if (i/ii==floor(i/ii)){
                             prime=false;
                             }
       }
       if (prime==true){
       primes[sizeof(primes+1)]=i;
   }
}
for (i=1;i<=20;i++){
cout << primes[i] << endl;
system("pause");
}
}
</code>```

答:
1) Use vector<int> instead of plain array to handle the array allocation and size housekeeping for you, and with a bit different syntax you may achieve approximately what you want.

2) Test i/ii==floor(i/ii) is bad. Use either floating point division, or (better) modulus operator.

3) if (prime==true) - this is another typical construct showing lack of understanding.

ContentLicense: CC BY-SA 2.5

Body:
I wrote a code. The goal was to find the prime numbers up to 1000. It compiles and runs, but it seems that the table is blank at the end. What is the reason for this? How do I fix it? Thanks.

#include <iostream>
#include <cmath>
#include <fstream>
using namespace std;

int primes[20];
bool prime;
int main()
{
    int i;
for(i=2;i<=1000;i++){
prime=true;
int ii;
   for (ii=1;ii<=sizeof(primes);ii++){
       if (i/ii==floor(i/ii)){
                             prime=false;
                             }
       }
       if (prime==true){
       primes[sizeof(primes+1)]=i;
   }
}
for (i=1;i<=20;i++){
cout << primes[i] << endl;
system("pause");
}
}


问:
Reclassifying data column with specific parameters
I have a tree list with diameters for each tree (among many other variables). I'm trying to streamline the process of adding a new column that gives a diameter class based on each tree's diameter and I think it can be done with indexing and/or a for loop but I'm not strong with either of these skills. Diameters range from 0-80 cm. I want to put these into 2-cm classes where a tree between 0-0.9 is class "0", a tree 1.0-2.9 is class "2", a tree 3-4.9 is class "4" etc all the way to 80 cm. Here is a small snapshot of my data:

```<code>     Unit Plot Treatment           Year Species2 DBHmet
2     1    1        WB Post-treatment     PIPO 42.164
3     1    1        WB Post-treatment     PIPO 24.384
4     1    1        WB Post-treatment     PIPO 16.764
5     1    1        WB Post-treatment     PIPO 23.114
6     1    1        WB Post-treatment     PIPO 41.148
7     1    1        WB Post-treatment     PIPO  4.826
8     1    1        WB Post-treatment     PIPO 17.780
10    1    1        WB    Pre-harvest     PIPO 11.176
11    1    1        WB    Pre-harvest     PIPO 42.164
12    1    1        WB    Pre-harvest     PIPO  3.302
13    1    1        WB    Pre-harvest     PIPO 12.192
</code>```

How can I quickly add an additional column that places the "DBHmet" into 2cm classes, as described above?

答:
From the snapshot, I assume, that you have a dataframe/table and not a list.
Assuming this, the following will change the DBHmet values to the desired 2 cm classes:</p>

```<code>> data <- data.frame(DBHmet = c(0.0, 0.9, 1.0, 2.9, 3.0, 4.9, 80.0),
+                    otherVar = rep("a", 7))
> data$DBHmet_2cm <- floor(((data$DBHmet + 1)/2))*2
> data
  DBHmet otherVar DBHmet_2cm
1    0.0        a          0
2    0.9        a          0
3    1.0        a          2
4    2.9        a          2
5    3.0        a          4
6    4.9        a          4
7   80.0        a         80
</code>```

Body:
I have a tree list with diameters for each tree (among many other variables). I'm trying to streamline the process of adding a new column that gives a diameter class based on each tree's diameter and I think it can be done with indexing and/or a for loop but I'm not strong with either of these skills. Diameters range from 0-80 cm. I want to put these into 2-cm classes where a tree between 0-0.9 is class "0", a tree 1.0-2.9 is class "2", a tree 3-4.9 is class "4" etc all the way to 80 cm. Here is a small snapshot of my data:

     Unit Plot Treatment           Year Species2 DBHmet
2     1    1        WB Post-treatment     PIPO 42.164
3     1    1        WB Post-treatment     PIPO 24.384
4     1    1        WB Post-treatment     PIPO 16.764
5     1    1        WB Post-treatment     PIPO 23.114
6     1    1        WB Post-treatment     PIPO 41.148
7     1    1        WB Post-treatment     PIPO  4.826
8     1    1        WB Post-treatment     PIPO 17.780
10    1    1        WB    Pre-harvest     PIPO 11.176
11    1    1        WB    Pre-harvest     PIPO 42.164
12    1    1        WB    Pre-harvest     PIPO  3.302
13    1    1        WB    Pre-harvest     PIPO 12.192

How can I quickly add an additional column that places the "DBHmet" into 2cm classes, as described above?

Body:
From the snapshot, I assume, that you have a dataframe/table and not a list.
Assuming this, the following will change the DBHmet values to the desired 2 cm classes:

> data <- data.frame(DBHmet = c(0.0, 0.9, 1.0, 2.9, 3.0, 4.9, 80.0),
+                    otherVar = rep("a", 7))
> data$DBHmet_2cm <- floor(((data$DBHmet + 1)/2))*2
> data
  DBHmet otherVar DBHmet_2cm
1    0.0        a          0
2    0.9        a          0
3    1.0        a          2
4    2.9        a          2
5    3.0        a          4
6    4.9        a          4
7   80.0        a         80


问:
Complete TFS Pull Request programmatically
Using the Microsoft.TeamFoundationServer.Client (15.112.1) to connect to a TFS 2017 Update 2 server we can get details about an existing PR like this:

```<code>var connection = new VssConnection(collectionUri, credentials);
var client = connection.GetClient<GitHttpClient>();
var pr = await client.GetPullRequestByIdAsync(pullRequestId);
</code>```

Also, we can create new PR like this:

```<code>var pr = await client.CreatePullRequestAsync(
        new GitPullRequest
        {
          SourceRefName = "master",
          TargetRefName = "develop",
          Title = "[Automatic Merge]"
        },
        projectName, repositoryName);
</code>```

In addition, we can vote on the PR like this:

```<code>var pr = await client.CreatePullRequestReviewerAsync(
            reviewer, projectName, repositoryName, pullRequestId, authorizedIdenity.Id.ToString());
</code>```

Is there any way to complete the PR (overriding or not existing branch
  policies) and proceed with the merge operation?

答:
The GitHttpClient has an UpdatePullRequestAsync method.

To complete the pull request you need to update the Status property of your pull request. and use the UpdatePullRequestAsync method to complete your PR.

Please make sure that to set the the CompletionOptions property to specify whether you are merging the commit, delete the source branch etc.

So your code would look like following

```<code>pr.Status = PullRequestStatus.Completed
pr.CompletionOption = new GitPullRequestCompletionOption() { SquashMerge = true };
client.UpdatePullRequest(pr, repositoryId, pullRequestId);
</code>```

EDIT:

The ByPassPolicy is not available for the released version of Microsoft.TeamFoundationServer.ExtendedClient yet.

However, if you install the pre-release NuGet Package v15.122.1-preview of library Microsoft.TeamFoundationServer.ExtendedClient, you will see the option ByPassPolicy as a property in the GitPullrequestCompletionOptions class. You can set it to true to by pass policy.

Body:
Using the Microsoft.TeamFoundationServer.Client (15.112.1) to connect to a TFS 2017 Update 2 server we can get details about an existing PR like this:

var connection = new VssConnection(collectionUri, credentials);
var client = connection.GetClient<GitHttpClient>();
var pr = await client.GetPullRequestByIdAsync(pullRequestId);

Also, we can create new PR like this:

var pr = await client.CreatePullRequestAsync(
        new GitPullRequest
        {
          SourceRefName = "master",
          TargetRefName = "develop",
          Title = "[Automatic Merge]"
        },
        projectName, repositoryName);

In addition, we can vote on the PR like this:

var pr = await client.CreatePullRequestReviewerAsync(
            reviewer, projectName, repositoryName, pullRequestId, authorizedIdenity.Id.ToString());

Is there any way to complete the PR (overriding or not existing branch
  policies) and proceed with the merge operation?

Body:
The GitHttpClient has an UpdatePullRequestAsync method.

To complete the pull request you need to update the Status property of your pull request. and use the UpdatePullRequestAsync method to complete your PR.

Please make sure that to set the the CompletionOptions property to specify whether you are merging the commit, delete the source branch etc.

So your code would look like following

pr.Status = PullRequestStatus.Completed
pr.CompletionOption = new GitPullRequestCompletionOption() { SquashMerge = true };
client.UpdatePullRequest(pr, repositoryId, pullRequestId);

EDIT:

The ByPassPolicy is not available for the released version of Microsoft.TeamFoundationServer.ExtendedClient yet.

However, if you install the pre-release NuGet Package v15.122.1-preview of library Microsoft.TeamFoundationServer.ExtendedClient, you will see the option ByPassPolicy as a property in the GitPullrequestCompletionOptions class. You can set it to true to by pass policy.


问:
jQuery - How can I create an element based on user choice in a loop?
I'm trying to create 5 different audio players from the following code to call them out individually wherever I need it in the HTML document: https://codepen.io/katzkode/pen/ZbxYYG

The issue is that these 2 loops use a single div element to call the function (5 audio players at once):

For audio:

```<code>/* createAudioElements
 * create audio elements for each file in files */
function createAudioElements() {
    for (f in files) {
        var audioString = "<audio id=\"audio-" + f + "\" class=\"audio\" preload=\"true\"><source src=\"http://www.alexkatz.me/codepen/music/" + files[f] + "\"></audio>";
        $("#audio-players").append(audioString);
    }
}
</code>```

For div element:

```<code>/* createAudioPlayers
 * create audio players for each file in files */
function createAudioPlayers() {
    for (f in files) {
        var playerString = "<div id=\"audioplayer-" + f + "\" class=\"audioplayer\"><button id=\"playbutton-" + f + "\" class=\"play playbutton\"></button><div id=\"timeline-" + f + "\" class=\"timeline\"><div id=\"playhead-" + f + "\" class=\"playhead\"></div></div></div>";
        $("#audio-players").append(playerString);
    }
}
</code>```

But what I'm trying to do is invoke a specific player with a specific song of my choice instead of 5 of them at once which is how it currently works.

Like this:

```<code><div id="audio-players1"></div>
<div id="audio-players2"></div>
<div id="audio-players3"></div>
<div id="audio-players4"></div>
<div id="audio-players5"></div>
</code>```

I've tried to do this for both loops:

Replacing this:

```<code>$("#audio-players")
</code>```

With this:

```<code>$("#audio-players" + f)
</code>```

But then the buttons won't work.

Here's the code to pull the files from:

```<code>var files = ["interlude.mp3", // 0
            "chooseyourweapon.mp3", // 1
            "interlude.mp3", // 2
            "scriptures.mp3",
       "scriptures.mp3"// 3
            ];
</code>```

And I'm unsure how to proceed, I'm still learning. Thank you.

答:
Life will become a lot simpler by doing the following in a single loop using files.forEach(...) (or the jQuery equivalent) :

creating the <audio> elements

creating the corresponding
 elements

attaching the play button's .on('click' ...) event handler

This approach will cause any assignments made within the loop to remain available to the event handler. This is a feature of javascript (and some other languages) called "closure".

```<code>/* createAudio
 * create audio elements and corresponding div elements in a single loop */
function createAudio() {
    files.forEach(function(fileName) {
        var $audio = $('<audio class="audio" preload="true"><source src="http://www.alexkatz.me/codepen/music/' + fileName + '"></audio>');
        var $player = $('<div class="audioplayer"><button class="play playbutton"></button><div class="timeline"><div class="playhead"></div></div></div>')

        $("#audio-players").append($audio).append($player);

        $player.find(".playbutton").on('click', function() {
            $audio.play(); // "closure" causes the variable `$audio` still to exist when the button is clicked, even though createAudio() and the iterator function have both completed and returned.
        });
        // Attach any further event handlers here (eg "stop", "pause")
    });
}
</code>```

Note that the need for elements to have a unique ids disappears - unless of course they are needed for other purposes, though it's highly likely that the need disappears completely.

Body:
I'm trying to create 5 different audio players from the following code to call them out individually wherever I need it in the HTML document: https://codepen.io/katzkode/pen/ZbxYYG

The issue is that these 2 loops use a single div element to call the function (5 audio players at once):

For audio:

/* createAudioElements
 * create audio elements for each file in files */
function createAudioElements() {
    for (f in files) {
        var audioString = "<audio id=\"audio-" + f + "\" class=\"audio\" preload=\"true\"><source src=\"http://www.alexkatz.me/codepen/music/" + files[f] + "\"></audio>";
        $("#audio-players").append(audioString);
    }
}

For div element:

/* createAudioPlayers
 * create audio players for each file in files */
function createAudioPlayers() {
    for (f in files) {
        var playerString = "
<button id=\"playbutton-" + f + "\" class=\"play playbutton\"></button>

";
        $("#audio-players").append(playerString);
    }
}

But what I'm trying to do is invoke a specific player with a specific song of my choice instead of 5 of them at once which is how it currently works.

Like this:

I've tried to do this for both loops:

Replacing this:

$("#audio-players")

With this:

$("#audio-players" + f)

But then the buttons won't work.

Here's the code to pull the files from:

var files = ["interlude.mp3", // 0
            "chooseyourweapon.mp3", // 1
            "interlude.mp3", // 2
            "scriptures.mp3",
       "scriptures.mp3"// 3
            ];

And I'm unsure how to proceed, I'm still learning. Thank you.

Body:
Life will become a lot simpler by doing the following in a single loop using files.forEach(...) (or the jQuery equivalent) :

creating the <audio> elements

creating the corresponding <div> elements

attaching the play button's .on('click' ...) event handler

This approach will cause any assignments made within the loop to remain available to the event handler. This is a feature of javascript (and some other languages) called "closure".

/* createAudio
 * create audio elements and corresponding div elements in a single loop */
function createAudio() {
    files.forEach(function(fileName) {
        var $audio = $('<audio class="audio" preload="true"><source src="http://www.alexkatz.me/codepen/music/' + fileName + '"></audio>');
        var $player = $('<div class="audioplayer"><button class="play playbutton"></button><div class="timeline"><div class="playhead"></div></div></div>')

        $("#audio-players").append($audio).append($player);

        $player.find(".playbutton").on('click', function() {
            $audio.play(); // "closure" causes the variable `$audio` still to exist when the button is clicked, even though createAudio() and the iterator function have both completed and returned.
        });
        // Attach any further event handlers here (eg "stop", "pause")
    });
}

Note that the need for elements to have a unique ids disappears - unless of course they are needed for other purposes, though it's highly likely that the need disappears completely.


问:
Laravel valet linked php error
I got an error.

```<code>$ valet install

[DomainException]
Unable to determine linked PHP.

install
</code>```

'which' command returns:

```<code>$ which php
/usr/local/Cellar/php70/7.0.6/bin/php
</code>```

答:
I used Homebrew to instal php7.1 , So I ran this command in terminal

ln -s /usr/local/opt/php71/bin/php /usr/local/bin/php

and everything is done.

Title: Laravel valet linked php error

Body:
I got an error.

$ valet install

[DomainException]
Unable to determine linked PHP.

install

'which' command returns:

$ which php
/usr/local/Cellar/php70/7.0.6/bin/php


问:
Best way to get vertices of a mesh three.js
I am new to Three.js so perhaps I am not going abut this optimally,

I have geometry which I create as follows,

```<code>const geo = new THREE.PlaneBufferGeometry(10,0);
</code>```

I then apply a rotation to it

```<code>geo.applyMatrix( new THREE.Matrix4().makeRotationX( Math.PI * 0.5 ) );
</code>```

then I create a Mesh from it

```<code>const open = new THREE.Mesh( geo, materialNormal);
</code>```

I then apply a bunch of operations to the mesh to position it correctly, as follows:

```<code>open.position.copy(v2(10,20);
open.position.z = 0.5*10

open.position.x -= 20
open.position.y -= 10
open.rotation.z = angle;
</code>```

Now what is the best way to get the vertices of the mesh both before and after it's position is changed? I was surpised to discover that the vertices of a mesh are not in-built into three.js.

Any hints and code samples would be greatly appreciated.

答:
Here's an example written by typescript.

It gets the grid's position in the world coordinate system.

```<code>    GetObjectVertices(obj: THREE.Object3D): { pts: Array<THREE.Vector3>, faces: Array<THREE.Face3> }
{
    let pts: Array<THREE.Vector3> = [];

    let rs = { pts: pts, faces: null };

    if (obj.hasOwnProperty("geometry"))
    {
        let geo = obj["geometry"];
        if (geo instanceof THREE.Geometry)
        {
            for (let pt of geo.vertices)
            {
                pts.push(pt.clone().applyMatrix4(obj.matrix));
            }
            rs.faces = geo.faces;
        }
        else if (geo instanceof THREE.BufferGeometry)
        {
            let tempGeo = new THREE.Geometry().fromBufferGeometry(geo);
            for (let pt of tempGeo.vertices)
            {
                pts.push(pt.applyMatrix4(obj.matrix));
            }
            rs.faces = tempGeo.faces;
            tempGeo.dispose();
        }
    }
    return rs;
}
</code>```

or

```<code>if (geo instanceof THREE.BufferGeometry)
{
    let positions: Float32Array = geo.attributes["position"].array;
    let ptCout = positions.length / 3;
    for (let i = 0; i < ptCout; i++)
    {
        let p = new THREE.Vector3(positions[i * 3], positions[i * 3 + 1], positions[i * 3 + 2]);
    }
}
</code>```

Body:
I am new to Three.js so perhaps I am not going abut this optimally,

I have geometry which I create as follows,

const geo = new THREE.PlaneBufferGeometry(10,0);

I then apply a rotation to it

geo.applyMatrix( new THREE.Matrix4().makeRotationX( Math.PI * 0.5 ) );

then I create a Mesh from it

const open = new THREE.Mesh( geo, materialNormal);

I then apply a bunch of operations to the mesh to position it correctly, as follows:

open.position.copy(v2(10,20);
open.position.z = 0.5*10

open.position.x -= 20
open.position.y -= 10
open.rotation.z = angle;

Now what is the best way to get the vertices of the mesh both before and after it's position is changed? I was surpised to discover that the vertices of a mesh are not in-built into three.js.

Any hints and code samples would be greatly appreciated.

Body:
Here's an example written by typescript.

It gets the grid's position in the world coordinate system.

    GetObjectVertices(obj: THREE.Object3D): { pts: Array<THREE.Vector3>, faces: Array<THREE.Face3> }
{
    let pts: Array<THREE.Vector3> = [];

    let rs = { pts: pts, faces: null };

    if (obj.hasOwnProperty("geometry"))
    {
        let geo = obj["geometry"];
        if (geo instanceof THREE.Geometry)
        {
            for (let pt of geo.vertices)
            {
                pts.push(pt.clone().applyMatrix4(obj.matrix));
            }
            rs.faces = geo.faces;
        }
        else if (geo instanceof THREE.BufferGeometry)
        {
            let tempGeo = new THREE.Geometry().fromBufferGeometry(geo);
            for (let pt of tempGeo.vertices)
            {
                pts.push(pt.applyMatrix4(obj.matrix));
            }
            rs.faces = tempGeo.faces;
            tempGeo.dispose();
        }
    }
    return rs;
}

or

if (geo instanceof THREE.BufferGeometry)
{
    let positions: Float32Array = geo.attributes["position"].array;
    let ptCout = positions.length / 3;
    for (let i = 0; i < ptCout; i++)
    {
        let p = new THREE.Vector3(positions[i * 3], positions[i * 3 + 1], positions[i * 3 + 2]);
    }
}


问:
Rails Paperclip Invalid Path in AWS
I'm using rails and paperclip in uploading in AWS S3 bucket.  The bucket name, secret keys, region are the same for both Heroku and AWS, in Heroku it's working fine i can see the image but in AWS its not working.

In AWS this is the path  and its not working.

http://s3-ap-southeast-2.amazonaws.com/assets.steel-ps.com/var/www/steelip-admin/public/ckeditor_assets/pictures/45/content_notes-icon-mac.jpg

In Heroku its working fine

http://s3-ap-southeast-2.amazonaws.com/assets.steel-ps.com/app/public/ckeditor_assets/pictures/45/content_notes-icon-mac.jpg

Notice that in AWS its adding my '/var/www/steelip-admin' which is the folder in my server.   What could be wrong.

Thanks.

答:
Thanks for all the help everyone.  Basically the fix were inside the CkEditor::Picture class.  I have remove the rails_root in front of the path.  </p>

```<code>path: 'app/public/ckeditor_assets/pictures/:id/:style_:basename.:extension'
</code>```

Title: Rails Paperclip Invalid Path in AWS

Body:
Thanks for all the help everyone.  Basically the fix were inside the CkEditor::Picture class.  I have remove the rails_root in front of the path.

path: 'app/public/ckeditor_assets/pictures/:id/:style_:basename.:extension'


问:
Pass vector elements to a function in c++
I now have a vector of objects. And a pre-defined function that can take objects as parameters. Just curious if there's a way of passing these objects to this function?

```<code>std::vector<obj> objects; //contains obj1, obj2 .., objn
</code>```

And I'd like to achieve something like this:

```<code> foo(obj1, obj2 ... , objn) //foo can take as many objects as I want
</code>```

答:
While common in scripted languages like P(ython|erl), this still requires a library solution in C++. Something like</p>

```<code>template<typename F, class Container> inline decltype(auto) apply(F f, Container const &args) {
    switch(args.size()) {
        case 0: return f();
        case 1: return f(args.front());
        case 2: return f(args[0], args[1]);
        case 3: return f(args[0], args[1], args[2]);
        // and so forth
        default: throw std::range_error("f does not accept that many arguments!");
    }
}
</code>```

Body:
I now have a vector of objects. And a pre-defined function that can take objects as parameters. Just curious if there's a way of passing these objects to this function?

std::vector<obj> objects; //contains obj1, obj2 .., objn

And I'd like to achieve something like this:

 foo(obj1, obj2 ... , objn) //foo can take as many objects as I want

Body:
While common in scripted languages like P(ython|erl), this still requires a library solution in C++. Something like

template<typename F, class Container> inline decltype(auto) apply(F f, Container const &args) {
    switch(args.size()) {
        case 0: return f();
        case 1: return f(args.front());
        case 2: return f(args[0], args[1]);
        case 3: return f(args[0], args[1], args[2]);
        // and so forth
        default: throw std::range_error("f does not accept that many arguments!");
    }
}


问:
jQuery ajax in ASP.NET with customErrors mode="On"
any idea how to retrieve the original exception thrown on server side when doing

ajax calls with jQuery  and using

customErrors mode="On"

in web.config.

If mode="Off" I can take the error using this function:

```<code>error: function(xhr, status, error) {
        var error = JSON.parse(xhr.responseText);
        alert(error.Message);
}
</code>```

答:
I had the same problem and found a couple of differens solutions:

Either, you could disable customerrors for a specific location in web.config.

```<code><location path="ajaxReuests">
  <system.web>
    <customErrors mode="Off" />
  </system.web>
</location>
</code>```

However, be aware of the customerrors security vunerability when disabling custom errors.

Another (safer solution) would be to use the ajax-complete-callback-handler together with meta tags on the error pages to detect errors and forward the response to the "normal" error function. In order for this to work, you need to include the error status code on your custom error pages, eg:

```<code><head runat="server">
  <title>Oops</title>
  <link href="/css/default.css" rel="stylesheet" type="text/css" />
  <meta name="statuscode" content="500" />
  ...
</code>```

Then you could parse out the status code from XmlHttpRequest.responsText and invoke the normal error function if an errorneous status code is detected.

```<code>$.ajax({

  url: '/ajax/mydata.ashx',
  dataType: 'json',

  complete: function(XMLHttpRequest, textStatus) {
    var statuscodeRegex = /content="(.*?)"/;
    if (statuscodeRegex.test(XMLHttpRequest.responseText) &&
      statuscodeRegex.exec(XMLHttpRequest.responseText)[0] != 200)
      this.error(XMLHttpRequest, textStatus, "Oh no... an error!");
  },

  success: function(myData) {
    //Do something useful...
  },

  error: function(XMLHttpRequest, textStatus, errorThrown) {
    //Error...
  }
});
</code>```

Body:
any idea how to retrieve the original exception thrown on server side when doing

ajax calls with jQuery  and using

customErrors mode="On"

in web.config.

If mode="Off" I can take the error using this function:

error: function(xhr, status, error) {
        var error = JSON.parse(xhr.responseText);
        alert(error.Message);
}

Body:
I had the same problem and found a couple of differens solutions:

Either, you could disable customerrors for a specific location in web.config.

<location path="ajaxReuests">
  <system.web>
    <customErrors mode="Off" />
  </system.web>
</location>

However, be aware of the customerrors security vunerability when disabling custom errors.

Another (safer solution) would be to use the ajax-complete-callback-handler together with meta tags on the error pages to detect errors and forward the response to the "normal" error function. In order for this to work, you need to include the error status code on your custom error pages, eg:

<head runat="server">
  <title>Oops</title>
  <link href="/css/default.css" rel="stylesheet" type="text/css" />
  <meta name="statuscode" content="500" />
  ...

Then you could parse out the status code from XmlHttpRequest.responsText and invoke the normal error function if an errorneous status code is detected.

$.ajax({

  url: '/ajax/mydata.ashx',
  dataType: 'json',

  complete: function(XMLHttpRequest, textStatus) {
    var statuscodeRegex = /content="(.*?)"/;
    if (statuscodeRegex.test(XMLHttpRequest.responseText) &&
      statuscodeRegex.exec(XMLHttpRequest.responseText)[0] != 200)
      this.error(XMLHttpRequest, textStatus, "Oh no... an error!");
  },

  success: function(myData) {
    //Do something useful...
  },

  error: function(XMLHttpRequest, textStatus, errorThrown) {
    //Error...
  }
});


问:
The request was aborted: Could not create SSL/TLS secure channel
We are unable to connect to an HTTPS server using WebRequest because of this error message:

The request was aborted: Could not create SSL/TLS secure channel.

We know that the server doesn't have a valid HTTPS certificate with the path used, but to bypass this issue, we use the following code that we've taken from another StackOverflow post:

```<code>private void Somewhere() {
    ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(AlwaysGoodCertificate);
}

private static bool AlwaysGoodCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors policyErrors) {
   return true;
}
</code>```

The problem is that server never validates the certificate and fails with the above error. Does anyone have any idea of what I should do?

I should mention that a colleague and I performed tests a few weeks ago and it was working fine with something similar to what I wrote above. The only "major difference" we've found is that I'm using Windows 7 and he was using Windows XP.  Does that change something?

答: The default .NET ServicePointManager.SecurityProtocol uses SSLv3 and TLS. If you are accessing an Apache server, there is a config variable called SSLProtocol which defaults to TLSv1.2. You can either set the ServicePointManager.SecurityProtocol to use the appropriate protocol supported by your web server or change your Apache config to allow all protocols like this SSLProtocolall.

Body:
We are unable to connect to an HTTPS server using WebRequest because of this error message:

The request was aborted: Could not create SSL/TLS secure channel.

We know that the server doesn't have a valid HTTPS certificate with the path used, but to bypass this issue, we use the following code that we've taken from another StackOverflow post:

private void Somewhere() {
    ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(AlwaysGoodCertificate);
}

private static bool AlwaysGoodCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors policyErrors) {
   return true;
}

The problem is that server never validates the certificate and fails with the above error. Does anyone have any idea of what I should do?

I should mention that a colleague and I performed tests a few weeks ago and it was working fine with something similar to what I wrote above. The only "major difference" we've found is that I'm using Windows 7 and he was using Windows XP.  Does that change something?


问:
jQuery get Select option value shows Undefined error
I am generating an Html select in a form that is in a bootstrap 3 modal popup. I am trying to get the selected value and pass it through JQuery to dump to a database.

I have other input fields and a text area field using tinyMCE that I get the value from without any issues at all using $('#id').val();.

My select is super simple and displays in the view source as:

```<code><select id='practitionerID' name='practitionerID' class='form-control'>
    <option value="1">Doctor 1</option>
    <option value="2">Doctor 2</option>
</select>
</code>```

I am have tried many different ways to get the data to display and cannot for the life of me get the option value.

I have tried the following:

```<code>$('#practitionerID').prop('selectedIndex'); // give's me -1 no matter the option selected
$('#practitionerID').val(); // returns null
$('#practitionerID').text(); // returns null, dont want the text anyways
$("#practitionerID option:selected").val(); // returns undefined
$("#practitionerID option:selected" ).text(); //returns undefined, still not what i want.
</code>```

EDIT:
So it tried this and it actually gives me a value now but only ever gives me the first option in the dropdown even though i have chosen something else.
    $('#practitionerID :selected').val();

The only thing i can think of that is tripping this up is the fact that I am loading it in a modal? Maybe it cannot read into it for some reason to see the property?

When I load an existing record and get the data.event.practitionerID it works gives me the value fine. However, I cannot seem to set the value when i get it though. So it appears to be an issue with the ID of this select but I just cant see where or how.

Any help would be greatly appreciated!

答:
I am a complete idiot.

The solution that worked for me was

```<code>$('#practitionerID').val();
</code>```

The issue is I had a quick add feature on the same page and guess what I used, a drop down with the same ID. It was taking the value from the first drop down every time.

I hope this mistake can help someone else.

Body:
I am generating an Html select in a form that is in a bootstrap 3 modal popup. I am trying to get the selected value and pass it through JQuery to dump to a database.

I have other input fields and a text area field using tinyMCE that I get the value from without any issues at all using $('#id').val();.

My select is super simple and displays in the view source as:

<select id='practitionerID' name='practitionerID' class='form-control'>
    <option value="1">Doctor 1</option>
    <option value="2">Doctor 2</option>
</select>

I am have tried many different ways to get the data to display and cannot for the life of me get the option value.

I have tried the following:

$('#practitionerID').prop('selectedIndex'); // give's me -1 no matter the option selected
$('#practitionerID').val(); // returns null
$('#practitionerID').text(); // returns null, dont want the text anyways
$("#practitionerID option:selected").val(); // returns undefined
$("#practitionerID option:selected" ).text(); //returns undefined, still not what i want.

EDIT:
So it tried this and it actually gives me a value now but only ever gives me the first option in the dropdown even though i have chosen something else.
    $('#practitionerID :selected').val();

The only thing i can think of that is tripping this up is the fact that I am loading it in a modal? Maybe it cannot read into it for some reason to see the property?

When I load an existing record and get the data.event.practitionerID it works gives me the value fine. However, I cannot seem to set the value when i get it though. So it appears to be an issue with the ID of this select but I just cant see where or how.

Any help would be greatly appreciated!

Body:
I am a complete idiot.

The solution that worked for me was

$('#practitionerID').val();

The issue is I had a quick add feature on the same page and guess what I used, a drop down with the same ID. It was taking the value from the first drop down every time.

I hope this mistake can help someone else.


问:
How to store input line by line from an input file into variables
I am trying to store input of certain data types into variables and print them out into a output file but my code does not seem to work. If I enter the input through std in with System.in Scanner and print to stdout, my code will work. However, when I try what I have, I keep getting this:

```<code> Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at Queue.main(Queue.java:17)
</code>```

Here is my code:

```<code>import java.util.*;
import java.io.*;

public class Queue {
public static void main(String[] args) throws IOException {

// open files
// takes input from test-input.txt
Scanner input = new Scanner(new File("test-input.txt"));
// prints output to test-output.txt
PrintWriter output = new PrintWriter(new FileWriter("test-output.txt"));

//Scanner input = new Scanner(System.in);

while (input.hasNextLine()) {
  int teller = input.nextInt();
  String name = input.next();
  int simTime = input.nextInt();
  int transTime = input.nextInt();

  output.println(teller + " " + name + " " + simTime + " " + transTime);

}
// close files
input.close();
output.close();
}
}
</code>```

My input file contains lines such as:

```<code>1 Jesse 2 9
2 Wilson 1 4
3 King 4 8
4 Andy 6 7
</code>```

答:
Try to make sure you are parsing a non empty line, it can happen if your file has extra empty lines, so i suggest do a check inside your while statement

```<code>while (input.hasNextLine()) {
            final String line = input.nextLine().trim();
            if (line.isEmpty()) continue; // continue if line is empty
            String [] items = line.split("\\s+");
            int teller = Integer.parseInt(items[0]);
            String name = items[1];
            int simTime = Integer.parseInt(items[3]);
            int transTime = Integer.parseInt(items[3]);
            output.println(teller + " " + name + " " + simTime + " " + transTime);
        }
</code>```

Body:
I am trying to store input of certain data types into variables and print them out into a output file but my code does not seem to work. If I enter the input through std in with System.in Scanner and print to stdout, my code will work. However, when I try what I have, I keep getting this:

 Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at Queue.main(Queue.java:17)

Here is my code:

import java.util.*;
import java.io.*;

public class Queue {
public static void main(String[] args) throws IOException {

// open files
// takes input from test-input.txt
Scanner input = new Scanner(new File("test-input.txt"));
// prints output to test-output.txt
PrintWriter output = new PrintWriter(new FileWriter("test-output.txt"));

//Scanner input = new Scanner(System.in);

while (input.hasNextLine()) {
  int teller = input.nextInt();
  String name = input.next();
  int simTime = input.nextInt();
  int transTime = input.nextInt();

  output.println(teller + " " + name + " " + simTime + " " + transTime);

}
// close files
input.close();
output.close();
}
}

My input file contains lines such as:

1 Jesse 2 9
2 Wilson 1 4
3 King 4 8
4 Andy 6 7

Body:
Try to make sure you are parsing a non empty line, it can happen if your file has extra empty lines, so i suggest do a check inside your while statement

while (input.hasNextLine()) {
            final String line = input.nextLine().trim();
            if (line.isEmpty()) continue; // continue if line is empty
            String [] items = line.split("\\s+");
            int teller = Integer.parseInt(items[0]);
            String name = items[1];
            int simTime = Integer.parseInt(items[3]);
            int transTime = Integer.parseInt(items[3]);
            output.println(teller + " " + name + " " + simTime + " " + transTime);
        }


问:
App crash on share file dialog only in release mode
My application crash when I open the file share dialog, happens only in release mode, in debug mode everything works correctly.
this is my code:

```<code>        private List<IStorageFile> fileSelectedToShare;

        private void shareFileAppBarButton_Click(object sender, RoutedEventArgs e)
            {
                dataTransferManager = DataTransferManager.GetForCurrentView();
                dataTransferManager.DataRequested += DataTransferManager_DataRequested;

                DataTransferManager.ShowShareUI();
            }

            private void DataTransferManager_DataRequested(DataTransferManager sender, DataRequestedEventArgs args)
            {
                if (fileSelectedToShare == null) return;

                DataRequest request = args.Request;
                if (fileSelectedToShare.Count != 0) {
                    request.Data.Properties.Title = "Share";
                    request.Data.Properties.Description = "Share the selected document";
                    request.Data.SetStorageItems(fileSelectedToShare);
                    fileSelectedToShare.Clear();
                }
                dataTransferManager.DataRequested -= DataTransferManager_DataRequested;
            }
</code>```

fileSelectedToShare is initialized and contains files.

this is the exception:

System.Runtime.InteropServices.MissingInteropDataException: 'ComTypeMarshalling_MissingInteropData, System.Collections.Generic.IEnumerable. For more information, visit http://go.microsoft.com/fwlink/?LinkId=623485'

答:
Not sure why, but copying the file references into another collection and passing the latter into request.Data.SetStorageItems() makes your code work:

```<code>    private void DataTransferManager_DataRequested(DataTransferManager sender, DataRequestedEventArgs args)
    {
        if (fileSelectedToShare == null) return;

        DataRequest request = args.Request;
        if (fileSelectedToShare.Count != 0)
        {
            request.Data.Properties.Title = "Share";
            request.Data.Properties.Description = "Share the selected document";

            List<IStorageItem> files = new List<IStorageItem>(fileSelectedToShare);
            request.Data.SetStorageItems(files);

            fileSelectedToShare.Clear();
        }
        dataTransferManager.DataRequested -= DataTransferManager_DataRequested;
    }
</code>```

Body:
My application crash when I open the file share dialog, happens only in release mode, in debug mode everything works correctly.
this is my code:

        private List<IStorageFile> fileSelectedToShare;

        private void shareFileAppBarButton_Click(object sender, RoutedEventArgs e)
            {
                dataTransferManager = DataTransferManager.GetForCurrentView();
                dataTransferManager.DataRequested += DataTransferManager_DataRequested;

                DataTransferManager.ShowShareUI();
            }

            private void DataTransferManager_DataRequested(DataTransferManager sender, DataRequestedEventArgs args)
            {
                if (fileSelectedToShare == null) return;

                DataRequest request = args.Request;
                if (fileSelectedToShare.Count != 0) {
                    request.Data.Properties.Title = "Share";
                    request.Data.Properties.Description = "Share the selected document";
                    request.Data.SetStorageItems(fileSelectedToShare);
                    fileSelectedToShare.Clear();
                }
                dataTransferManager.DataRequested -= DataTransferManager_DataRequested;
            }

fileSelectedToShare is initialized and contains files.

this is the exception:

System.Runtime.InteropServices.MissingInteropDataException: 'ComTypeMarshalling_MissingInteropData, System.Collections.Generic.IEnumerable. For more information, visit http://go.microsoft.com/fwlink/?LinkId=623485'

Body:
Not sure why, but copying the file references into another collection and passing the latter into request.Data.SetStorageItems() makes your code work:

    private void DataTransferManager_DataRequested(DataTransferManager sender, DataRequestedEventArgs args)
    {
        if (fileSelectedToShare == null) return;

        DataRequest request = args.Request;
        if (fileSelectedToShare.Count != 0)
        {
            request.Data.Properties.Title = "Share";
            request.Data.Properties.Description = "Share the selected document";

            List<IStorageItem> files = new List<IStorageItem>(fileSelectedToShare);
            request.Data.SetStorageItems(files);

            fileSelectedToShare.Clear();
        }
        dataTransferManager.DataRequested -= DataTransferManager_DataRequested;
    }


问:
C# - IComparer - If datetime is null then should be sorted to the bottom not the top
I have a list of dates that I want to sort in an ascending order. However, the default comparer means that I have:

```<code>null
null
18/01/2011
23/01/2011
</code>```

Can someone help with a IComparer that will mean that the dates sorted in ascending order will look like:

```<code>18/01/2011
23/01/2011
null
null
</code>```

答:
Here's a generic comparer that should work for pretty much any type:</p>

```<code>var yourList = new List<DateTime?>
                   {
                       null, new DateTime(2011, 1, 23),
                       null, new DateTime(2011, 1, 18)
                   };

var comparer = new NullsLastComparer<DateTime?>();
yourList.Sort(comparer);  // now contains { 18/01/2011, 23/01/2011, null, null }

// ...

public sealed class NullsLastComparer<T> : Comparer<T>
{
    private readonly IComparer<T> _comparer;

    public NullsLastComparer() : this(null) { }

    public NullsLastComparer(IComparer<T> comparer)
    {
        _comparer = comparer ?? Comparer<T>.Default;
    }

    public override int Compare(T x, T y)
    {
        if (x == null)
            return (y == null) ? 0 : 1;

        if (y == null)
            return -1;

        return _comparer.Compare(x, y);
    }
}
</code>```

Body:
I have a list of dates that I want to sort in an ascending order. However, the default comparer means that I have:

null
null
18/01/2011
23/01/2011

Can someone help with a IComparer that will mean that the dates sorted in ascending order will look like:

18/01/2011
23/01/2011
null
null

Body:
Here's a generic comparer that should work for pretty much any type:

var yourList = new List<DateTime?>
                   {
                       null, new DateTime(2011, 1, 23),
                       null, new DateTime(2011, 1, 18)
                   };

var comparer = new NullsLastComparer<DateTime?>();
yourList.Sort(comparer);  // now contains { 18/01/2011, 23/01/2011, null, null }

// ...

public sealed class NullsLastComparer<T> : Comparer<T>
{
    private readonly IComparer<T> _comparer;

    public NullsLastComparer() : this(null) { }

    public NullsLastComparer(IComparer<T> comparer)
    {
        _comparer = comparer ?? Comparer<T>.Default;
    }

    public override int Compare(T x, T y)
    {
        if (x == null)
            return (y == null) ? 0 : 1;

        if (y == null)
            return -1;

        return _comparer.Compare(x, y);
    }
}