问:
Is it good idea to write multi level inline functions in C++?
Is something like this code considered a bad practice?
If so, what should I do when func1 duplicates func2's behavior and I need both functions to be present (isn't that considered code redundancy)?!

UPD: Sorry for my bad illustration, I'll try to explain the question more clearly.
What i wanted to ask about is that:
I'm trying to design an optimized class that heavily calls two methods func1 and func2, func1's implementation uses func2 and i want the two methods calls to be inlined as much as possible, So is it better to call func2 from func1 like this code or to implement both independently.

```<code>inline int func2(int x) {
    return x * (x + 2);
}
inline int func1(int x) {
    return x * (x + 1) * func2(x + 2);
}
</code>```

答:
Writing several small functions is fine if it avoids writing the same code more than once. Some may argue that too many small functions makes code hard to read and that's a matter of opinion.

If you are worried about performance, the compiler will inline if it thinks it will help, you shouldn't worry about it until you've proven that there is a problem. See this question on premature optimization.

Body:
Is something like this code considered a bad practice?
If so, what should I do when func1 duplicates func2's behavior and I need both functions to be present (isn't that considered code redundancy)?!

UPD: Sorry for my bad illustration, I'll try to explain the question more clearly.
What i wanted to ask about is that:
I'm trying to design an optimized class that heavily calls two methods func1 and func2, func1's implementation uses func2 and i want the two methods calls to be inlined as much as possible, So is it better to call func2 from func1 like this code or to implement both independently.

inline int func2(int x) {
    return x * (x + 2);
}
inline int func1(int x) {
    return x * (x + 1) * func2(x + 2);
}


来源: stackexchange

问:
Choosing more than 1 element from the list
I am trying to make a choice for each element in elements, and then I am pairing up the element in elements list with its preferential choice(one,two or three). The choice is mostly done regarding the probabilities (weights) of the elements. The code until here:

```<code>from numpy.random import choice
elements = ['one', 'two', 'three']
weights = [0.2, 0.3, 0.5]
chosenones= []
for el in elements:
    chosenones.append(choice(elements,p=weights))
tuples = list(zip(elements,chosenones))
</code>```

Yields:

```<code>[('one', 'two'), ('two', 'two'), ('three', 'two')]
</code>```

What I need is, for each element to make two choices instead of one.

The expected output should look like:

```<code>[('one', 'two'), ('one', 'one'), ('two', 'two'),('two', 'three'), ('three', 'two'), ('three', 'one')]
</code>```

Do you know how to do have this output?

答:
If you accept duplicates, random.choices will do the job:

random.choices(population, weights=None, *, cum_weights=None, k=1)

Return a k sized list of elements chosen from the population with replacement. If the population is empty, raises IndexError.

If a weights sequence is specified, selections are made according to the relative weights.

```<code>>>> random.choices(['one', 'two', 'three'], weights=[0.2, 0.3, 0.5], k=2)
['one', 'three']
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to make a choice for each element in elements, and then I am pairing up the element in elements list with its preferential choice(one,two or three). The choice is mostly done regarding the probabilities (weights) of the elements. The code until here:

from numpy.random import choice
elements = ['one', 'two', 'three']
weights = [0.2, 0.3, 0.5]
chosenones= []
for el in elements:
    chosenones.append(choice(elements,p=weights))
tuples = list(zip(elements,chosenones))

Yields:

[('one', 'two'), ('two', 'two'), ('three', 'two')]

What I need is, for each element to make two choices instead of one.

The expected output should look like:

[('one', 'two'), ('one', 'one'), ('two', 'two'),('two', 'three'), ('three', 'two'), ('three', 'one')]

Do you know how to do have this output?

Body:
If you accept duplicates, random.choices will do the job:

random.choices(population, weights=None, *, cum_weights=None, k=1)

Return a k sized list of elements chosen from the population with replacement. If the population is empty, raises IndexError.

If a weights sequence is specified, selections are made according to the relative weights.

>>> random.choices(['one', 'two', 'three'], weights=[0.2, 0.3, 0.5], k=2)
['one', 'three']


问:
intellij GWT debug configuration
How can I override the default server intellij's GWT debug configuration ?
Intellij takes a Jetty as default server but I want it to use a jboss server.

I tried with the Jetty server, But I've got something like a authentication error ...

Does someone know either how to override the default server, or why I get this kind of error using Jetty ?

答:
I did not tested it with JBoss, but using a Tomcat as a server it works well:

compile your GWT project

create a new web application project and add the compiled GWT artefacts , the html and css files to that project

create a running configuration for Tomcat and add the newly created web project to that server and start it

create a GWT running configuration with the following Dev Mode parameters: -noserver -port 8080 (if you use Tomcat, for JBoss use the JBoss port for web application) and use as startpage: http://127.0.0.1:[WebApplicationPort]/[YourApplilcationHtml] (Depending on your application context in your Tomcat running configuration, the url can differ) and start it

This works for me.

Hope that helps.

Title: intellij GWT debug configuration


问:
Reactive Multi-level List in Shiny
I am trying to create a multi-level list in Shiny with the capability to add children to parents but I am unable to have it reactive. Is it possible to have a button in shiny to append a new item indexed by the next integer?

For example:

```<code> 1.
 1.1
 1.1.1
 1.2
</code>```

With the functionality to "add" a new item under 1.1 indexed 1.1.2 and likewise the capability of 1.2.1 under 1.2 as seen below:

```<code> 1.
 1.1
 1.1.1
 1.1.2
 1.2
 1.2.1
</code>```

I am trying to have it create a list and then have two action buttons to add/remove the list item in the list.

答:
You could store it in a reactiveValue() and make the selection via a selectInput() as discussed in the comments:

```<code>ui <- fluidPage(
  uiOutput("parent"),
  actionButton("add", "add"),
  actionButton("remove", "remove"),
  verbatimTextOutput("txt")
)
server <- function(input, output){
  global <- reactiveValues(lst = list(list(list(1),list(2), list(3))))

  output$parent <- renderUI({
    selectInput("par", "parent", 1:length(global$lst[[1]]))
  })

  observe({
    if(input$remove){
      isolate({
        lst <- global$lst[[1]]
        len <- as.numeric(input$par)
        lens <- lengths(lst)
        global$lst[[1]][[len]][[lens[len]]] <- NULL
      })
    }
  })

  observe({
    if(input$add){
      isolate({
        lst <- global$lst[[1]]
        len <- as.numeric(input$par)
        lens <- lengths(lst)
        global$lst[[1]][[len]][[lens[len] + 1]] <- "i am the new guy"
      })
    }
  })

  output$txt <- renderPrint({
    str(global$lst)
  })
}
shinyApp(ui, server)
</code>```

Title: Reactive Multi-level List in Shiny

Body:
I am trying to create a multi-level list in Shiny with the capability to add children to parents but I am unable to have it reactive. Is it possible to have a button in shiny to append a new item indexed by the next integer?

For example:

 1.
 1.1
 1.1.1
 1.2

With the functionality to "add" a new item under 1.1 indexed 1.1.2 and likewise the capability of 1.2.1 under 1.2 as seen below:

 1.
 1.1
 1.1.1
 1.1.2
 1.2
 1.2.1

I am trying to have it create a list and then have two action buttons to add/remove the list item in the list.

Body:
You could store it in a reactiveValue() and make the selection via a selectInput() as discussed in the comments:

ui <- fluidPage(
  uiOutput("parent"),
  actionButton("add", "add"),
  actionButton("remove", "remove"),
  verbatimTextOutput("txt")
)
server <- function(input, output){
  global <- reactiveValues(lst = list(list(list(1),list(2), list(3))))

  output$parent <- renderUI({
    selectInput("par", "parent", 1:length(global$lst[[1]]))
  })

  observe({
    if(input$remove){
      isolate({
        lst <- global$lst[[1]]
        len <- as.numeric(input$par)
        lens <- lengths(lst)
        global$lst[[1]][[len]][[lens[len]]] <- NULL
      })
    }
  })

  observe({
    if(input$add){
      isolate({
        lst <- global$lst[[1]]
        len <- as.numeric(input$par)
        lens <- lengths(lst)
        global$lst[[1]][[len]][[lens[len] + 1]] <- "i am the new guy"
      })
    }
  })

  output$txt <- renderPrint({
    str(global$lst)
  })
}
shinyApp(ui, server)


问:
How to get the last 50 element from Firebase in a ListView?
I made a ListView for my chat application. I'm using Firebase but I have a problem:

It shows every data from the server which slows the loading time drastically.

I would like to make a Query which only shows the last 10-30 or 50 element from the list, but I don't know how to develop it and didn't find enough good answer for me in the Query Api Reference. It would be better if I could dynamically adjust the number like every other chat app (Viber, Messenger) if I scroll up.
So here is my display implementation:

```<code>private void displayChatMessages() {
    listOfMessages = (ListView) findViewById(R.id.list_of_messages);

    adapter = new FirebaseListAdapter<ChatMessage>(this, ChatMessage.class,
            R.layout.message, FirebaseDatabase.getInstance().getReference()) {
        @Override
        protected void populateView(View v, ChatMessage model, int position) {
            // Get references to the views of message.xml
            TextView messageText = (TextView) v.findViewById(R.id.message_text);
            TextView messageUser = (TextView) v.findViewById(R.id.message_user);
            TextView messageTime = (TextView) v.findViewById(R.id.message_time);

            // Set their text
            messageText.setText(model.getMessageText());
            messageUser.setText(model.getMessageUser());

            // Format the date before showing it
            messageTime.setText(DateFormat.format("yyyy-MM-dd (HH:mm:ss)",
                    model.getMessageTime()));
        }
    };

    listOfMessages.setAdapter(adapter);
    listOfMessages.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
}
</code>```

答:
Here is something from Firebase Documentation

```<code>// Last 100 posts, these are automatically the 100 most recent
// due to sorting by push() keys
Query recentPostsQuery = databaseReference.child("posts")
        .limitToFirst(100);
</code>```

https://firebase.google.com/docs/database/android/lists-of-data#filtering_data

Body:
I made a ListView for my chat application. I'm using Firebase but I have a problem:

It shows every data from the server which slows the loading time drastically.

I would like to make a Query which only shows the last 10-30 or 50 element from the list, but I don't know how to develop it and didn't find enough good answer for me in the Query Api Reference. It would be better if I could dynamically adjust the number like every other chat app (Viber, Messenger) if I scroll up.
So here is my display implementation:

private void displayChatMessages() {
    listOfMessages = (ListView) findViewById(R.id.list_of_messages);

    adapter = new FirebaseListAdapter<ChatMessage>(this, ChatMessage.class,
            R.layout.message, FirebaseDatabase.getInstance().getReference()) {
        @Override
        protected void populateView(View v, ChatMessage model, int position) {
            // Get references to the views of message.xml
            TextView messageText = (TextView) v.findViewById(R.id.message_text);
            TextView messageUser = (TextView) v.findViewById(R.id.message_user);
            TextView messageTime = (TextView) v.findViewById(R.id.message_time);

            // Set their text
            messageText.setText(model.getMessageText());
            messageUser.setText(model.getMessageUser());

            // Format the date before showing it
            messageTime.setText(DateFormat.format("yyyy-MM-dd (HH:mm:ss)",
                    model.getMessageTime()));
        }
    };

    listOfMessages.setAdapter(adapter);
    listOfMessages.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
}

Body:
Here is something from Firebase Documentation

// Last 100 posts, these are automatically the 100 most recent
// due to sorting by push() keys
Query recentPostsQuery = databaseReference.child("posts")
        .limitToFirst(100);

https://firebase.google.com/docs/database/android/lists-of-data#filtering_data


问:
Can't understand the logic of a JavaScript code block [Bulls and Cows game]
I'm in need of a little help. I need to write a detailed interpretation of a JavaScript code for a game of Bulls and Cows and I don't understand exactly what's happening in the main logic block. This is the block:

```<code>        //Check Bull,Cow,Try Again
    var bull, cow;

    if (check) {
        bull = 0;
        cow = 0;

        for (var i = 0; i < getNum.length; i++) {
            for (var k = 0; k < userText.length; k++) {
                if ((getNum[i] == userText[k]) && (i == k)) {
                    bull++;
                } else if ((getNum[i] == userText[k]) && (i != k)) {
                    cow++;
                }
            }
        }

        if (bull == 0 && cow == 0) {
            setText.innerHTML += "try again\n";
        } else if (bull == numLength) {
            setText.innerHTML += numLength + " bulls! you won the game!!!\nclick restart to play again\n";
        } else {
            setText.innerHTML += userText + " : ";
            setText.innerHTML += (bull + " bull(s), " + cow + " cow(s)!\n");
        }
    }
    check = true;

}
</code>```

Also here's the entire program in case you need to check the interconnection of variables and such:

```<code>var getNum = new Array();
var numLength;
var check = true;

window.onload = function() {
    numLength = document.getElementById("select").value;
    setNumber();
}

/*Get random numbers
Numbers must not be the same as each other
(found this entire codeblock on the internet
and adapted it, not gonna lie)*/
function setNumber() {
    var random;
    getNum.splice(0, getNum.length);
    while (getNum.length < numLength) {
        random = Math.floor(Math.random() * 9) + 1;

        for (var i = 0; i < getNum.length; i++) {
            if (getNum[i] == random) {
                check = false;
                break;
            }
        }

        if (check) {
            getNum.push(random);
        }
        check = true;
    }
}

//Check user number
function checkUserText() {
    var userText = document.getElementById("userText").value;
    var setText = document.getElementById("textArea");
    //Check if userText is number
    for (var i = 0; i < userText.length; i++) {
        if (userText.charCodeAt(i) < 48 || userText.charCodeAt(i) > 57
                || userText.length != numLength) {
            setText.innerHTML += "Type only" + numLength + " numbers!\n";
            check = false;
            break;
        }
    }

    //Check Bull,Cow,Try Again
    var bull, cow;

    if (check) {
        bull = 0;
        cow = 0;

        for (var i = 0; i < getNum.length; i++) {
            for (var k = 0; k < userText.length; k++) {
                if ((getNum[i] == userText[k]) && (i == k)) {
                    bull++;
                } else if ((getNum[i] == userText[k]) && (i != k)) {
                    cow++;
                }
            }
        }

        if (bull == 0 && cow == 0) {
            setText.innerHTML += "try again\n";
        } else if (bull == numLength) {
            setText.innerHTML += numLength + " bulls! you won the game!!!\nclick restart to play again\n";
        } else {
            setText.innerHTML += userText + " : ";
            setText.innerHTML += (bull + " bull(s), " + cow + " cow(s)!\n");
        }
    }
    check = true;

}

//change difficulty
function difficulty() {
    numLength = document.getElementById("select").value;
    reload();
}

//restart game
function reload() {
    setNumber();
    document.getElementById("textArea").innerHTML = "";
}
</code>```

I understand the general idea of the block but I can't see the specifics, I can't see the logic behind it, if someone could explain this block to me or make a quick flow chart I would be more than grateful.

 var getNum = new Array();
 var numLength;
 var check = true;

 window.onload = function() {
  numLength = document.getElementById("select").value;
  setNumber();
 }

 /*Get random numbers
 Numbers must not be the same as each other
 (found this entire codeblock on the internet
 and adapted it, not gonna lie)*/
 function setNumber() {
  var random;
  getNum.splice(0, getNum.length);
  while (getNum.length < numLength) {
   random = Math.floor(Math.random() * 9) + 1;

   for (var i = 0; i < getNum.length; i++) {
    if (getNum[i] == random) {
     check = false;
     break;
    }
   }

   if (check) {
    getNum.push(random);
   }
   check = true;
  }
 }

 //Check user number
 function checkUserText() {
  var userText = document.getElementById("userText").value;
  var setText = document.getElementById("textArea");
  //Check if userText is number
  for (var i = 0; i < userText.length; i++) {
   if (userText.charCodeAt(i) < 48 || userText.charCodeAt(i) > 57
     || userText.length != numLength) {
    setText.innerHTML += "Type only" + numLength + " numbers!\n";
    check = false;
    break;
   }
  }

  //Check Bull,Cow,Try Again
  var bull, cow;

  if (check) {
   bull = 0;
   cow = 0;

   for (var i = 0; i < getNum.length; i++) {
    for (var k = 0; k < userText.length; k++) {
     if ((getNum[i] == userText[k]) && (i == k)) {
      bull++;
     } else if ((getNum[i] == userText[k]) && (i != k)) {
      cow++;
     }
    }
   }

   if (bull == 0 && cow == 0) {
    setText.innerHTML += "try again\n";
   } else if (bull == numLength) {
    setText.innerHTML += numLength + " bulls! you won the game!!!\nclick restart to play again\n";
   } else {
    setText.innerHTML += userText + " : ";
    setText.innerHTML += (bull + " bull(s), " + cow + " cow(s)!\n");
   }
  }
  check = true;

 }

 //change difficulty
 function difficulty() {
  numLength = document.getElementById("select").value;
  reload();
 }

 //restart game
 function reload() {
  setNumber();
  document.getElementById("textArea").innerHTML = "";
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
 <head>
  <title>Bulls and Cows</title>

  <script type="text/javascript" src="operation.js">

     </script>

  <link href="https://fonts.googleapis.com/css?family=Lobster" rel="stylesheet" type="text/css">

  <style>
     h2 {
    font-family: Lobster;
    color: blue;
    }
   body {
    background-color: #cccccc
    }
  </style>

 </head>
 <body>
  <h2>Bulls and Cows</h2>
  <label for="userText">Type here: </label>
  <input type="text" id="userText"/>
  <br />
  <button id="ch" onclick="checkUserText()">check</button>
  <button id="re" onclick="reload()">restart</button>
  Length : <select id="select" onchange="difficulty()">
   <option>3</option>
   <option>4</option>
   <option>5</option>
   <option>6</option>
   <option>7</option>
   <option>8</option>
   <option>9</option>
   <option>10</option>
  </select>
  <br />
  <textarea id="textArea" rows="20" cols="30" readonly="readonly" style="overflow-y: scroll"></textarea>
 </body>
</html></code>```

答:
```<code>// ok lets assume the getNum.length is 3
// and the random getNum is 123
// and user enters 321 and clicks check

var bull, cow;

if (check) {
    bull = 0;
    cow = 0;

    for (var i = 0; i < getNum.length; i++) {
      // this will loop three times
      // in the first iteration getNum[i] == 1
      // the second iteration getNum[i] == 2
      // the third iteration getNum[i] == 3

        for (var k = 0; k < userText.length; k++) {

          // for each iteration of getNum it will iterate all user input (also 3 times)
          // so 3 times per iteration of getNum, clear so far? good
          // so at first iteration userText[k] == 3
          // so at second iteration userText[k] == 2
          // so at third iteration userText[k] == 1
          // while i keeps the value of the outer loop

            // this expression checks if user input matches the same number on the same position in getNum
            if ((getNum[i] == userText[k]) && (i == k)) {
                // in the second iteration of the outer loop its a bull because
                // getNum[i] == 2 == userText[k] == 2 AND 1 == 1 (number and position of number/index is matching the random number
                bull++;
            } else if ((getNum[i] == userText[k]) && (i != k)) {
                // in the first and last iteration of the outer loop its a cow because
                // getNum[i] == 1/2 == userText[k] == 1/2 AND 0/2 is NOT 2/0 (number is matching but position not matching)
                cow++;
            }

            // if the getNum[i] doesnt exist at all in userText, neither cow or bull will count up
        }
    }

    if (bull == 0 && cow == 0) {
        // so if no number matched - try again
        setText.innerHTML += "try again\n";
    } else if (bull == numLength) {
        // if all numbers and positions (cow) matched you won
        setText.innerHTML += numLength + " bulls! you won the game!!!\nclick restart to play again\n";
    } else {
        // else show how many "cows" and "bulls"
        setText.innerHTML += userText + " : ";
        setText.innerHTML += (bull + " bull(s), " + cow + " cow(s)!\n");
    }

    // so the output of above assumption would be
    // 1 bull, 2 cows
    // cool game ;-)
}
</code>```

Body:
I'm in need of a little help. I need to write a detailed interpretation of a JavaScript code for a game of Bulls and Cows and I don't understand exactly what's happening in the main logic block. This is the block:

        //Check Bull,Cow,Try Again
    var bull, cow;

    if (check) {
        bull = 0;
        cow = 0;

        for (var i = 0; i < getNum.length; i++) {
            for (var k = 0; k < userText.length; k++) {
                if ((getNum[i] == userText[k]) && (i == k)) {
                    bull++;
                } else if ((getNum[i] == userText[k]) && (i != k)) {
                    cow++;
                }
            }
        }

        if (bull == 0 && cow == 0) {
            setText.innerHTML += "try again\n";
        } else if (bull == numLength) {
            setText.innerHTML += numLength + " bulls! you won the game!!!\nclick restart to play again\n";
        } else {
            setText.innerHTML += userText + " : ";
            setText.innerHTML += (bull + " bull(s), " + cow + " cow(s)!\n");
        }
    }
    check = true;

}

Also here's the entire program in case you need to check the interconnection of variables and such:

var getNum = new Array();
var numLength;
var check = true;

window.onload = function() {
    numLength = document.getElementById("select").value;
    setNumber();
}

/*Get random numbers
Numbers must not be the same as each other
(found this entire codeblock on the internet
and adapted it, not gonna lie)*/
function setNumber() {
    var random;
    getNum.splice(0, getNum.length);
    while (getNum.length < numLength) {
        random = Math.floor(Math.random() * 9) + 1;

        for (var i = 0; i < getNum.length; i++) {
            if (getNum[i] == random) {
                check = false;
                break;
            }
        }

        if (check) {
            getNum.push(random);
        }
        check = true;
    }
}

//Check user number
function checkUserText() {
    var userText = document.getElementById("userText").value;
    var setText = document.getElementById("textArea");
    //Check if userText is number
    for (var i = 0; i < userText.length; i++) {
        if (userText.charCodeAt(i) < 48 || userText.charCodeAt(i) > 57
                || userText.length != numLength) {
            setText.innerHTML += "Type only" + numLength + " numbers!\n";
            check = false;
            break;
        }
    }

    //Check Bull,Cow,Try Again
    var bull, cow;

    if (check) {
        bull = 0;
        cow = 0;

        for (var i = 0; i < getNum.length; i++) {
            for (var k = 0; k < userText.length; k++) {
                if ((getNum[i] == userText[k]) && (i == k)) {
                    bull++;
                } else if ((getNum[i] == userText[k]) && (i != k)) {
                    cow++;
                }
            }
        }

        if (bull == 0 && cow == 0) {
            setText.innerHTML += "try again\n";
        } else if (bull == numLength) {
            setText.innerHTML += numLength + " bulls! you won the game!!!\nclick restart to play again\n";
        } else {
            setText.innerHTML += userText + " : ";
            setText.innerHTML += (bull + " bull(s), " + cow + " cow(s)!\n");
        }
    }
    check = true;

}

//change difficulty
function difficulty() {
    numLength = document.getElementById("select").value;
    reload();
}

//restart game
function reload() {
    setNumber();
    document.getElementById("textArea").innerHTML = "";
}

I understand the general idea of the block but I can't see the specifics, I can't see the logic behind it, if someone could explain this block to me or make a quick flow chart I would be more than grateful.

 var getNum = new Array();
 var numLength;
 var check = true;

 window.onload = function() {
  numLength = document.getElementById("select").value;
  setNumber();
 }

 /*Get random numbers
 Numbers must not be the same as each other
 (found this entire codeblock on the internet
 and adapted it, not gonna lie)*/
 function setNumber() {
  var random;
  getNum.splice(0, getNum.length);
  while (getNum.length < numLength) {
   random = Math.floor(Math.random() * 9) + 1;

   for (var i = 0; i < getNum.length; i++) {
    if (getNum[i] == random) {
     check = false;
     break;
    }
   }

   if (check) {
    getNum.push(random);
   }
   check = true;
  }
 }

 //Check user number
 function checkUserText() {
  var userText = document.getElementById("userText").value;
  var setText = document.getElementById("textArea");
  //Check if userText is number
  for (var i = 0; i < userText.length; i++) {
   if (userText.charCodeAt(i) < 48 || userText.charCodeAt(i) > 57
     || userText.length != numLength) {
    setText.innerHTML += "Type only" + numLength + " numbers!\n";
    check = false;
    break;
   }
  }

  //Check Bull,Cow,Try Again
  var bull, cow;

  if (check) {
   bull = 0;
   cow = 0;

   for (var i = 0; i < getNum.length; i++) {
    for (var k = 0; k < userText.length; k++) {
     if ((getNum[i] == userText[k]) && (i == k)) {
      bull++;
     } else if ((getNum[i] == userText[k]) && (i != k)) {
      cow++;
     }
    }
   }

   if (bull == 0 && cow == 0) {
    setText.innerHTML += "try again\n";
   } else if (bull == numLength) {
    setText.innerHTML += numLength + " bulls! you won the game!!!\nclick restart to play again\n";
   } else {
    setText.innerHTML += userText + " : ";
    setText.innerHTML += (bull + " bull(s), " + cow + " cow(s)!\n");
   }
  }
  check = true;

 }

 //change difficulty
 function difficulty() {
  numLength = document.getElementById("select").value;
  reload();
 }

 //restart game
 function reload() {
  setNumber();
  document.getElementById("textArea").innerHTML = "";
 }

<!DOCTYPE html>

  <title>Bulls and Cows</title>

  <link href="https://fonts.googleapis.com/css?family=Lobster" rel="stylesheet" type="text/css">

Bulls and Cows

  Type here:
  <input type="text" id="userText"/>

  <button id="ch" onclick="checkUserText()">check</button>
  <button id="re" onclick="reload()">restart</button>
  Length : <select id="select" onchange="difficulty()">
   <option>3</option>
   <option>4</option>
   <option>5</option>
   <option>6</option>
   <option>7</option>
   <option>8</option>
   <option>9</option>
   <option>10</option>
  </select>

  <textarea id="textArea" rows="20" cols="30" readonly="readonly" style="overflow-y: scroll"></textarea>


问:
How to get Javascript variable value into CSS?
How can I have the time variable's contents displayed as the content property in my CSS?

JavaScript:

function clock(){
    var d = new Date();
    var hour = d.getHours();
    var min = d.getMinutes();
    var time = hour + ":" + min;
}
```

<p>CSS:</p>

<pre class="lang-css prettyprint-override"><code>.screen{
    position: absolute;
    height: 75%;
    width: 75%;
    background: #98E8EE;
    top: 11.5%;
    left: 12.5%;
}

.screen::after{
    color: #F9F5F4;
    font-size: 40px;
    content: ;
    font-family: Arial;
    margin-left: 36.5px;
    top: 20px;
    position: relative
}
</code>```

答:
Instead of adding a javascript value to your CSS (impossible), you can change your CSS value with javascript.

For example, you can use jQuery library and do changes in your html or CSS, according to the value.

Body:
How can I have the time variable's contents displayed as the content property in my CSS?

JavaScript:

function clock(){
    var d = new Date();
    var hour = d.getHours();
    var min = d.getMinutes();
    var time = hour + ":" + min;
}

CSS:

.screen{
    position: absolute;
    height: 75%;
    width: 75%;
    background: #98E8EE;
    top: 11.5%;
    left: 12.5%;
}

.screen::after{
    color: #F9F5F4;
    font-size: 40px;
    content: ;
    font-family: Arial;
    margin-left: 36.5px;
    top: 20px;
    position: relative
}


问:
Real-time speech recognition from a phone call recorded with Twillio
I'm currently using Twilio to make phone calls and I'd like to add a speech recognition element such that if a user says a specific phrase, my backend can take specific actions. If you're familiar with Twilio, something akin to the Gather verb. It needs to be real-time since if there are issues with recognition, the user would be prompted for clarification.</p>

答:
To add speech recognition to the Twilio Gather verb, add "speech" to the Gather input value, example: input="dtmf speech". After the caller says something and is quiet, the Twilio server translates the speech in text and sends the text to the action URL, then waits for response instructions. Your program can use the text to respond how ever you choose. One choice is to have your program respond with correction instructions (Say verb) and have the caller say something more, which would be processed again by your action URL.

Twilio Gather documentation including the implementation of speech recognition:
https://www.twilio.com/docs/api/twiml/gather

Example TwiML with a Gather verb using the speech recognition identifier.

```<code><?xml version="1.0" encoding="UTF-8"?>
<Response>
    <Gather input="dtmf speech" language="en-us"
          numDigits="1"
          timeout="6"
          action="http://hostname/processUserResponse.py">
        <Say voice="alice" language="en-CA">
            Okay, speech recognition test. Enter any digit or say something.
        </Say>
    </Gather>
    <Say voice="alice" language="en-CA">
        Waited to long to say something. Response canceled ....
    </Say>
</Response>
</code>```

Body:
To add speech recognition to the Twilio Gather verb, add "speech" to the Gather input value, example: input="dtmf speech". After the caller says something and is quiet, the Twilio server translates the speech in text and sends the text to the action URL, then waits for response instructions. Your program can use the text to respond how ever you choose. One choice is to have your program respond with correction instructions (Say verb) and have the caller say something more, which would be processed again by your action URL.

Twilio Gather documentation including the implementation of speech recognition:
https://www.twilio.com/docs/api/twiml/gather

Example TwiML with a Gather verb using the speech recognition identifier.

<?xml version="1.0" encoding="UTF-8"?>
<Response>
    <Gather input="dtmf speech" language="en-us"
          numDigits="1"
          timeout="6"
          action="http://hostname/processUserResponse.py">
        <Say voice="alice" language="en-CA">
            Okay, speech recognition test. Enter any digit or say something.
        </Say>
    </Gather>
    <Say voice="alice" language="en-CA">
        Waited to long to say something. Response canceled ....
    </Say>
</Response>


问:
How to include greek letters and bold characters in a legend using plotly?
I am trying to make a graph with greek letters in the legend and bold characters in the legend of the x-axis. This works fine with ggplot:

```<code>library(ggplot2)
library(plotly)
## Dataframe
df <- data.frame(dose=c("D0.5", "D1", "D2"),len=c(4.2, 10, 29.5))

## Legend with the greek letter pi
my.labs <- list(bquote(Pi==.(5)) )

## Plot with ggplot
p=ggplot(data=df, aes(x=dose, y=len, group=1,colour = paste("Pi = ",5,sep=""))) +
geom_line()+
geom_point()+
scale_colour_manual(values=3, labels=my.labs)+
theme(legend.title=element_blank(), legend.position = c(.1, .9),axis.title.x = element_text(face="bold", colour="black", size=10))

p
</code>```

However the greek letter and the bold legend for the x-axis disappear when using plotly:

```<code>p=plotly_build(p)
style( p, hoverinfo = "x+y" ) %>%
layout( legend = list(x = 0.1, y = 0.9, font=list(size=12)) )
</code>```

答:
You would need two small changes to get pretty close to your ggplot graph.

Set the xaxis title to bold manually

```<code>layout(legend = list(x = 0.1,
                     y = 0.9,
                   font=list(size=12)),
       xaxis = list(title = "<b>dose</b>")
)
</code>```

Use the HTML code for pi in ggplot (works with RStudio in Windows) or add π (works with RStudio in Ubuntu).

```<code>colour = paste("π = ",5,sep="")
</code>```

or

```<code>colour = paste("π = ",5,sep="")
</code>```

```<code>library(ggplot2)
library(plotly)
## Dataframe
df <- data.frame(dose=c("D0.5", "D1", "D2"),len=c(4.2, 10, 29.5))

## Legend with the greek letter pi
my.labs <- list(bquote(Pi==.(5)) )

## Plot with ggplot
p=ggplot(data=df, aes(x=dose, y=len, group=1,colour = paste("π = ",5,sep=""))) +
  geom_line()+
  geom_point()+
  scale_colour_manual(values=3, labels=my.labs)+
  theme(legend.title=element_blank(), legend.position = c(.1, .9),axis.title.x = element_text(face="bold", colour="black", size=10))
p
p=plotly_build(p)
p <- style(p, hoverinfo = "x+y" ) %>%
  layout(legend = list(x = 0.1,
                       y = 0.9,
                       font=list(size=12)),
         xaxis = list(title = "<b>dose</b>")
  )

p
</code>```

Body:
I am trying to make a graph with greek letters in the legend and bold characters in the legend of the x-axis. This works fine with ggplot:

library(ggplot2)
library(plotly)
## Dataframe
df <- data.frame(dose=c("D0.5", "D1", "D2"),len=c(4.2, 10, 29.5))

## Legend with the greek letter pi
my.labs <- list(bquote(Pi==.(5)) )

## Plot with ggplot
p=ggplot(data=df, aes(x=dose, y=len, group=1,colour = paste("Pi = ",5,sep=""))) +
geom_line()+
geom_point()+
scale_colour_manual(values=3, labels=my.labs)+
theme(legend.title=element_blank(), legend.position = c(.1, .9),axis.title.x = element_text(face="bold", colour="black", size=10))

p

However the greek letter and the bold legend for the x-axis disappear when using plotly:

p=plotly_build(p)
style( p, hoverinfo = "x+y" ) %>%
layout( legend = list(x = 0.1, y = 0.9, font=list(size=12)) )

Body:
You would need two small changes to get pretty close to your ggplot graph.

Set the xaxis title to bold manually

layout(legend = list(x = 0.1,
                     y = 0.9,
                   font=list(size=12)),
       xaxis = list(title = "<b>dose</b>")
)

Use the HTML code for pi in ggplot (works with RStudio in Windows) or add π (works with RStudio in Ubuntu).

colour = paste("&pi; = ",5,sep="")

or

colour = paste("π = ",5,sep="")

library(ggplot2)
library(plotly)
## Dataframe
df <- data.frame(dose=c("D0.5", "D1", "D2"),len=c(4.2, 10, 29.5))

## Legend with the greek letter pi
my.labs <- list(bquote(Pi==.(5)) )

## Plot with ggplot
p=ggplot(data=df, aes(x=dose, y=len, group=1,colour = paste("&pi; = ",5,sep=""))) +
  geom_line()+
  geom_point()+
  scale_colour_manual(values=3, labels=my.labs)+
  theme(legend.title=element_blank(), legend.position = c(.1, .9),axis.title.x = element_text(face="bold", colour="black", size=10))
p
p=plotly_build(p)
p <- style(p, hoverinfo = "x+y" ) %>%
  layout(legend = list(x = 0.1,
                       y = 0.9,
                       font=list(size=12)),
         xaxis = list(title = "<b>dose</b>")
  )

p


问:
How to do SNS Push Notification? CreatePlatformEndpointResult returns null
I have followed a tutorial on how to setup SNS Push notification but the CreatePlatformEndpointResult object returns null. I need that so that I can retrieve the endpointArn and send that to the backend. Below is my entire setup. And here is the link to the tutorial: http://www.allcode.com/amazon-sns-push-notification-tutorial-android-using-gcm/

First I retrieve a token from GCM by calling

AWSManager.registerAppToGCM(getApplicationContext())

This is from my AWSManager class

```<code>public class AWSManager {
    private static final String TAG = AWSManager.class.getSimpleName();
    private static final String SNS_ACCESS_KEY_ID = "1234567890"; // I have swapped out the real key
    private static final String SNS_SECRET_KEY = "1234567890"; // I have swapped out the real key

    private static AmazonSNSClient snsClient;

    /**
     * Method is used to retrieve SNSClient object
     *
     * @return snsClient object
     */
    public static AmazonSNSClient getSNSClient() {
        if (FrameworkUtils.checkIfNull(snsClient)) {
            snsClient = new AmazonSNSClient(new BasicAWSCredentials(SNS_ACCESS_KEY_ID, SNS_SECRET_KEY));
            snsClient.setRegion(Region.getRegion(Regions.US_WEST_1));
        }
        return snsClient;
    }

    /**
     * Method is used to register app to GCM
     *
     * @param context
     */
    public static void registerAppToGCM(Context context) {
        SharedPref sharedPref = new SharedPref(context, Constants.PREF_FILE_NAME);
        String gcmToken = sharedPref.getStringPref(Constants.NOTIFICATION_GCM_TOKEN, "");
        if (FrameworkUtils.isStringEmpty(gcmToken)) {
            new GCMRegisterTask(context).execute();
        }
    }
}
</code>```

Here is the class performing the background task

```<code>public class GCMRegisterTask extends AsyncTask<String, Void, Boolean> {
    private static final String TAG = GCMRegisterTask.class.getSimpleName();

    private Context mContext;

    /**
     * Constructor
     *
     * @param context
     */
    public GCMRegisterTask(Context context) {
        super();
        mContext = context;
    }

    @Override
    protected Boolean doInBackground(String... params) {
        String token;
        try {
            token = InstanceID.getInstance(mContext).getToken(mContext.getString(R.string.gcm_project_id), GoogleCloudMessaging.INSTANCE_ID_SCOPE);
            SharedPref sharedPref = new SharedPref(mContext, Constants.PREF_FILE_NAME);
            sharedPref.setPref(Constants.NOTIFICATION_GCM_TOKEN, token);
            Logger.i(TAG, "GCM token successfully stored to prefs: " + token);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }
}
</code>```

Once I have successfully retrieved the GCM token. I use new

AWSCreateEndpointTask(mContext).execute(test, token,
  "email@gmail.com")

to begin the process of creating the endpoint ARN. test = "arn:aws:sns:region:us-east-1:app/GCM/AppName"

```<code>public class AWSCreateEndpointTask extends AsyncTask<String, Void, CreatePlatformEndpointResult> {

    Context mContext;

    /**
     * Constructor
     *
     * @param context
     */
    public AWSCreateEndpointTask(Context context) {
        super();
        mContext = context;
    }

    @Override
    protected CreatePlatformEndpointResult doInBackground(String[] params) {
        if (params.length < 3) {
            return null;
        }

        String arn = params[0];
        String gcmToken = params[1];
        String userData = params[2];

        try {
            CreatePlatformEndpointRequest request = new CreatePlatformEndpointRequest();
            request.setCustomUserData(userData);
            request.setToken(gcmToken);
            request.setPlatformApplicationArn(arn);
            return AWSManager.getSNSClient().createPlatformEndpoint(request);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    protected void onPostExecute(CreatePlatformEndpointResult result) {
        if (!FrameworkUtils.checkIfNull(result)) {
            String endpointArn = result.getEndpointArn();
            SharedPref sharedPref = new SharedPref(mContext, Constants.PREF_FILE_NAME);
            sharedPref.setPref(Constants.NOTIFICATION_ENDPOINT_ARN, endpointArn);
        }
    }
</code>```

Inside of onPostExecute, the returned CreatePlatformEndpointResult object is null. What am I missing or doing incorrectly to cause this?

答:
It turns out that the implementation is correct, the arn value was wrong. For others running into this conflict, make sure the information is correct when trying to get the endpointARN. I updated mine to

arn:aws:sns:us-east-1::app/GCM/

This comes from the developer console.

Body:
I have followed a tutorial on how to setup SNS Push notification but the CreatePlatformEndpointResult object returns null. I need that so that I can retrieve the endpointArn and send that to the backend. Below is my entire setup. And here is the link to the tutorial: http://www.allcode.com/amazon-sns-push-notification-tutorial-android-using-gcm/

First I retrieve a token from GCM by calling

AWSManager.registerAppToGCM(getApplicationContext())

This is from my AWSManager class

public class AWSManager {
    private static final String TAG = AWSManager.class.getSimpleName();
    private static final String SNS_ACCESS_KEY_ID = "1234567890"; // I have swapped out the real key
    private static final String SNS_SECRET_KEY = "1234567890"; // I have swapped out the real key

    private static AmazonSNSClient snsClient;

    /**
     * Method is used to retrieve SNSClient object
     *
     * @return snsClient object
     */
    public static AmazonSNSClient getSNSClient() {
        if (FrameworkUtils.checkIfNull(snsClient)) {
            snsClient = new AmazonSNSClient(new BasicAWSCredentials(SNS_ACCESS_KEY_ID, SNS_SECRET_KEY));
            snsClient.setRegion(Region.getRegion(Regions.US_WEST_1));
        }
        return snsClient;
    }

    /**
     * Method is used to register app to GCM
     *
     * @param context
     */
    public static void registerAppToGCM(Context context) {
        SharedPref sharedPref = new SharedPref(context, Constants.PREF_FILE_NAME);
        String gcmToken = sharedPref.getStringPref(Constants.NOTIFICATION_GCM_TOKEN, "");
        if (FrameworkUtils.isStringEmpty(gcmToken)) {
            new GCMRegisterTask(context).execute();
        }
    }
}

Here is the class performing the background task

public class GCMRegisterTask extends AsyncTask<String, Void, Boolean> {
    private static final String TAG = GCMRegisterTask.class.getSimpleName();

    private Context mContext;

    /**
     * Constructor
     *
     * @param context
     */
    public GCMRegisterTask(Context context) {
        super();
        mContext = context;
    }

    @Override
    protected Boolean doInBackground(String... params) {
        String token;
        try {
            token = InstanceID.getInstance(mContext).getToken(mContext.getString(R.string.gcm_project_id), GoogleCloudMessaging.INSTANCE_ID_SCOPE);
            SharedPref sharedPref = new SharedPref(mContext, Constants.PREF_FILE_NAME);
            sharedPref.setPref(Constants.NOTIFICATION_GCM_TOKEN, token);
            Logger.i(TAG, "GCM token successfully stored to prefs: " + token);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }
}

Once I have successfully retrieved the GCM token. I use new

AWSCreateEndpointTask(mContext).execute(test, token,
  "email@gmail.com")

to begin the process of creating the endpoint ARN. test = "arn:aws:sns:region:us-east-1:app/GCM/AppName"

public class AWSCreateEndpointTask extends AsyncTask<String, Void, CreatePlatformEndpointResult> {

    Context mContext;

    /**
     * Constructor
     *
     * @param context
     */
    public AWSCreateEndpointTask(Context context) {
        super();
        mContext = context;
    }

    @Override
    protected CreatePlatformEndpointResult doInBackground(String[] params) {
        if (params.length < 3) {
            return null;
        }

        String arn = params[0];
        String gcmToken = params[1];
        String userData = params[2];

        try {
            CreatePlatformEndpointRequest request = new CreatePlatformEndpointRequest();
            request.setCustomUserData(userData);
            request.setToken(gcmToken);
            request.setPlatformApplicationArn(arn);
            return AWSManager.getSNSClient().createPlatformEndpoint(request);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    protected void onPostExecute(CreatePlatformEndpointResult result) {
        if (!FrameworkUtils.checkIfNull(result)) {
            String endpointArn = result.getEndpointArn();
            SharedPref sharedPref = new SharedPref(mContext, Constants.PREF_FILE_NAME);
            sharedPref.setPref(Constants.NOTIFICATION_ENDPOINT_ARN, endpointArn);
        }
    }

Inside of onPostExecute, the returned CreatePlatformEndpointResult object is null. What am I missing or doing incorrectly to cause this?


问:
How does the browser render Images with different sizes ( tag in HTML)?
If an HTML document has three images in different sizes (5MB, 50KB and 10MB) then which image will be rendered first in the page? Does the browser process  tags synchronously? That is, will the render sequence  be

5_mb_img.jpg > 50_kb_img.jpg > 10_mb_img.jpg

OR

might 50_kb_img.jpg be rendered first because  it is smallest in size?

```<code><img src="5_mb_img.jpg" /> <!-- a 5MB image file -->
<img src="50_kb_img.jpg" /> <!-- a 50KB image file -->
<img src="10_mb_img.jpg" /> <!-- a 10MB image file -->
</code>```

WHY A BOUNTY? I know the answer but am expecting a very good explanation that helps someone who is searching it in Stack Overflow

答:
There are many factors to depend on.

Normally, the smallest will render first and the largest will render last.

Asynchronized Requests: meaning you don't know which request happen first. When you have a huge HTML page, the first  the browser sees will be requested first, while the last one will be requested last. But which request will get response first depend on other factors.

Server Response Time:  and  are at different servers, one server could be really fast responding, while another could be really slow.

Image Size: File size makes a difference.

Cache (as Kaiido said): If an image is cached, most likely will be rendered before others. There is server cache and client (browser) cache, each play a role.

Client Speed Connection: Your internet speed connection. If you have fiber-optic speed connection to request a small image, and have a cached giant image, there is a chance the requested image from server may render even before the cached.

Timeout: If an image request times out, it may take few seconds 'til it times out, which means the bigger images may render will the small image still waiting until it times out.

Rendering Time: Rendering 50MB may take seconds/minutes, while requesting and rendering a small image may take a split of a second. Rendering time depends on the client's computer specs.

Image Sprites: When optimizing images for website, combining multiple images into one, may endup in a bigger image size but less requests. But most of the time it's better for faster rendering. Read more.

Browsers Limit: In the old days, IE6 had a limit of 2 requests only, which means the ones requested first even if huge will be loaded first and the others will have to wait. Now the limit has gone up. EDIT: as "A STEFANI" mentioned, each browser engine handles the DOM differently, which may affect the rendering.

Utilizing CDNs: Requesting many images from one server even if small images, and requesting only 1 image from another server, makes a difference. The one getting many requests will have to do more processing causing the server to delay at responding.

Title: How does the browser render Images with different sizes (<img> tag in HTML)?

Body:
If an HTML document has three images in different sizes (5MB, 50KB and 10MB) then which image will be rendered first in the page? Does the browser process  tags synchronously? That is, will the render sequence  be

5_mb_img.jpg > 50_kb_img.jpg > 10_mb_img.jpg

OR

might 50_kb_img.jpg be rendered first because  it is smallest in size?

WHY A BOUNTY? I know the answer but am expecting a very good explanation that helps someone who is searching it in Stack Overflow

Body:
There are many factors to depend on.

Normally, the smallest will render first and the largest will render last.

Asynchronized Requests: meaning you don't know which request happen first. When you have a huge HTML page, the first <img src="..."> the browser sees will be requested first, while the last one will be requested last. But which request will get response first depend on other factors.

Server Response Time: <img src="http://domain1.com/img.jpg"> and <img src="http://domain2.com/img.jpg"> are at different servers, one server could be really fast responding, while another could be really slow.

Image Size: File size makes a difference.

Cache (as Kaiido said): If an image is cached, most likely will be rendered before others. There is server cache and client (browser) cache, each play a role.

Client Speed Connection: Your internet speed connection. If you have fiber-optic speed connection to request a small image, and have a cached giant image, there is a chance the requested image from server may render even before the cached.

Timeout: If an image request times out, it may take few seconds 'til it times out, which means the bigger images may render will the small image still waiting until it times out.

Rendering Time: Rendering 50MB may take seconds/minutes, while requesting and rendering a small image may take a split of a second. Rendering time depends on the client's computer specs.

Image Sprites: When optimizing images for website, combining multiple images into one, may endup in a bigger image size but less requests. But most of the time it's better for faster rendering. Read more.

Browsers Limit: In the old days, IE6 had a limit of 2 requests only, which means the ones requested first even if huge will be loaded first and the others will have to wait. Now the limit has gone up. EDIT: as "A STEFANI" mentioned, each browser engine handles the DOM differently, which may affect the rendering.

Utilizing CDNs: Requesting many images from one server even if small images, and requesting only 1 image from another server, makes a difference. The one getting many requests will have to do more processing causing the server to delay at responding.


问:
PDO how do I returns the total number of executed queries
With mysql wrapper

```<code>function query($msql)
{
    $this->last_connection =& $this->connection;
    $this->msql =& $msql;
    $queryult = mysql_query($msql, $this->connection);
    if ($queryult) {
        $this->queries_count++;
        return $queryult;
    } else {
        $this->display_errors();
        return false;
    }
}

function num_queries()
{
    return @$this->queries_count;
}
</code>```

With PDO how to get the total number of executed queries.

答:
If you are counting your queries in a single process/request and need to know how many execute in the course of performing a single task, you could build this functionality right into your database object using the _construct and _destruct magic functions if you are on php 5.3.  Since your existing function for querying in your object increments this count, you can save it.

Write a _destruct function that will save how many times the query function has iterated down to a log file on the system or to a predetermined place in the database.  This will save the value of the queries_count property out to a place where you can utilize it.

```<code>function _destruct(){
//write a log file with the value or a serialized version of the database object itself
//set the mode to w+ so it truncates every request
$fh = fopen('/path/to/a/new/log' 'w+');
fwrite($fh, $this->queries_count);
fclose($fh);
}
</code>```

This will run every time your database object is GC'ed.  You can then write a static method in to open the file and read the value.

```<code>public static function getLastQueriesCount(){
  $fh = fopen('/path/to/a/new/log' 'r+');
  $count = fgets($fh);
  fclose($fh);
  return $count;
}
</code>```

You would of course need write privileges set correctly for this file/directory.  You could substitute the function bodies to store the count however you like - be it flat file format or in a database.

ContentLicense: CC BY-SA 2.5

Body:
With mysql wrapper

function query($msql)
{
    $this->last_connection =& $this->connection;
    $this->msql =& $msql;
    $queryult = mysql_query($msql, $this->connection);
    if ($queryult) {
        $this->queries_count++;
        return $queryult;
    } else {
        $this->display_errors();
        return false;
    }
}

function num_queries()
{
    return @$this->queries_count;
}

With PDO how to get the total number of executed queries.

Body:
If you are counting your queries in a single process/request and need to know how many execute in the course of performing a single task, you could build this functionality right into your database object using the _construct and _destruct magic functions if you are on php 5.3.  Since your existing function for querying in your object increments this count, you can save it.

Write a _destruct function that will save how many times the query function has iterated down to a log file on the system or to a predetermined place in the database.  This will save the value of the queries_count property out to a place where you can utilize it.

function _destruct(){
//write a log file with the value or a serialized version of the database object itself
//set the mode to w+ so it truncates every request
$fh = fopen('/path/to/a/new/log' 'w+');
fwrite($fh, $this->queries_count);
fclose($fh);
}

This will run every time your database object is GC'ed.  You can then write a static method in to open the file and read the value.

public static function getLastQueriesCount(){
  $fh = fopen('/path/to/a/new/log' 'r+');
  $count = fgets($fh);
  fclose($fh);
  return $count;
}

You would of course need write privileges set correctly for this file/directory.  You could substitute the function bodies to store the count however you like - be it flat file format or in a database.


问:
dialog --buildlist option, how to use it?
I've been reading up on the many uses of dialog to create interactive shell scripts, but I'm stumped on how to use the --buildlist option. Read the man pages, searched google, searched stackoverflow, even read through some old articles of Linux Journal from 1994, to no avail.

Can some give me a clear example of how to use it properly?

Lets imagine a directory with 5 files which  you'd want to select from, to copy to another directory. Can someone give a working example?

Thankyou!

答:
Consider the following:

```<code>dialog --buildlist "Select a directory" 20 50 5 \
  f1 "Directory One" off \
  f2 "Directory Two" on \
  f3 "Directory Three" on
</code>```

This will display something like

```<code>     ┌────────────────────────────────────────────────┐
     │ Select a directory                             │
     │ ┌─────────────────────┐ ┌────^(-)─────────────┐│
     │ │Directory One        │ │Directory Two        ││
     │ │                     │ │Directory Three      ││
     │ │                     │ │                     ││
     │ │                     │ │                     ││
     │ │                     │ │                     ││
     │ └─────────────────────┘ └─────────────100%────┘│
     │                                                │
     │                                                │
     │                                                │
     │                                                │
     │                                                │
     │                                                │
     │                                                │
     │                                                │
     ├────────────────────────────────────────────────┤
     │           <OK>          <Cancel>               │
     └────────────────────────────────────────────────┘
</code>```

The box is 50 characters wide and 20 rows tall; each column displays 5 items. off/on determines if the item starts in the left or right column, respectively.

The controls:

^ selects the left column

$ selects the right column

Move up and down the selected column with the arrow keys

Move the selected item to the other column with the space bar

Toggle between OK and Cancel with the tab key. If you use the --visit-items option, the tab key lets you cycle through the lists as well as the buttons.

Hit enter to select OK or cancel.

If you select OK, the tags (f1, f2, etc) associated with each item in the right column is printed to standard error.

Body:
Consider the following:

dialog --buildlist "Select a directory" 20 50 5 \
  f1 "Directory One" off \
  f2 "Directory Two" on \
  f3 "Directory Three" on

This will display something like

     ┌────────────────────────────────────────────────┐
     │ Select a directory                             │
     │ ┌─────────────────────┐ ┌────^(-)─────────────┐│
     │ │Directory One        │ │Directory Two        ││
     │ │                     │ │Directory Three      ││
     │ │                     │ │                     ││
     │ │                     │ │                     ││
     │ │                     │ │                     ││
     │ └─────────────────────┘ └─────────────100%────┘│
     │                                                │
     │                                                │
     │                                                │
     │                                                │
     │                                                │
     │                                                │
     │                                                │
     │                                                │
     ├────────────────────────────────────────────────┤
     │           <OK>          <Cancel>               │
     └────────────────────────────────────────────────┘

The box is 50 characters wide and 20 rows tall; each column displays 5 items. off/on determines if the item starts in the left or right column, respectively.

The controls:

^ selects the left column

$ selects the right column

Move up and down the selected column with the arrow keys

Move the selected item to the other column with the space bar

Toggle between OK and Cancel with the tab key. If you use the --visit-items option, the tab key lets you cycle through the lists as well as the buttons.

Hit enter to select OK or cancel.

If you select OK, the tags (f1, f2, etc) associated with each item in the right column is printed to standard error.

ContentLicense: CC BY-SA 4.0


问:
A Module in Angular (2+) should be an App by itself created with angular-cli?
I want to separate the login/register workflow into an isolated module. So far I created the module (ng g module login-module) and I want to add the Facebook and Google SDKs to it.

The thing is, the main module (AppModule) is the responsible for the dependencies (package.json) and I would like to isolate the dependencies for the login/register workflow too.

That means that my LoginModule should be an Angular App by itself (created with ng new login-module)?

答:
In a normal situation you don't want to have to applications (i.e. 2 websites) where one is responsible for stuff and the other for authentication. Stuff would still need to make requests to the authentication and then .. why separate that?

Also there are different things you talk about. You want to separate the flow and you look into the right direction with module.

But then, other parts of your application might need to check whether somebody is authenticated and display a message or not allow certain things.

So go ahead and create the module which handles the interaction with the user (registration form, login form). Thats the right thing.

Then use a auth-service to handle and store the current state. And beside storing tokens this should also orchestrate which method to call (Google login or FB login)

Set up a structure recommended by John Papa here: https://angular.io/docs/ts/latest/guide/style-guide.html under the section Application structure and Angular modules

Use package.json and import at the places (the auth-service).. Export the auth-service to a core-module and import this core-module into the app-module and the application modules where you need the functionalities of that one core-module.


问:
The EntityContainer name must be unique. An EntityContainer with the name 'Entities' is already defined
For a little background:

I have a DLL project with the following structure:

```<code>Rivworks.Model (project)
  \Negotiation (folder)
      Model.edmx (model from DB #1)
  \NegotiationAutos (folder)
      Model.edmx (model from DB #2)
</code>```

I have moved the connection strings from this project's app.config to the web.config file.  They are not in the ConnectionString section.  Rather, I have a static class that consumes part of the web.config and exposes them to my app as AppSettings.[settingName].

```<code><FeedAutosEntities_connString>metadata=res://*/;provider=System.Data.SqlClient;provider connection string='Data Source=db4;Initial Catalog=RivFeeds;Persist Security Info=True;User ID=****;Password="****";MultipleActiveResultSets=True'</FeedAutosEntities_connString>
<RivWorkEntities_connString>metadata=res://*/NegotiationAutos.NegotiationAutos.csdl|res://*/NegotiationAutos.NegotiationAutos.ssdl|res://*/NegotiationAutos.NegotiationAutos.msl;provider=System.Data.SqlClient;provider connection string='Data Source=db2;Initial Catalog=RivFramework_Dev;Persist Security Info=True;User ID=****;Password="****";MultipleActiveResultSets=True'</RivWorkEntities_connString>
</code>```

I have 2 classes, one for each Context and they look like this:

```<code>namespace RivWorks.Model
{
    public class RivWorksStore
    {
        private RivWorks.Model.Negotiation.Entities _dbNegotiation;

        public RivWorksStore(string connectionString, string metadata, string provider)
        {
            EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder();
            entityBuilder.ConnectionString = connectionString;
            entityBuilder.Metadata = "res://*/";    // metadata;
            //entityBuilder.Provider = provider;
            _dbNegotiation = new RivWorks.Model.Negotiation.Entities(entityBuilder.ConnectionString);
        }

        public RivWorks.Model.Negotiation.Entities NegotiationEntities()
        {
            return _dbNegotiation;
        }
    }
}

namespace RivWorks.Model
{
    public class FeedStoreReadOnly
    {
        private RivWorks.Model.NegotiationAutos.Entities _dbFeed;

        public FeedStoreReadOnly(string connectionString, string metadata, string provider)
        {
            EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder();
            entityBuilder.ConnectionString = connectionString;
            entityBuilder.Metadata = "res://*/";    // metadata;
            //entityBuilder.Provider = provider;
            _dbFeed = new RivWorks.Model.NegotiationAutos.Entities(entityBuilder.ConnectionString);
        }

        public RivWorks.Model.NegotiationAutos.Entities ReadOnlyEntities()
        {
            return _dbFeed;
        }
    }
}
</code>```

You will note that the MetaData is being rewritten to a short version.

When I comment out that line in each class I get this error:

Unable to load the specified metadata resource.

When I leave that line in in each class I get this error:

Schema specified is not valid. Errors:

Negotiation.Model.csdl(3,4) : error 0019: The EntityContainer name must be unique. An EntityContainer with the name 'Entities' is already defined.

I know it is something simple, something obvious.  Any suggestions welcome...

答:
To solve the issue Entity 6.2.0, VS 2017, single edmx

I changed the name of my model.edmx to another name, built the project, then changed it back to the original name.

Body:
For a little background:

I have a DLL project with the following structure:

Rivworks.Model (project)
  \Negotiation (folder)
      Model.edmx (model from DB #1)
  \NegotiationAutos (folder)
      Model.edmx (model from DB #2)

I have moved the connection strings from this project's app.config to the web.config file.  They are not in the ConnectionString section.  Rather, I have a static class that consumes part of the web.config and exposes them to my app as AppSettings.[settingName].

<FeedAutosEntities_connString>metadata=res://*/;provider=System.Data.SqlClient;provider connection string='Data Source=db4;Initial Catalog=RivFeeds;Persist Security Info=True;User ID=****;Password="****";MultipleActiveResultSets=True'</FeedAutosEntities_connString>
<RivWorkEntities_connString>metadata=res://*/NegotiationAutos.NegotiationAutos.csdl|res://*/NegotiationAutos.NegotiationAutos.ssdl|res://*/NegotiationAutos.NegotiationAutos.msl;provider=System.Data.SqlClient;provider connection string='Data Source=db2;Initial Catalog=RivFramework_Dev;Persist Security Info=True;User ID=****;Password="****";MultipleActiveResultSets=True'</RivWorkEntities_connString>

I have 2 classes, one for each Context and they look like this:

namespace RivWorks.Model
{
    public class RivWorksStore
    {
        private RivWorks.Model.Negotiation.Entities _dbNegotiation;

        public RivWorksStore(string connectionString, string metadata, string provider)
        {
            EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder();
            entityBuilder.ConnectionString = connectionString;
            entityBuilder.Metadata = "res://*/";    // metadata;
            //entityBuilder.Provider = provider;
            _dbNegotiation = new RivWorks.Model.Negotiation.Entities(entityBuilder.ConnectionString);
        }

        public RivWorks.Model.Negotiation.Entities NegotiationEntities()
        {
            return _dbNegotiation;
        }
    }
}

namespace RivWorks.Model
{
    public class FeedStoreReadOnly
    {
        private RivWorks.Model.NegotiationAutos.Entities _dbFeed;

        public FeedStoreReadOnly(string connectionString, string metadata, string provider)
        {
            EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder();
            entityBuilder.ConnectionString = connectionString;
            entityBuilder.Metadata = "res://*/";    // metadata;
            //entityBuilder.Provider = provider;
            _dbFeed = new RivWorks.Model.NegotiationAutos.Entities(entityBuilder.ConnectionString);
        }

        public RivWorks.Model.NegotiationAutos.Entities ReadOnlyEntities()
        {
            return _dbFeed;
        }
    }
}

You will note that the MetaData is being rewritten to a short version.

When I comment out that line in each class I get this error:

Unable to load the specified metadata resource.

When I leave that line in in each class I get this error:

Schema specified is not valid. Errors:

Negotiation.Model.csdl(3,4) : error 0019: The EntityContainer name must be unique. An EntityContainer with the name 'Entities' is already defined.

I know it is something simple, something obvious.  Any suggestions welcome...


问:
Using scrapy shell with splash return empty value
I'm scraping this site: http://www.germandeli.com/Meats/Sausages which contains some dynamic content.

I am using scrapy shell with splash to render the javascript but it returns the empty value []. My system is Ubuntu 14.04 LTS.

Here the code I used:

```<code>$ scrapy shell 'http://localhost:8050/render.html?url=http://www.germandeli.com/Meats/Sausages'
>>> response.xpath('*//h2[@class="item-cell-name"]/a/@href').extract()
</code>```

Any hint would be greatly appreciated!

答:
I figured it out. I forgot to add '&timeout=10&wait=5' in the end of the link!</p>

```<code>scrapy shell 'http://localhost:8050/render.html?url=http://www.germandeli.com/Meats/Sausages&timeout=10&wait=5'
</code>```

Body:
I'm scraping this site: http://www.germandeli.com/Meats/Sausages which contains some dynamic content.

I am using scrapy shell with splash to render the javascript but it returns the empty value []. My system is Ubuntu 14.04 LTS.

Here the code I used:

$ scrapy shell 'http://localhost:8050/render.html?url=http://www.germandeli.com/Meats/Sausages'
>>> response.xpath('*//h2[@class="item-cell-name"]/a/@href').extract()

Any hint would be greatly appreciated!

Body:
I figured it out. I forgot to add '&timeout=10&wait=5' in the end of the link!

scrapy shell 'http://localhost:8050/render.html?url=http://www.germandeli.com/Meats/Sausages&timeout=10&wait=5'


答:
If you need two, just tell numpy.random.choice() to pick two values; include the el value as a tuple as you loop (no need to use zip()):

```<code>tuples = []
for el in elements:
    for chosen in choice(elements, size=2, replace=False, p=weights):
        tuples.append((el, chosen))
</code>```

or by using a list comprehension:

```<code>tuples = [(el, chosen) for el in elements
          for chosen in choice(elements, size=2, replace=False, p=weights)]
</code>```

By setting replace=False, you get unique values; remove it or set it to True explicitly to allow for repetition. See the numpy.random.choice() documentation:

size : int or tuple of ints, optional

  Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. Default is None, in which case a single value is returned.

replace : boolean, optional

  Whether the sample is with or without replacement

Demo:

```<code>>>> from numpy.random import choice
>>> elements = ['one', 'two', 'three']
>>> weights = [0.2, 0.3, 0.5]
>>> tuples = []
>>> for el in elements:
...     for chosen in choice(elements, size=2, replace=False, p=weights):
...         tuples.append((el, chosen))
...
>>> tuples
[('one', 'three'), ('one', 'one'), ('two', 'three'), ('two', 'two'), ('three', 'three'), ('three', 'two')]
>>> [(el, chosen) for el in elements for chosen in choice(elements, size=2, replace=False, p=weights)]
[('one', 'one'), ('one', 'three'), ('two', 'one'), ('two', 'three'), ('three', 'two'), ('three', 'three')]
</code>```

Title: Choosing more than 1 element from the list

Body:
I am trying to make a choice for each element in elements, and then I am pairing up the element in elements list with its preferential choice(one,two or three). The choice is mostly done regarding the probabilities (weights) of the elements. The code until here:

from numpy.random import choice
elements = ['one', 'two', 'three']
weights = [0.2, 0.3, 0.5]
chosenones= []
for el in elements:
    chosenones.append(choice(elements,p=weights))
tuples = list(zip(elements,chosenones))

Yields:

[('one', 'two'), ('two', 'two'), ('three', 'two')]

What I need is, for each element to make two choices instead of one.

The expected output should look like:

[('one', 'two'), ('one', 'one'), ('two', 'two'),('two', 'three'), ('three', 'two'), ('three', 'one')]

Do you know how to do have this output?

Body:
If you need two, just tell numpy.random.choice() to pick two values; include the el value as a tuple as you loop (no need to use zip()):

tuples = []
for el in elements:
    for chosen in choice(elements, size=2, replace=False, p=weights):
        tuples.append((el, chosen))

or by using a list comprehension:

tuples = [(el, chosen) for el in elements
          for chosen in choice(elements, size=2, replace=False, p=weights)]

By setting replace=False, you get unique values; remove it or set it to True explicitly to allow for repetition. See the numpy.random.choice() documentation:

size : int or tuple of ints, optional

  Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. Default is None, in which case a single value is returned.

replace : boolean, optional

  Whether the sample is with or without replacement

Demo:

>>> from numpy.random import choice
>>> elements = ['one', 'two', 'three']
>>> weights = [0.2, 0.3, 0.5]
>>> tuples = []
>>> for el in elements:
...     for chosen in choice(elements, size=2, replace=False, p=weights):
...         tuples.append((el, chosen))
...
>>> tuples
[('one', 'three'), ('one', 'one'), ('two', 'three'), ('two', 'two'), ('three', 'three'), ('three', 'two')]
>>> [(el, chosen) for el in elements for chosen in choice(elements, size=2, replace=False, p=weights)]
[('one', 'one'), ('one', 'three'), ('two', 'one'), ('two', 'three'), ('three', 'two'), ('three', 'three')]


问:
get edge weights when creating the graph
Suppose we have a list with the edges, and we created with graph with igraph:

```<code>links = [[1, 2], [1, 3], [2, 4], [1, 2]]
g = ig.Graph()
for link in links:
    g.add_vertices(link)
g.add_edges(links)

print(g)
# IGRAPH UN-- 8 4 --
# + attr: name (v)
# + edges (vertex names):
# 2--1, 2--3, 1--2, 2--1
</code>```

2 -- 1 is repeated. How can you create the graph to get the edge weights?

答:
According to igraph documentation, edges can be repeated, so, if you don't want edges duplicates, you need to remove them by your own.

This piece of code shows how to set weights (or any property you want) to edges and how to read then.

Creation of the graph

```<code>import igraph as ig

links = [[1, 2], [1, 3], [2, 4], [1, 2]]
vertices = [v for s in links for v in s]  # = [1,2,1,3,2,4,1,2]
g = ig.Graph()
g.add_vertices(vertices)
for l in links:
  g.add_edge(l[0], l[1], weight=0.5*l[0]*l[1]) # weight value is just an example

print(g)
</code>```

The links list is flattered in order to get a vertices list. Not that vertices cannot be duplicated, hence there's no need to explicitly remove the duplicates elements in them.

You can specify any property you want add to the edge by specifying the relative keyword argument (weight=0.5*l[0]*l[1]).

Retriving Edges infos

You retrive the weights by simply e['weight'] where e is a single edge (igraph.Edge object). In this example it's shown how to loop over the edges set.

```<code>print("\nEdges\n")
for e in g.es():
  print("source: %s target: %d" % (e.source, e.target))
  print("multiplicity %d" % (g.count_multiple(e)))
  print("weight %f\n" % e['weight'])
</code>```

The output is this:

```<code>Edges

source: 1 target: 2
multiplicity 2
weight 1.000000

source: 1 target: 3
multiplicity 1
weight 1.500000

source: 2 target: 4
multiplicity 1
weight 4.000000

source: 1 target: 2
multiplicity 2
weight 1.000000
</code>```

For further details, refer to the documentation of igraph: igraph.Graph, igraph.Vertex and igraph.Edge

Body:
Suppose we have a list with the edges, and we created with graph with igraph:

links = [[1, 2], [1, 3], [2, 4], [1, 2]]
g = ig.Graph()
for link in links:
    g.add_vertices(link)
g.add_edges(links)

print(g)
# IGRAPH UN-- 8 4 --
# + attr: name (v)
# + edges (vertex names):
# 2--1, 2--3, 1--2, 2--1

2 -- 1 is repeated. How can you create the graph to get the edge weights?

Body:
According to igraph documentation, edges can be repeated, so, if you don't want edges duplicates, you need to remove them by your own.

This piece of code shows how to set weights (or any property you want) to edges and how to read then.

Creation of the graph

import igraph as ig

links = [[1, 2], [1, 3], [2, 4], [1, 2]]
vertices = [v for s in links for v in s]  # = [1,2,1,3,2,4,1,2]
g = ig.Graph()
g.add_vertices(vertices)
for l in links:
  g.add_edge(l[0], l[1], weight=0.5*l[0]*l[1]) # weight value is just an example

print(g)

The links list is flattered in order to get a vertices list. Not that vertices cannot be duplicated, hence there's no need to explicitly remove the duplicates elements in them.

You can specify any property you want add to the edge by specifying the relative keyword argument (weight=0.5*l[0]*l[1]).

Retriving Edges infos

You retrive the weights by simply e['weight'] where e is a single edge (igraph.Edge object). In this example it's shown how to loop over the edges set.

print("\nEdges\n")
for e in g.es():
  print("source: %s target: %d" % (e.source, e.target))
  print("multiplicity %d" % (g.count_multiple(e)))
  print("weight %f\n" % e['weight'])

The output is this:

Edges

source: 1 target: 2
multiplicity 2
weight 1.000000

source: 1 target: 3
multiplicity 1
weight 1.500000

source: 2 target: 4
multiplicity 1
weight 4.000000

source: 1 target: 2
multiplicity 2
weight 1.000000

For further details, refer to the documentation of igraph: igraph.Graph, igraph.Vertex and igraph.Edge


问:
How to modify the code for p-values (lapply R)
I can extract the p-value (df2) if I define modelList in this way

```<code>responseList <- names(mtcars)[-c(4,9)]
modelList    <- lapply(responseList, function(resp) {
                           mF <- formula(paste(resp, " ~ hp*am"))
                           aov(mF, data = mtcars)
                })
df2 <- plyr::ldply( modelList , function(x) summary(x)[[1]][["Pr(>F)"]])
names(df2) <- c(attr(modelList[[1]]$terms, "term.labels"), "residuals")
</code>```

However if I define ModelList in the following way, I can not get the result.

```<code>formula <- as.formula(paste0("cbind(", paste(names(mtcars)[-c(4,9)], collapse = ","), ") ~ hp*am"))
modelList  <- aov(formula, data=mtcars)
</code>```

So how can I modify df2 in order to extract the pvalues from the second defined function for modelList.

```<code>df2 <- plyr::ldply( modelList , function(x) summary(x)[[1]][["Pr(>F)"]])
    names(df2) <- c(attr(modelList[[1]]$terms, "term.labels"), "residuals")
</code>```

Body:
I can extract the p-value (df2) if I define modelList in this way

responseList <- names(mtcars)[-c(4,9)]
modelList    <- lapply(responseList, function(resp) {
                           mF <- formula(paste(resp, " ~ hp*am"))
                           aov(mF, data = mtcars)
                })
df2 <- plyr::ldply( modelList , function(x) summary(x)[[1]][["Pr(>F)"]])
names(df2) <- c(attr(modelList[[1]]$terms, "term.labels"), "residuals")

However if I define ModelList in the following way, I can not get the result.

formula <- as.formula(paste0("cbind(", paste(names(mtcars)[-c(4,9)], collapse = ","), ") ~ hp*am"))
modelList  <- aov(formula, data=mtcars)

So how can I modify df2 in order to extract the pvalues from the second defined function for modelList.

df2 <- plyr::ldply( modelList , function(x) summary(x)[[1]][["Pr(>F)"]])
    names(df2) <- c(attr(modelList[[1]]$terms, "term.labels"), "residuals")

Body:
Here is one of the possible ways for extracting p-values from the second modelList.

formula <- as.formula(paste0("cbind(", paste(names(mtcars)[-c(4,9)], collapse = ","), ") ~ hp*am"))
modelList2  <- aov(formula, data=mtcars)

df2 <- plyr::ldply( summary(modelList2), function(x) x[,"Pr(>F)"])
names(df2) <- c("", rownames(modelList2[[1]])[-1], "residuals")
df2

################
                           hp           am        hp:am residuals
1   Response mpg 1.504500e-09 4.748593e-05 0.9806460396        NA
2   Response cyl 3.974632e-11 2.997217e-04 0.0969093688        NA
3  Response disp 5.835767e-11 1.164601e-05 0.0178673463        NA
4  Response drat 9.236405e-04 1.911898e-05 0.8664040719        NA
5    Response wt 1.348501e-07 2.977105e-06 0.1913211750        NA
6  Response qsec 2.312064e-07 4.577810e-04 0.1767439339        NA
7    Response vs 2.060911e-06 9.495711e-01 0.0458841894        NA
8  Response gear 1.696824e-01 1.405025e-09 0.0002293635        NA
9  Response carb 3.077405e-07 3.622291e-02 0.1902486095        NA


问:
Replace backward slashes with forwards slashes or double backward slashes in C++
So I have a string:

```<code>string path = "C:\Users\Richard\Documents\Visual Studio 2010\Projects\Client\Debug";
</code>```

I want to replace all backward slashes in it with forward ones so it looks like:

```<code>C:/Users/Richard/Documents/Visual Studio 2010/Projects/Client/Debug
</code>```

This does not work:

```<code>string toReplace = "\\";
path.replace(path.find(toReplace), toReplace.length(), "/");
</code>```

Obviously, \ is an escape character so that is probably causing the problem.

答:
As far as I know, there's no way to do this from the string you specified.  Your code is trying to escape the characters U, R, D, V, P, etc.

If the string is hard-coded, you'll have to use double-slashes (i.e., C:\\Users\\Richard...).

If the string is a path that, say, the user enters, you might be able to add the escape characters programmatically.

Body:
So I have a string:

string path = "C:\Users\Richard\Documents\Visual Studio 2010\Projects\Client\Debug";

I want to replace all backward slashes in it with forward ones so it looks like:

C:/Users/Richard/Documents/Visual Studio 2010/Projects/Client/Debug

This does not work:

string toReplace = "\\";
path.replace(path.find(toReplace), toReplace.length(), "/");

Obviously, \ is an escape character so that is probably causing the problem.


问:
How to SEND multiple requests ASYNC from Flask server?
So I'm building a Flask API, and I have a GET route that basically sends 5 requests to another API to gather data that I'm then merging and returning.

Like so:

```<code>results = [requests.get('http://localhost:9000/ss/1'),
            requests.get('http://localhost:9000/ss/2'),
        requests.get('http://localhost:9000/ss/3'),
       requests.get('http://localhost:9000/ss/4'),
            requests.get('http://localhost:9000/ss/5')]
</code>```

The problem is each request takes about 2 seconds, so it takes 10 seconds for this to go down. How can I make all the requests async using different threads so it will take around 2 seconds overall? And then how do I tell the API to start merging them when theyre all loaded?

Any help is GREATLY appreciated!

答:
You can use grequests package( https://pypi.python.org/pypi/grequests) that is originally based on gevent I think and requests.

Code is as simple as:

```<code>urls = [url1,url2,...]
#prepare the shells
shells = (grequests.get(u) for u in urls)
#start all requests at the same time
responses = grequests.map(shells) #will output a list of responses that you can access
</code>```

Body:
So I'm building a Flask API, and I have a GET route that basically sends 5 requests to another API to gather data that I'm then merging and returning.

Like so:

results = [requests.get('http://localhost:9000/ss/1'),
            requests.get('http://localhost:9000/ss/2'),
        requests.get('http://localhost:9000/ss/3'),
       requests.get('http://localhost:9000/ss/4'),
            requests.get('http://localhost:9000/ss/5')]

The problem is each request takes about 2 seconds, so it takes 10 seconds for this to go down. How can I make all the requests async using different threads so it will take around 2 seconds overall? And then how do I tell the API to start merging them when theyre all loaded?

Any help is GREATLY appreciated!

Body:
You can use grequests package( https://pypi.python.org/pypi/grequests) that is originally based on gevent I think and requests.

Code is as simple as:

urls = [url1,url2,...]
#prepare the shells
shells = (grequests.get(u) for u in urls)
#start all requests at the same time
responses = grequests.map(shells) #will output a list of responses that you can access


问:
Using SSHTunnel Correctly
I'm trying to use pymysql and sshtunnel in python2.7 to tunnel my connection so that I can connect to a mysql instance that is only accessible via a bastion server. The bastion server has a hostname of BASTIONIP and that server can connection to MYSQLHOST with no problem. However, python can't seem to connect via the tunnel. Below is my code:

```<code>    with sshtunnel.SSHTunnelForwarder(
            (BASTIONIP, 22),
            ssh_username='dataengineer',
            ssh_pkey="/Users/USERNAME/.ssh/id_rsa",
            remote_bind_address=(MYSQLHOST, 3306),
            local_bind_address=(MYSQLHOST, 3306)
    ) as tunnel:
        self.DB = {'con': pymysql.connect(host=MYSQLHOST,
                                          user=USERNAME,
                                          passwd=PASSWORD,
                                          db=DBNAME,
                                          port=tunnel.local_bind_port,
                                          charset='utf8',
                                          autocommit=True)}
        self.DB['cursor'] = self.DB['con'].cursor(pymysql.cursors.DictCursor)
</code>```

However, when I try to connect I get the following error:

```<code>  File "/Library/Python/2.7/site-packages/sshtunnel.py", line 1378, in _get_local_interfaces
    local_if = socket.gethostbyname_ex(socket.gethostname())[-1]
gaierror: [Errno 8] nodename nor servname provided, or not known
</code>```

Can anyone point out what I am doing wrong?

答:
Possible reasons I could figure out after some googling are mentioned below:

Not Sure, it was caused by _get_local_interfaces trying to resolve the local hostname and failing (probably just a bad /etc/hosts file or something)

Try to open as root /etc/hosts file, and add a line like the following

```<code># IP ADDR      HOSTNAME
192.168.1.1    your_desired_hostname
</code>```

and the name should resolve.
update 192.168.1.1 with your ip address.
Here

Another Resolution:
Replace :

local_if = socket.gethostbyname_ex(socket.gethostname())[-1]

with

```<code>  try:
    local_if = socket.gethostbyname_ex(socket.gethostname())[-1]
except:
    local_if = []
</code>```

Here

Title: Using SSHTunnel Correctly

Body:
I'm trying to use pymysql and sshtunnel in python2.7 to tunnel my connection so that I can connect to a mysql instance that is only accessible via a bastion server. The bastion server has a hostname of BASTIONIP and that server can connection to MYSQLHOST with no problem. However, python can't seem to connect via the tunnel. Below is my code:

    with sshtunnel.SSHTunnelForwarder(
            (BASTIONIP, 22),
            ssh_username='dataengineer',
            ssh_pkey="/Users/USERNAME/.ssh/id_rsa",
            remote_bind_address=(MYSQLHOST, 3306),
            local_bind_address=(MYSQLHOST, 3306)
    ) as tunnel:
        self.DB = {'con': pymysql.connect(host=MYSQLHOST,
                                          user=USERNAME,
                                          passwd=PASSWORD,
                                          db=DBNAME,
                                          port=tunnel.local_bind_port,
                                          charset='utf8',
                                          autocommit=True)}
        self.DB['cursor'] = self.DB['con'].cursor(pymysql.cursors.DictCursor)

However, when I try to connect I get the following error:

  File "/Library/Python/2.7/site-packages/sshtunnel.py", line 1378, in _get_local_interfaces
    local_if = socket.gethostbyname_ex(socket.gethostname())[-1]
gaierror: [Errno 8] nodename nor servname provided, or not known

Can anyone point out what I am doing wrong?

Body:
Possible reasons I could figure out after some googling are mentioned below:

Not Sure, it was caused by _get_local_interfaces trying to resolve the local hostname and failing (probably just a bad /etc/hosts file or something)

Try to open as root /etc/hosts file, and add a line like the following

# IP ADDR      HOSTNAME
192.168.1.1    your_desired_hostname

and the name should resolve.
update 192.168.1.1 with your ip address.
Here

Another Resolution:
Replace :

local_if = socket.gethostbyname_ex(socket.gethostname())[-1]

with

  try:
    local_if = socket.gethostbyname_ex(socket.gethostname())[-1]
except:
    local_if = []

Here


问:
How to use Spring Boot Activity Rest api in Activity App Ui
I am new to Activity process. I want to used the Activity with spring boot application. So, I want to used the rest api in spring boot and that rest api will be used by activiti-admin.war and activiti-app.war.

So, when I have deployed process from spring boot that will be available in UI and add some Listener while assigning task will be called in my spring boot app.

Can any one help.

Thanks in advance.

答:
It sounds like you are using the version 6 Activiti build.
Both the activiti-app and admin-app already use "a" REST API to communicate to the backend, however it is not the community REST API that will be deployed with your Spring boot application (I assume you are using the Activiti spring boot starter rest).

It is not actually going to be trivial to separate the activiti-app and admin-app UI from the service layer as they are quite tightly coupled, but it is certainly possible.
While I haven't actually attempted it, it may be easiest to take the activiti-app build module (activiti-ui/activiti-app) and separate the client and server portions since the client is now a regular AngularJS application.

Is this what you are looking for?
Thanks,
Greg


问:
how to disable userinteraction of nsview
I am trying to do something similar as UserInteractionEnabled = false in iOS, but it seems that this property is not available in NSView. I also see that one approach is to implement the hittest method to return null, but the hittest for this lass already has a non-trivial implementation and I don't think I can set it to return null. I found a (deprecated) property called acceptsTouchEnabled, and I m wondering if it can achieve the same thing as UserInteractionEnabled.
The project is done in Xamarin, btw.

```<code>FreeHandView = new PaintBoardControl
        {
            BackgroundColor = UIColor.Clear,
            TranslatesAutoresizingMaskIntoConstraints = false,
            UserInteractionEnabled = false
        };
</code>```

this is the original declaration of the variable, where the UserInteractionEnabled is set to false.

and this is the implementation of the hittest method in my Mac app:

```<code>public override NSView HitTest(CGPoint aPoint)
    {

        aPoint = ContentContainer.ConvertPointFromView(aPoint, this);
        aPoint = new CGPoint(aPoint.X + _freehandViewLeftConstraint.Constant,
            aPoint.Y + _freehandViewTopConstraint.Constant);
        if (_hitTestBitArray != null && aPoint.X >= 0 && aPoint.Y >= 0 &&
            _hitTestBitArrayWidth > aPoint.X && _hitTestBitArrayHeight > aPoint.Y)
        {
            var index = aPoint.Y * _hitTestBitArrayWidth + aPoint.X;
            return _hitTestBitArray.Get((int)index) ? this : null;
        }

        return null;
    }
</code>```

答:
Sometimes hitTest don't work at all try using something like this maybe mousedown can help you</p>

```<code> public class ExtendedNSView : NSView
    {
        public bool IsEnabled { get; set; }

        public override void MouseDown(NSEvent theEvent)
        {
            if (IsEnabled)
            {
                base.MouseDown(theEvent);
            }
        }
    }
</code>```

Body:
I am trying to do something similar as UserInteractionEnabled = false in iOS, but it seems that this property is not available in NSView. I also see that one approach is to implement the hittest method to return null, but the hittest for this lass already has a non-trivial implementation and I don't think I can set it to return null. I found a (deprecated) property called acceptsTouchEnabled, and I m wondering if it can achieve the same thing as UserInteractionEnabled.
The project is done in Xamarin, btw.

FreeHandView = new PaintBoardControl
        {
            BackgroundColor = UIColor.Clear,
            TranslatesAutoresizingMaskIntoConstraints = false,
            UserInteractionEnabled = false
        };

this is the original declaration of the variable, where the UserInteractionEnabled is set to false.

and this is the implementation of the hittest method in my Mac app:

public override NSView HitTest(CGPoint aPoint)
    {

        aPoint = ContentContainer.ConvertPointFromView(aPoint, this);
        aPoint = new CGPoint(aPoint.X + _freehandViewLeftConstraint.Constant,
            aPoint.Y + _freehandViewTopConstraint.Constant);
        if (_hitTestBitArray != null && aPoint.X >= 0 && aPoint.Y >= 0 &&
            _hitTestBitArrayWidth > aPoint.X && _hitTestBitArrayHeight > aPoint.Y)
        {
            var index = aPoint.Y * _hitTestBitArrayWidth + aPoint.X;
            return _hitTestBitArray.Get((int)index) ? this : null;
        }

        return null;
    }

Body:
Sometimes hitTest don't work at all try using something like this maybe mousedown can help you

 public class ExtendedNSView : NSView
    {
        public bool IsEnabled { get; set; }

        public override void MouseDown(NSEvent theEvent)
        {
            if (IsEnabled)
            {
                base.MouseDown(theEvent);
            }
        }
    }


问:
How to call a method when a trait and struct use the same method name?
This program dies because of infinite recursion:

```<code>use std::any::Any;

trait Foo {
    fn get(&self, index: usize) -> Option<&Any>;
}

impl Foo for Vec<i32> {
    fn get(&self, index: usize) -> Option<&Any> {
        Vec::get(self, index).map(|v| v as &Any)
    }
}

fn main() {
    let v: Vec<i32> = vec![1, 2, 4];
    println!("Results: {:?}", v.get(0))
}
</code>```

The compiler itself warns about this:

warning: function cannot return without recurring
  --> src/main.rs:8:5
   |
8  |       fn get(&self, index: usize) -> Option<&Any> {
   |  _____^ starting here...
9  | |         Vec::get(self, index).map(|v| v as &Any)
10 | |     }
   | |_____^ ...ending here
   |
   = note: #[warn(unconditional_recursion)] on by default
note: recursive call site
  --> src/main.rs:9:9
   |
9  |         Vec::get(self, index).map(|v| v as &Any)
   |         ^^^^^^^^^^^^^^^^^^^^^
   = help: a `loop` may express intention better if this is on purpose
```

Why does universal call syntax not work in this case? The compiler does not understand that I want to call Vec::get not Foo::get.

How can I fix this, if I do not want to change function names?

答:
To specify which method to call, whether inherent or provided from a trait, you want to use the fully qualified syntax:

```<code>Type::function(maybe_self, needed_arguments, more_arguments)
Trait::function(maybe_self, needed_arguments, more_arguments)
</code>```

Your case doesn't work because Vec doesn't have a method called get! get is provided from the Deref implementation to [T].

The easiest fix is to call as_slice directly:

```<code>self.as_slice().get(index).map(|v| v as &Any)
</code>```

You could also use the fully qualified syntax which requires the angle brackets in this case (<...>) to avoid ambiguity with declaring an array literal:

```<code><[i32]>::get(self, index).map(|v| v as &Any)
</code>```

universal call syntax

Note that while Rust originally used the term universal function call syntax (UFCS), the usage of this term conflicted with the existing understood programming term, so the use of it is not suggested. The replacement term is fully qualified syntax.

Body:
This program dies because of infinite recursion:

use std::any::Any;

trait Foo {
    fn get(&self, index: usize) -> Option<&Any>;
}

impl Foo for Vec<i32> {
    fn get(&self, index: usize) -> Option<&Any> {
        Vec::get(self, index).map(|v| v as &Any)
    }
}

fn main() {
    let v: Vec<i32> = vec![1, 2, 4];
    println!("Results: {:?}", v.get(0))
}

The compiler itself warns about this:

warning: function cannot return without recurring
  --> src/main.rs:8:5
   |
8  |       fn get(&self, index: usize) -> Option<&Any> {
   |  _____^ starting here...
9  | |         Vec::get(self, index).map(|v| v as &Any)
10 | |     }
   | |_____^ ...ending here
   |
   = note: #[warn(unconditional_recursion)] on by default
note: recursive call site
  --> src/main.rs:9:9
   |
9  |         Vec::get(self, index).map(|v| v as &Any)
   |         ^^^^^^^^^^^^^^^^^^^^^
   = help: a `loop` may express intention better if this is on purpose

Why does universal call syntax not work in this case? The compiler does not understand that I want to call Vec::get not Foo::get.

How can I fix this, if I do not want to change function names?

Body:
To specify which method to call, whether inherent or provided from a trait, you want to use the fully qualified syntax:

Type::function(maybe_self, needed_arguments, more_arguments)
Trait::function(maybe_self, needed_arguments, more_arguments)

Your case doesn't work because Vec doesn't have a method called get! get is provided from the Deref implementation to [T].

The easiest fix is to call as_slice directly:

self.as_slice().get(index).map(|v| v as &Any)

You could also use the fully qualified syntax which requires the angle brackets in this case (<...>) to avoid ambiguity with declaring an array literal:

<[i32]>::get(self, index).map(|v| v as &Any)

universal call syntax

Note that while Rust originally used the term universal function call syntax (UFCS), the usage of this term conflicted with the existing understood programming term, so the use of it is not suggested. The replacement term is fully qualified syntax.