问:
Order By 2 columns
I have this table and .

```<code> id  |  item_id  | created_at
-----+-----------+------------
  1  |   Apple   | 2017-03-21
  2  |   Grape   | 2017-03-23
  3  |   Grape   | 2017-03-24
  4  |   Apple   | 2017-03-25
</code>```

I want to order by created_at and also at the same time order by item_id like this:

```<code> id  |  item_id  | created_at
-----+-----------+------------
  4  |   Apple   | 2017-03-25
  1  |   Apple   | 2017-03-21
  3  |   Grape   | 2017-03-24
  2  |   Grape   | 2017-03-23
</code>```

So if i add a new row for item_id: Grape my new results should be like this:

```<code> id  |  item_id  | created_at
-----+-----------+------------
  5  |   Grape   | 2017-03-28  (NEW)
  3  |   Grape   | 2017-03-24
  2  |   Grape   | 2017-03-23
  4  |   Apple   | 2017-03-25
  1  |   Apple   | 2017-03-21
</code>```

and then if i add new row for item_id: Apple it should be like this:

```<code> id  |  item_id  | created_at
-----+-----------+------------
  6  |   Apple   | 2017-03-28  (NEW)
  4  |   Apple   | 2017-03-25
  1  |   Apple   | 2017-03-21
  5  |   Grape   | 2017-03-27
  3  |   Grape   | 2017-03-24
  2  |   Grape   | 2017-03-23
</code>```

...So it orders by the latest created_at and show the other rows with the same item_id below it

I have tried ORDER BY created_at, item_id  DESC but it does not works and give me this instead:

```<code> id  |  item_id  | created_at
-----+-----------+------------
  6  |   Apple   | 2017-03-28
  5  |   Grape   | 2017-03-27
  4  |   Apple   | 2017-03-25
  3  |   Grape   | 2017-03-24
  2  |   Grape   | 2017-03-23
  1  |   Apple   | 2017-03-21
</code>```

答:
Please try -</p>

```<code>SELECT id,
       item_ID,
       created_at
FROM tblOrders
ORDER BY item_ID,
         item_ID = ( SELECT item_ID
                     FROM tblOrders
                     WHERE id = ( SELECT MAX( id ) FROM tblOrders ) ),
         created_at;
</code>```

Title: Order By 2 columns

Body:
I have this table and .

 id  |  item_id  | created_at
-----+-----------+------------
  1  |   Apple   | 2017-03-21
  2  |   Grape   | 2017-03-23
  3  |   Grape   | 2017-03-24
  4  |   Apple   | 2017-03-25

I want to order by created_at and also at the same time order by item_id like this:

 id  |  item_id  | created_at
-----+-----------+------------
  4  |   Apple   | 2017-03-25
  1  |   Apple   | 2017-03-21
  3  |   Grape   | 2017-03-24
  2  |   Grape   | 2017-03-23

So if i add a new row for item_id: Grape my new results should be like this:

 id  |  item_id  | created_at
-----+-----------+------------
  5  |   Grape   | 2017-03-28  (NEW)
  3  |   Grape   | 2017-03-24
  2  |   Grape   | 2017-03-23
  4  |   Apple   | 2017-03-25
  1  |   Apple   | 2017-03-21

and then if i add new row for item_id: Apple it should be like this:

 id  |  item_id  | created_at
-----+-----------+------------
  6  |   Apple   | 2017-03-28  (NEW)
  4  |   Apple   | 2017-03-25
  1  |   Apple   | 2017-03-21
  5  |   Grape   | 2017-03-27
  3  |   Grape   | 2017-03-24
  2  |   Grape   | 2017-03-23

...So it orders by the latest created_at and show the other rows with the same item_id below it

I have tried ORDER BY created_at, item_id  DESC but it does not works and give me this instead:

 id  |  item_id  | created_at
-----+-----------+------------
  6  |   Apple   | 2017-03-28
  5  |   Grape   | 2017-03-27
  4  |   Apple   | 2017-03-25
  3  |   Grape   | 2017-03-24
  2  |   Grape   | 2017-03-23
  1  |   Apple   | 2017-03-21

Body:
Please try -

SELECT id,
       item_ID,
       created_at
FROM tblOrders
ORDER BY item_ID,
         item_ID = ( SELECT item_ID
                     FROM tblOrders
                     WHERE id = ( SELECT MAX( id ) FROM tblOrders ) ),
         created_at;


来源: stackexchange

答:
For mysql, try this:

```<code>select item.*
from item
left join (
    select item_id, max(created_at) maxdate
    from item
    group by item_id
) t on item.item_id = t.item_id
order by t.maxdate desc, item.created_at desc
</code>```

Demo1 in SQLFiddle

Demo2 in SQLFiddle

ContentLicense: CC BY-SA 3.0

Title: Order By 2 columns

Body:
For mysql, try this:

select item.*
from item
left join (
    select item_id, max(created_at) maxdate
    from item
    group by item_id
) t on item.item_id = t.item_id
order by t.maxdate desc, item.created_at desc

Demo1 in SQLFiddle

Demo2 in SQLFiddle


问:
Looking for a clean and efficient algorithm for checking on and off elements of a "tree" (actually a DAG)
This is not a homework.

Visually it looks like a tree, but all leafs are unique (have unique ids in database). The hierarchy above them is somewhat arbitrary. Each checkbox has 3 states: on, off, and partial. Leaves can be only checked or not checked. The state of the children should drive the state of the parents. Clicking on a checkbox should "toggle" it, and propagate the necessary changes up or down. If you click on a parent that is partially checked, it should become fully checked. Each child has a pointer to a list (I could change this to a set if I must) of parents. Each parent has a list of children sorted alphabetically. At the same time, for display purposes, this structure is a tree that I can expand and collapse, as you would see from the picture below.

I am sure this algorithm has been invented before. Since the number of leaves has been up to 20,000, I do care about the performance in practice. But, I would not try to squeeze every last drop of performance out of the algo at the expense of code being short and readable.

I figured that in principle I should walk down (if there is anywhere to go) and identify all leaves that should be changed. After that I should walk up. From the set of leaves I should figure out a set of parents that might be affected. Then filter it down to the set of parents that will need to change, and to which value. Then Add those to a set. Then I will need to walk up from those nodes and repeat. After I have a set of leaves and other nodes that need to change as well as their values, I will need to just do it ... or something like that. A matrix-based representation would be too expensive.

I am hacking this thing together in C++ using MFC, but my question is pretty much language-agnostic. I would prefer a concrete implementation to an algorithm, however. Some languages like Python, Perl, Scala might have too modern tricks up their sleeves. I would try to stick to something more conventional, like Java, C# (minus LINQ).

Code, links, references and questions are welcome.

答:
Ah, I see why this is complicated. You want to incrementally topologically sort items as you add them to the "possibly changed" list. That way, you only process elements after you've processed their children; this ensures that you only process changed elements once, and assuming you have a DAG, you will not encounter a situation where you cannot process any elements due to circular references.

So, the general algorithm goes like this:

Add all changing leaf children to the set of nodes to process.

For every node in the set that has no children to process:

Determine its new state.

If its state changed, add its parent(s) to the set of nodes to
process.

The hard part is the "every node that has no children to process". But that's just a topological sort.

ContentLicense: CC BY-SA 2.5


问:
Chained select with the second <select> preselected
There is a chained select example at http://jsfiddle.net/LZhQ8:

```<code><select id="firstSelect">
<option value="blah1">Blah1</option>
<option value="blah2">Blah2</option>
<option value="blah3">Blah3</option>
</select>

<select id="secondSelect">
</select>

var options = {
blah1: ["A", "B", "C"],
blah2: ["D", "E", "F"],
blah3: ["G", "G", "I"]
};
$(function(){
$('#firstSelect').change(function() {
    var x= $('#firstSelect :selected').val();
    $('#secondSelect').html("");
    for(index in options[x]) {
        $('#secondSelect').append('<option value="' + options[x][index] + '">' + options[x][index] + '</option>')
    };
});})
</code>```

One of the options is shown in the first  dropdown but the options for the second dropdown aren't shown until something is selected in the first.

I would like to have the options in the second dropdown already there depending on what is "selected='selected'" in the first dropdown.

Can such a thing be done?

答:
The simplest way would be to just trigger your existing change handler by chaining a call to .change() on the end (where .change() with no arguments is a shortcut for .trigger('change')):

var options = {
blah1: ["A", "B", "C"],
blah2: ["D", "E", "F"],
blah3: ["G", "G", "I"]
};
$(function(){
  $('#firstSelect').change(function() {
    var x= $('#firstSelect').val();
    $('#secondSelect').html("");
    for(index in options[x]) {
        $('#secondSelect').append('<option value="' + options[x][index] + '">' + options[x][index] + '</option>')
    };
  }).change();   // <---- ADD THIS
;})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="firstSelect">
<option value="blah1">Blah1</option>
<option value="blah2" selected>Blah2</option>
<option value="blah3">Blah3</option>
</select>

<select id="secondSelect">
</select></code>```

As an optional extra, I've changed $('#firstSelect :selected').val() to $('#firstSelect').val() because you can get the currently selected value of a (single-select) select element directly, you don't have to go via the selected option element.

Body:
There is a chained select example at http://jsfiddle.net/LZhQ8:

<select id="firstSelect">
<option value="blah1">Blah1</option>
<option value="blah2">Blah2</option>
<option value="blah3">Blah3</option>
</select>

<select id="secondSelect">
</select>

var options = {
blah1: ["A", "B", "C"],
blah2: ["D", "E", "F"],
blah3: ["G", "G", "I"]
};
$(function(){
$('#firstSelect').change(function() {
    var x= $('#firstSelect :selected').val();
    $('#secondSelect').html("");
    for(index in options[x]) {
        $('#secondSelect').append('<option value="' + options[x][index] + '">' + options[x][index] + '</option>')
    };
});})

One of the options is shown in the first  dropdown but the options for the second dropdown aren't shown until something is selected in the first.

I would like to have the options in the second dropdown already there depending on what is "selected='selected'" in the first dropdown.

Can such a thing be done?

Body:
The simplest way would be to just trigger your existing change handler by chaining a call to .change() on the end (where .change() with no arguments is a shortcut for .trigger('change')):

var options = {
blah1: ["A", "B", "C"],
blah2: ["D", "E", "F"],
blah3: ["G", "G", "I"]
};
$(function(){
  $('#firstSelect').change(function() {
    var x= $('#firstSelect').val();
    $('#secondSelect').html("");
    for(index in options[x]) {
        $('#secondSelect').append('<option value="' + options[x][index] + '">' + options[x][index] + '</option>')
    };
  }).change();   // <---- ADD THIS
;})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="firstSelect">
<option value="blah1">Blah1</option>
<option value="blah2" selected>Blah2</option>
<option value="blah3">Blah3</option>
</select>

<select id="secondSelect">
</select>

As an optional extra, I've changed $('#firstSelect :selected').val() to $('#firstSelect').val() because you can get the currently selected value of a (single-select) select element directly, you don't have to go via the selected option element.


问:
Don't understand why replace() method is not working as expected
Working on the following problem:

Create a function called alienLanguage where the input will be a str and the output should capitalize all letters except for the last letter of each word

alienLanguage("My name is John") should return "My NAMe Is JOHn"

This is what I have coded:

```<code>function alienLanguage(str){
  var words = str.toUpperCase().split(' ').map(function (a) {
    return a.replace(a[a.length - 1], a[a.length - 1].toLowerCase())
  });
  return words.join(' ');
}
</code>```

All of the example test cases work except for the following:

```<code>Expected: '\'THIs Is An EXAMPLe\'', instead got: '\'THIs Is An eXAMPLE\''
</code>```

Why is the e in eXAMPLE turning lowercase? Shouldn't everything automatically turn upperCase ?

edit: I just realized that there are 2 e's and the first one is being replaced. How can I replace the last e? and isn't the last character specified already?

答:
Instead of searching for the letter, just concatenate the uppercase part of the string up to the last letter with the lowercased last letter.

This should do the trick:

```<code>function alienLanguage(str) {
  return str.split(' ').map(function(a) {
    return a.slice(0, -1).toUpperCase() + a.slice(-1).toLowerCase();
  }).join(' ');
}
</code>```

Body:
Working on the following problem:

Create a function called alienLanguage where the input will be a str and the output should capitalize all letters except for the last letter of each word

alienLanguage("My name is John") should return "My NAMe Is JOHn"

This is what I have coded:

function alienLanguage(str){
  var words = str.toUpperCase().split(' ').map(function (a) {
    return a.replace(a[a.length - 1], a[a.length - 1].toLowerCase())
  });
  return words.join(' ');
}

All of the example test cases work except for the following:

Expected: '\'THIs Is An EXAMPLe\'', instead got: '\'THIs Is An eXAMPLE\''

Why is the e in eXAMPLE turning lowercase? Shouldn't everything automatically turn upperCase ?

edit: I just realized that there are 2 e's and the first one is being replaced. How can I replace the last e? and isn't the last character specified already?

Body:
Instead of searching for the letter, just concatenate the uppercase part of the string up to the last letter with the lowercased last letter.

This should do the trick:

function alienLanguage(str) {
  return str.split(' ').map(function(a) {
    return a.slice(0, -1).toUpperCase() + a.slice(-1).toLowerCase();
  }).join(' ');
}


答:
You don't need to split the string into words. Just use a positive lookahead assertion in your regex to upper-case all letters that are immediately followed by another letter, like this: </p>

```<code>function alienLanguage(str){
    return str.replace(/(\w)(?=\w)/g, l => l.toUpperCase())
}
</code>```

Title: Don't understand why replace() method is not working as expected

Body:
You don't need to split the string into words. Just use a positive lookahead assertion in your regex to upper-case all letters that are immediately followed by another letter, like this:

function alienLanguage(str){
    return str.replace(/(\w)(?=\w)/g, l => l.toUpperCase())
}


问:
ActionEvent button - TextField JavaFX
Hi everyone I need to create an ActionEvent from a button and put the button name on a TextField. What i have is a kind of calculator but when I press a button doesn't fills the TextField. As an example what I want: I have the numer one on a button and when I press it the number one appears on the TextField. This is what I have until now:

AppCalculator class:

```<code>package appcalculator;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class AppCalculator extends Application {

@Override
public void start(Stage stage) throws Exception {
    Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));

    Scene scene = new Scene(root);

    stage.setScene(scene);
    stage.show();
}

public static void main(String[] args) {
    launch(args);
}

}
</code>```

FXMLDocumentController:

```<code>package appcalculadora;

import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TextField;

public class FXMLDocumentController implements Initializable {

TextField texto = new TextField();

@FXML
private void btnOne(ActionEvent event) {
    texto.setText("1");

}

@FXML
private void btnTwo(ActionEvent event) {
    texto.setText("2");
}

@FXML
private void btnThree(ActionEvent event) {
    texto.setText("3");
}

@FXML
private void btnFour(ActionEvent event) {
    texto.setText("4");
}

@FXML
private void btnFive(ActionEvent event) {
    texto.setText("5");
}

@FXML
private void btnSix(ActionEvent event) {
    texto.setText("6");
}

@FXML
private void btnSevent(ActionEvent event) {
    texto.setText("7");
}

@FXML
private void btnEight(ActionEvent event) {
    texto.setText("8");
}

@FXML
private void btnNine(ActionEvent event) {
    texto.setText("9");
}

@FXML
private void btnZero(ActionEvent event) {
    texto.setText("0");
}

@FXML
private void btnPoint(ActionEvent event) {
    texto.setText(".");
}

@FXML
private void btnPlus(ActionEvent event) {
    texto.setText("+");
}

@FXML
private void btnMinus(ActionEvent event) {
    texto.setText("-");
}

@FXML
private void btnBy(ActionEvent event) {
    texto.setText("*");
}

@FXML
private void btnDivided(ActionEvent event) {
    texto.setText("/");
}

@FXML
private void btnErrase(ActionEvent event){
    texto.deletePreviousChar();
}

@FXML
private void btnTotal(ActionEvent event){
    texto.getText();
}

@Override
public void initialize(URL url, ResourceBundle rb) {
    // TODO
}

}
</code>```

And my respective FXML document

答:
```<code>public void actionPerformed(ActionEvent e) {

String x = TextFieldName.getText();
if(e.getSource() == ButtonName)
TextFieldName.setText("");
</code>```

Title: ActionEvent button - TextField JavaFX

Body:
Hi everyone I need to create an ActionEvent from a button and put the button name on a TextField. What i have is a kind of calculator but when I press a button doesn't fills the TextField. As an example what I want: I have the numer one on a button and when I press it the number one appears on the TextField. This is what I have until now:

AppCalculator class:

package appcalculator;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class AppCalculator extends Application {

@Override
public void start(Stage stage) throws Exception {
    Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));

    Scene scene = new Scene(root);

    stage.setScene(scene);
    stage.show();
}

public static void main(String[] args) {
    launch(args);
}

}

FXMLDocumentController:

package appcalculadora;

import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TextField;

public class FXMLDocumentController implements Initializable {

TextField texto = new TextField();

@FXML
private void btnOne(ActionEvent event) {
    texto.setText("1");

}

@FXML
private void btnTwo(ActionEvent event) {
    texto.setText("2");
}

@FXML
private void btnThree(ActionEvent event) {
    texto.setText("3");
}

@FXML
private void btnFour(ActionEvent event) {
    texto.setText("4");
}

@FXML
private void btnFive(ActionEvent event) {
    texto.setText("5");
}

@FXML
private void btnSix(ActionEvent event) {
    texto.setText("6");
}

@FXML
private void btnSevent(ActionEvent event) {
    texto.setText("7");
}

@FXML
private void btnEight(ActionEvent event) {
    texto.setText("8");
}

@FXML
private void btnNine(ActionEvent event) {
    texto.setText("9");
}

@FXML
private void btnZero(ActionEvent event) {
    texto.setText("0");
}

@FXML
private void btnPoint(ActionEvent event) {
    texto.setText(".");
}

@FXML
private void btnPlus(ActionEvent event) {
    texto.setText("+");
}

@FXML
private void btnMinus(ActionEvent event) {
    texto.setText("-");
}

@FXML
private void btnBy(ActionEvent event) {
    texto.setText("*");
}

@FXML
private void btnDivided(ActionEvent event) {
    texto.setText("/");
}

@FXML
private void btnErrase(ActionEvent event){
    texto.deletePreviousChar();
}

@FXML
private void btnTotal(ActionEvent event){
    texto.getText();
}

@Override
public void initialize(URL url, ResourceBundle rb) {
    // TODO
}

}

And my respective FXML document


问:
How to do on-behalf-of auth in .NET Core (missing BootstrapContext)?
I've run the on-behalf-of sample in .NET 4.5:

https://github.com/Azure-Samples/active-directory-dotnet-webapi-onbehalfof

But I need to do the same thing in .NET core.  When trying to port the sample service to .NET core everything compiles except for this line:

```<code>var bootstrapContext = ClaimsPrincipal.Current.Identities.First().BootstrapContext as System.IdentityModel.Tokens.BootstrapContext;
</code>```

It won't compile because System.IdentityModel isn't available in .NET Core.

I discovered that if I acquire the user access token and the user name using this code instead it works for users in the same tenant as the service:

```<code>System.Security.Claims.ClaimsIdentity identity =
    User.Identity as System.Security.Claims.ClaimsIdentity;
string userAccessToken = identity.BootstrapContext as string;
string userName = (User.FindFirst(ClaimTypes.Upn))?.Value;
</code>```

But for users in a different tenant (multi-tenant authentication), userAccessToken and userName are set to null.  What do I need to do differently to get this working for users coming from a different tenant?

答:
Instead of using the BootstrapContext class to get the access_token, we can use the HttpContext in the controller directly to get the orignal access_token via code below:

```<code>var orignalToken = HttpContext.Request.Headers["authorization"][0].Split(' ')[1];
</code>```

Body:
I've run the on-behalf-of sample in .NET 4.5:

https://github.com/Azure-Samples/active-directory-dotnet-webapi-onbehalfof

But I need to do the same thing in .NET core.  When trying to port the sample service to .NET core everything compiles except for this line:

var bootstrapContext = ClaimsPrincipal.Current.Identities.First().BootstrapContext as System.IdentityModel.Tokens.BootstrapContext;

It won't compile because System.IdentityModel isn't available in .NET Core.

I discovered that if I acquire the user access token and the user name using this code instead it works for users in the same tenant as the service:

System.Security.Claims.ClaimsIdentity identity =
    User.Identity as System.Security.Claims.ClaimsIdentity;
string userAccessToken = identity.BootstrapContext as string;
string userName = (User.FindFirst(ClaimTypes.Upn))?.Value;

But for users in a different tenant (multi-tenant authentication), userAccessToken and userName are set to null.  What do I need to do differently to get this working for users coming from a different tenant?

Body:
Instead of using the BootstrapContext class to get the access_token, we can use the HttpContext in the controller directly to get the orignal access_token via code below:

var orignalToken = HttpContext.Request.Headers["authorization"][0].Split(' ')[1];


问:
How to keep track of line number of big files which spans across multiple nodes?
I am reading big file using sc.textFile(file) here file is big file which spans across multiple nodes. I need the line number for my debugging and index purpose.

here as my file is divided in each node the line starts with 1 but it should be total line number from previous node +1 .

please advise me.

答:
Block quoteYou can use sc.textFile().zipWithIndex() which will add index to the file so you can track the line number
  Block quote


答:
Try it.</p>

```<code>function alienLanguage(str){
   var words = str.toUpperCase().split(' ').map(function (a) {
   return a.substr(0, a.length - 1) +a[a.length - 1].toLowerCase() + a.substr(a.length - 1 + 1);
   });
  return words.join(' ');
 }
</code>```

Body:
Try it.

function alienLanguage(str){
   var words = str.toUpperCase().split(' ').map(function (a) {
   return a.substr(0, a.length - 1) +a[a.length - 1].toLowerCase() + a.substr(a.length - 1 + 1);
   });
  return words.join(' ');
 }


问:
Trying to build Mozilla got this error when trying to open start-shell-msvc2015
I am trying to build Mozilla on Windows 7 64bit

I tried to run this start-shell-msvc2015.bat but got this error.

MozillaBuild Install Directory: C:\mozilla-build\
Visual C++ 2015 Directory: C:\Program Files (x86)\Microsoft Visual Studio 14.0\V
C\
Windows SDK Directory: C:\Program Files (x86)\Windows Kits\8.1\

Unable to call a suitable vcvars script. Exiting.

Press any key to continue . . .

I did everything according to their instructions

答:
When in doubt, search Google for the error message. From the first result:

Hallvord R. M. Steen:
  To anybody else who might have this problem: it's caused by choices made during installation, and the installer options were somewhat confusing. I don't remember the exact details, but I think the "Default" installation no longer gives you the required scripts - the "Default vs custom" section on https://msdn.microsoft.com/en-us/library/e2h7fzkw%28v=vs.140%29.aspx seems to confirm that you need to choose "Custom" during install and enable Visual C++ tools specifically.

Andrew Overholt: You're right, Hallvord. I went back to my VS2015 installation .exe download, clicked "Modify [the existing installation]" and picked "Common Tools for Visual C++ 2015" under "Programming Languages" > "Visual C++".

Also you'll need at least update 3 if you're using the VS2015 Community Edition. From that Mozilla dev docs page:

Once you’re up to date, download and install Visual Studio Community 2015 Update 3 from Microsoft. If you have an earlier version of Visual Studio, you'll need to upgrade; Firefox relies on C++ features that aren't supported in older versions of Visual Studio. Do not accept the default configuration. Instead, select **Programming Languages > Visual C++ > Common Tools for Visual C++ 2015.*

See also this question on Super User.

Furthermore, the MDN docs actually were updated with this info after that report, and indeed the current build instructions contain, in bold:

Be sure to install the "Common Tools for Visual C++ 2015", which requires a customized installation in Visual Studio 2015.

In the prerequisites section.

Also you'll need at least update 3 if you're using the VS2015 Community Edition. From that Mozilla dev docs page:

Once you’re up to date, download and install Visual Studio Community 2015 Update 3 from Microsoft. If you have an earlier version of Visual Studio, you'll need to upgrade; Firefox relies on C++ features that aren't supported in older versions of Visual Studio. Do not accept the default configuration. Instead, select Programming Languages > Visual C++ > Common Tools for Visual C++ 2015.


问:
Inequalities as python parameters
Firstly, Sry fo the bad title of this question I simply don't know a better one.
If you have a better one => Tell me!

So my problem is that I would like to write a simplex solver in Python by myself to deeply understand how they work.

Therefore, I would like to have something like this in my program:

```<code> m.addConstr(x[0] <= 7)
</code>```

Which basically should add a constraint to my model m.
This works in Gurobi which is just wonderful cause it's so easy to read.
The problem is that x[0] has to be an object where I itself can define what should happen when there is an inequality or equality or whatever, right?

I am happy to figure out most of the stuff by myself would just like to get an idea how this works.

答:
It looks like you want to overload the comparison operators of whatever objects you're working with. So if Foo is the class of x[0] in your example, then you could write it like this:

```<code>class Foo:
    def __gt__(self, other):
        # construct and return some kind of constraint object

    def __lt__(self, other):
        # likewise
</code>```

These special methods (__gt__, __ge__, __lt__, __le__, __ne__ and __eq__) are called for the left-hand object in a comparison relation. So if you have x > y, then the __gt__ method on x is called with y as an argument.

Title: Inequalities as python parameters

Body:
Firstly, Sry fo the bad title of this question I simply don't know a better one.
If you have a better one => Tell me!

So my problem is that I would like to write a simplex solver in Python by myself to deeply understand how they work.

Therefore, I would like to have something like this in my program:

 m.addConstr(x[0] <= 7)

Which basically should add a constraint to my model m.
This works in Gurobi which is just wonderful cause it's so easy to read.
The problem is that x[0] has to be an object where I itself can define what should happen when there is an inequality or equality or whatever, right?

I am happy to figure out most of the stuff by myself would just like to get an idea how this works.

Body:
It looks like you want to overload the comparison operators of whatever objects you're working with. So if Foo is the class of x[0] in your example, then you could write it like this:

class Foo:
    def __gt__(self, other):
        # construct and return some kind of constraint object

    def __lt__(self, other):
        # likewise

These special methods (__gt__, __ge__, __lt__, __le__, __ne__ and __eq__) are called for the left-hand object in a comparison relation. So if you have x > y, then the __gt__ method on x is called with y as an argument.


问:
understanding the creation of the array of lists in python
I was reading about how to declare a matrices in python and I find this question How to define two-dimensional array in python

It's work with me, but I understanding what was done here in part, what I don't understanding is the parameter before the "for" in both loops...So I going to my terminal and testing parts of this for one by one, so when I type:

```<code>0 for x in range(w):
</code>```

I receive:

File "< stdin >", line 1

So I try:

```<code>[0 for x in range(w)] for y in range(h):
</code>```

receive:

File "< stdin >", line 1
      [0 for x in range(w)] for y in range(h):

So I try:

```<code>[0 for x in range(w)]
</code>```

and

```<code>[[0 for x in range(w)] for y in range(h)]
</code>```

and it's work...

So why the loop works when I put the brackets and not work without the brackets?

Thanks in advance.

答:
It is list comprehension in python. And similar, there is also set comprehension, dict comprehension. It uses the elements in for loop to construct the list. Such as

```<code>>>> [2*i for i in range(10)]
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
>>> [i for i in range(10) if i % 2 == 1]
[1, 3, 5, 7, 9]
>>> [0 for _ in range(10)]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
>>> [[i for i in range(j)] for j in range(5)]
[[], [0], [0, 1], [0, 1, 2], [0, 1, 2, 3]]
>>> {i : chr(65+i) for i in range(5)}
{0: 'A', 1: 'B', 2: 'C', 3: 'D', 4: 'E'}
</code>```

https://www.python.org/dev/peps/pep-0202/

https://www.python.org/dev/peps/pep-0274/

Body:
I was reading about how to declare a matrices in python and I find this question How to define two-dimensional array in python

It's work with me, but I understanding what was done here in part, what I don't understanding is the parameter before the "for" in both loops...So I going to my terminal and testing parts of this for one by one, so when I type:

0 for x in range(w):

I receive:

File "< stdin >", line 1

So I try:

[0 for x in range(w)] for y in range(h):

receive:

File "< stdin >", line 1
      [0 for x in range(w)] for y in range(h):

So I try:

[0 for x in range(w)]

and

[[0 for x in range(w)] for y in range(h)]

and it's work...

So why the loop works when I put the brackets and not work without the brackets?

Thanks in advance.

Body:
It is list comprehension in python. And similar, there is also set comprehension, dict comprehension. It uses the elements in for loop to construct the list. Such as

>>> [2*i for i in range(10)]
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
>>> [i for i in range(10) if i % 2 == 1]
[1, 3, 5, 7, 9]
>>> [0 for _ in range(10)]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
>>> [[i for i in range(j)] for j in range(5)]
[[], [0], [0, 1], [0, 1, 2], [0, 1, 2, 3]]
>>> {i : chr(65+i) for i in range(5)}
{0: 'A', 1: 'B', 2: 'C', 3: 'D', 4: 'E'}

https://www.python.org/dev/peps/pep-0202/

https://www.python.org/dev/peps/pep-0274/


问:
SQL Server Express replication
Is it possible to replicate or mirror one database from SQL Server Express to SQL Server ?</p>

答:
TechNet Link

SQL Server Express cannot serve as a Publisher or Distributor.
  However, merge replication allows changes to be replicated in both
  directions between a Publisher and Subscriber. SQL Server Express does
  not include SQL Server Agent, which is typically used to run
  replication agents.

but what you can do is impose a replication process, create a trigger that will insert or update your replicated server

Title: SQL Server Express replication


问:
Limiting Output of Knapsack Algorithm to specified bit-size
Currently, my professor has given a group assignment that requires us to take values from a simulated ECG scan and Quantize them to 8-bit values. From there we are to take the 8-bit values and run them through a knapsack encryption algorithm.

I have no problem with the coding, but rather a question of the Knapsack itself.

We are using a Super-increasing key to create our general key. We are supposed to come up with the SIK, m and n values. In this case I picked { 1, 2, 5, 9, 22, 43, 118, 207 } to be my SIK, since we are just using 8 bits. Also, my n=19, and my m=511 (i.e. 19*(whatever)mod511).

This generates the resulting General Knapsack:
{19, 38, 95, 171, 418, 306, 198, 356}

The problem comes when I encrypt a value. Say I encrypt something like 10010111
The resulting value would be 1050 (in decimal). Putting this value back into my Quantizer would be a problem, considering it is designed to turn decimal values into 8 bits binary, and this gives a 10-bit number.

So I played around with the values, changing the SIK to the smallest values possible and different variations of m and n, and still I get encrypted values that are greater than 8 bits.

Essentially my question is this: Is there a value for m and n that I could use that would generate values in the desired bit range (8-bits), or is it mathematically impossible? The professor said he wasn't sure if it was possible, but he thought it was.

I could convert the Quantizer to be able to take larger amount of bits, but was just curious to see if what he was asking was even possible.

答:
"Is there a value for m and n that I could use that would generate values in the desired bit range (8-bits), or is it mathematically impossible?"

Can't prove it impossible, but I will say from a practical point of view, it's not going to work.  Here's why.

Because of the super increasing property, each element being at least double the previous implies that the 8th element has to be >= 2^8 = 256.  As a consequence, your modulus m needs to be larger than 256, which is 9-bits.

Now for this to work, you need to find a value of n such that any subset sum of the generated knapsack to be at most 8-bits (255 is the largest value).  The worst case is 11111111, where all numbers are added together.  The elements in your generated knapsack are all on the same order as your modulus, which is at least 9-bits.  So you're looking at adding 8 elements that are only the order of 9-bits in hope that the total sum is 8-bits.  True, I haven't proven it impossible, but I hope it gives you a feeling for why this is unlikely to happen.


问:
How to fill in NA values with grouped means in R
Say I have a df that looks like:

```<code>rat  let num
1     A   3
3     c   12
3     B   41
1     B   NA
1     A   NA
2     B   2
2     C   20
1     C   NA
2     A   33
3     C   10
</code>```

I would like to group_by 'rat' and 'let' and get the mean of 'num' for each group and use that to fill in the NA values.

I have done the grouping and got the mean but don't know how to apply the values to fill in the NA values in my original df. Different methods would be greatly appreciated! Thanks.

```<code>df %>% group_by(rat,let) %>% summarise(num_avg = mean(num,na.rm=T))
</code>```

答:
Here is one option with ave and na.aggregate from zoo

```<code>library(zoo)
df$num <- with(df, ave(num, rat, let, FUN = na.aggregate))
</code>```

Body:
Say I have a df that looks like:

rat  let num
1     A   3
3     c   12
3     B   41
1     B   NA
1     A   NA
2     B   2
2     C   20
1     C   NA
2     A   33
3     C   10

I would like to group_by 'rat' and 'let' and get the mean of 'num' for each group and use that to fill in the NA values.

I have done the grouping and got the mean but don't know how to apply the values to fill in the NA values in my original df. Different methods would be greatly appreciated! Thanks.

df %>% group_by(rat,let) %>% summarise(num_avg = mean(num,na.rm=T))

Body:
Here is one option with ave and na.aggregate from zoo

library(zoo)
df$num <- with(df, ave(num, rat, let, FUN = na.aggregate))


答: You are looking at a list comprehension(please look over 5.1.4. Nested List Comprehensions of the link). The same task may be achieved using generator expression which does not involve brackets, but a generator does not create a list.</p>

Title: understanding the creation of the array of lists in python


问:
Selenium Webdriver not clicking on element
I am setting up webdrivers to scrape reporting numbers from a couple of sites I use at work. All of them are password protected which hasn't been a problem until now. Here is the login screen I am trying to interact with:

https://ssp.vertamedia.com/

I am using the Selenium webdriver with Python 3.6 in Firefox.

With this site, the webdriver needs to input the user name, then interact with the "next" button before the password input and submit button are visible. I am able to fill in the username, but so far have not been able to get the webdriver to interact with the "next" button.

Below is a snippet of the button html from the site:

```<code><a class="x-btn attached-btn blue x-unselectable x-box-item x-btn-attached-btn-small x-item-disabled x-btn-disabled" style="height: 40px; right: auto; left: 282px; top: 0px; margin: 0px;" hidefocus="on" unselectable="on" role="button" aria-hidden="false" aria-disabled="true" id="button-1021" data-componentid="button-1021">
    <span id="button-1021-btnWrap" data-ref="btnWrap" role="presentation" unselectable="on" style="" class="x-btn-wrap x-btn-wrap-attached-btn-small ">
        <span id="button-1021-btnEl" data-ref="btnEl" role="presentation" unselectable="on" style="height:auto;" class="x-btn-button x-btn-button-attached-btn-small x-btn-text    x-btn-button-center ">
            <span id="button-1021-btnIconEl" data-ref="btnIconEl" role="presentation" unselectable="on" class="x-btn-icon-el x-btn-icon-el-attached-btn-small  " style=""></span>
            <span id="button-1021-btnInnerEl" data-ref="btnInnerEl" unselectable="on" class="x-btn-inner x-btn-inner-attached-btn-small">next</span>
        </span>
    </span>
</a>
</code>```

I have tried using class name, id, and css Selector and so far haven't been successful. Below is the python snippet:

```<code>def exe(self):
    browser = webdriver.Firefox()
    wait = WebDriverWait(browser, 15)
    yesterday = date.today() - timedelta(1)
    browser.get("https://ssp.vertamedia.com")

    try:
        userElement = wait.until(EC.visibility_of_element_located((By.ID,'textfield-1020-inputEl')))
        userElement.send_keys(self.cred.pop('User'))
        browser.find_element_by_id('button-1021').click()
        passElement = wait.until(EC.visibility_of_element_located((By.ID, 'textfield-1027-inputEl')))
        passElement.send_keys(self.cred.pop('Password'))
        browser.find_element_by_id('button-1028').click()

    except TimeoutException:
        self.cred['Impression'] = "Login error"
        self.cred['Revenue'] = "Login error"
        self.cred['Date'] = yesterday.strftime('%m%d%y')
</code>```

Essentially when it hits the passElement section where I am inputting the password, it hits an "Element is not visible" error.

Any suggestions on how to get it to interact with the next button would be appreciated!

答:
You should avoid using time.sleep(), and use WebDriverWait which let you wait for certain condition to occur before proceeding further :

```<code>from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

def exe():
    browser = webdriver.Firefox()
    wait    = WebDriverWait(driver, 10)
    browser.get("https://ssp.vertamedia.com")
    try:
        userElement = browser.find_element_by_id('textfield-1020-inputEl')
        userElement.send_keys(self.cred.pop('User'))
        browser.find_element_by_id('button-1021').click()
        passElement = wait.until(EC.visibility_of_element_located((By.ID,'textfield-1027-inputEl'))
        passElement.send_keys(self.cred.pop('Password'))
        browser.find_element_by_id('button-1028').click()
        time.sleep(10)  #Change this to WebDriverWait as well
</code>```

You can learn more about selenium waits here : http://selenium-python.readthedocs.io/waits.html

Body:
I am setting up webdrivers to scrape reporting numbers from a couple of sites I use at work. All of them are password protected which hasn't been a problem until now. Here is the login screen I am trying to interact with:

https://ssp.vertamedia.com/

I am using the Selenium webdriver with Python 3.6 in Firefox.

With this site, the webdriver needs to input the user name, then interact with the "next" button before the password input and submit button are visible. I am able to fill in the username, but so far have not been able to get the webdriver to interact with the "next" button.

Below is a snippet of the button html from the site:

            next

I have tried using class name, id, and css Selector and so far haven't been successful. Below is the python snippet:

def exe(self):
    browser = webdriver.Firefox()
    wait = WebDriverWait(browser, 15)
    yesterday = date.today() - timedelta(1)
    browser.get("https://ssp.vertamedia.com")

    try:
        userElement = wait.until(EC.visibility_of_element_located((By.ID,'textfield-1020-inputEl')))
        userElement.send_keys(self.cred.pop('User'))
        browser.find_element_by_id('button-1021').click()
        passElement = wait.until(EC.visibility_of_element_located((By.ID, 'textfield-1027-inputEl')))
        passElement.send_keys(self.cred.pop('Password'))
        browser.find_element_by_id('button-1028').click()

    except TimeoutException:
        self.cred['Impression'] = "Login error"
        self.cred['Revenue'] = "Login error"
        self.cred['Date'] = yesterday.strftime('%m%d%y')

Essentially when it hits the passElement section where I am inputting the password, it hits an "Element is not visible" error.

Any suggestions on how to get it to interact with the next button would be appreciated!

Body:
You should avoid using time.sleep(), and use WebDriverWait which let you wait for certain condition to occur before proceeding further :

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

def exe():
    browser = webdriver.Firefox()
    wait    = WebDriverWait(driver, 10)
    browser.get("https://ssp.vertamedia.com")
    try:
        userElement = browser.find_element_by_id('textfield-1020-inputEl')
        userElement.send_keys(self.cred.pop('User'))
        browser.find_element_by_id('button-1021').click()
        passElement = wait.until(EC.visibility_of_element_located((By.ID,'textfield-1027-inputEl'))
        passElement.send_keys(self.cred.pop('Password'))
        browser.find_element_by_id('button-1028').click()
        time.sleep(10)  #Change this to WebDriverWait as well

You can learn more about selenium waits here : http://selenium-python.readthedocs.io/waits.html


问:
What does $ sign at the end of function name indicate?
Here is the code I'm reviewing...</p>

```<code>import { Observable } from 'rxjs/Rx';
// reducer
import { playerRegister, PlayerState } from './player';
export function getPlayer$ (state$: Observable<MyAppState>): Observable<PlayerState> {
  return state$.select(state => state.player);
};
</code>```

答: I'm not sure if it's used more widely than within the RxJS community, but within this community it's commonly used to indicate that a variable is a stream (i.e. an Observable) or that a function returns such a stream.</p>

ContentLicense: CC BY-SA 4.0

Body:
Here is the code I'm reviewing...

import { Observable } from 'rxjs/Rx';
// reducer
import { playerRegister, PlayerState } from './player';
export function getPlayer$ (state$: Observable<MyAppState>): Observable<PlayerState> {
  return state$.select(state => state.player);
};


问:
Java Time API converting ISO 8601 to ZonedDateTime
I am having a hard time converting an ISO 8601 formatted String to a java.time.LocalDateTime which is in UTC.

More specific, I am trying to write an XMLAdapter for which you can enter the various ISO 8601 dataformats as a String (i.e. 2002-09-24, 2011-03-22T13:30, 2015-05-24T12:25:15Z, 2015-07-28T11:11:15.321+05:30) and which outputs a LocalDateTime in UTC and visa versa.

The system stores all it's Date and Time information internal in UTC times. When a user requests a Date or Time it is represented to the user based on their own ZoneId.

答:
tl;dr

```<code>Instant.parse( "2015-05-24T12:25:15Z" )
       .atZone(
           ZoneId.of( "America/Montreal" )
       )
       .toString()
</code>```

2015-05-24T08:25:15-04:00[America/Montreal]

ZonedDateTime vs LocalDateTime

Your Question contradicts itself, with the title asking for a ZonedDateTime and the body asking for a LocalDateTime. Those are two very different beasts. One (ZonedDateTime) is a specific moment on the timeline, the other (LocalDateTime) is only a vague idea about possible moments but is not a specific moment.

For example, the LocalDateTime of Christmas starting this year is 2017-12-25T00:00:00 but that has no meaning until you apply a time zone as Santa delivers first to the islands of Kiribati at their midnight (the first midnight on Earth), then on to New Zealand at their later midnight, then on to Australia at their later midnight, and so on moving westward toward successive midnights.

Also, you Question seems confused about exactly what is the input and what is the output.

a java.time.LocalDateTime which is in UTC.

This is a contradiction in terms. The LocalDateTime class lacks any concept of time zone or offset-from-UTC. So this class cannot be used to represent a moment such as a UTC value. For a moment in UTC, use either Instant or OffsetDateTime classes.

Instant

For an input like 2015-05-24T12:25:15Z, that represents a moment on the timeline in UTC (Z is short for Zulu and means UTC). To represent that, use the Instant class. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

```<code>Instant instant = Instant.parse( "2015-05-24T12:25:15Z" );
</code>```

Generally you should be working in UTC for most business logic, data storage, data exchange, and database. So for that Instant is all you need.

ZonedDateTime

If you need to adjust into a time zone, such as for presentation to a user, apply a ZoneId to get a ZonedDateTime.

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

```<code>ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );
</code>```

LocalDate

If you have a date-only value, parse as a LocalDate object.

```<code>LocalDate localDate = LocalDate.parse( "2002-09-24" );
</code>```

To get the first moment of the day for that date, specify a time zone. For any given moment, the date varies around the world by zone.

Also, do not assume the day starts at the time of 00:00:00. Anomalies such as Daylight Saving Time (DST) may cause the first moment to be something like 01:00:00. Let java.time determine the first moment’s time-of-day.

```<code>ZonedDateTime zdt = localDate.atStartOfDay( z );
</code>```

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

Java SE 8, Java SE 9, Java SE 10, and later

Built-in.

Part of the standard Java API with a bundled implementation.

Java 9 adds some minor features and fixes.

Java SE 6 and Java SE 7

Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.

Android

Later versions of Android bundle implementations of the java.time classes.

For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Body:
tl;dr

Instant.parse( "2015-05-24T12:25:15Z" )
       .atZone(
           ZoneId.of( "America/Montreal" )
       )
       .toString()

2015-05-24T08:25:15-04:00[America/Montreal]

ZonedDateTime vs LocalDateTime

Your Question contradicts itself, with the title asking for a ZonedDateTime and the body asking for a LocalDateTime. Those are two very different beasts. One (ZonedDateTime) is a specific moment on the timeline, the other (LocalDateTime) is only a vague idea about possible moments but is not a specific moment.

For example, the LocalDateTime of Christmas starting this year is 2017-12-25T00:00:00 but that has no meaning until you apply a time zone as Santa delivers first to the islands of Kiribati at their midnight (the first midnight on Earth), then on to New Zealand at their later midnight, then on to Australia at their later midnight, and so on moving westward toward successive midnights.

Also, you Question seems confused about exactly what is the input and what is the output.

a java.time.LocalDateTime which is in UTC.

This is a contradiction in terms. The LocalDateTime class lacks any concept of time zone or offset-from-UTC. So this class cannot be used to represent a moment such as a UTC value. For a moment in UTC, use either Instant or OffsetDateTime classes.

Instant

For an input like 2015-05-24T12:25:15Z, that represents a moment on the timeline in UTC (Z is short for Zulu and means UTC). To represent that, use the Instant class. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

Instant instant = Instant.parse( "2015-05-24T12:25:15Z" );

Generally you should be working in UTC for most business logic, data storage, data exchange, and database. So for that Instant is all you need.

ZonedDateTime

If you need to adjust into a time zone, such as for presentation to a user, apply a ZoneId to get a ZonedDateTime.

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );

LocalDate

If you have a date-only value, parse as a LocalDate object.

LocalDate localDate = LocalDate.parse( "2002-09-24" );

To get the first moment of the day for that date, specify a time zone. For any given moment, the date varies around the world by zone.

Also, do not assume the day starts at the time of 00:00:00. Anomalies such as Daylight Saving Time (DST) may cause the first moment to be something like 01:00:00. Let java.time determine the first moment’s time-of-day.

ZonedDateTime zdt = localDate.atStartOfDay( z );

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

Java SE 8, Java SE 9, Java SE 10, and later

Built-in.

Part of the standard Java API with a bundled implementation.

Java 9 adds some minor features and fixes.

Java SE 6 and Java SE 7

Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.

Android

Later versions of Android bundle implementations of the java.time classes.

For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.


问:
reset uncontrolled component content after submitting the form + react + jsx
I have a already built React form, which works fine expect reset functionality. It has used uncontrolled components bit different way. I am looking for what I need to follow, change the code to achieve my goal.

import * as React from "react";
import WidgetComponent from './../../lib/WidgetComponent';
import jQuery from 'jquery';

import InputListComponent from './components/InputListComponent';
import FormInputComponent from './components/FormInputComponent';
import formTextInputComponent from './components/formTextInputComponent';

import FormInputPasswordComponent from './components/FormInputPasswordComponent';
import FormSelectComponent from './components/FormSelectComponent';
import SubmitBtnListComponent from './components/SubmitBtnListComponent';
import SubmitBtnComponent from './components/SubmitBtnComponent';
import ErrorListBox from './components/ErrorListBox';
import EmailPromptModal from './components/EmailPromptModal';

import formHandlerInterfaceFactory from './lib/formHandlerInterface';
import formValidator from './lib/formValidators';
import {generateJQueryAjaxConfigFromPlaceholders} from './../../lib/GenerateJQueryAjaxConfig';

import './styles/registration-form.scss';

export default class ControlPanelCreateAccounts extends WidgetComponent {
    constructor(props) {
        super(props);

        this.state = {
            form: {
                firstName: "",
                lastName: "",
                username: "",
                password: "",
                confirmPassword: "",
                email: "",
                phone: "",
                accessLevel: -1,

            },
            userRoles: [],

            validInputs: {
                firstName: false,
                lastName: false,
                username: false,
                password: false,
                confirmPassword: false,
                email: false,
                phone: false,
                accessLevel: false,

            },
            defaultValue: {
                firstName: "",
                lastName: "",
                username: "",
                password: "",
                confirmPassword: "",
                email: "",
                phone: "",
                accessLevel: -1,
            },
            errors: [],
            submitService: null,
            userRoleService: null,
            newUserId: null,
        };

        this.onFormInputChange = this.onFormInputChange.bind(this);
        this.onServicesCalled = this.onServicesCalled.bind(this);
        this.onFormSubmit = this.onFormSubmit.bind(this);
        this.formElementInvalid = this.formElementInvalid.bind(this);
        this.formElementValid = this.formElementValid.bind(this);
        this.postWidgetLoad = this.postWidgetLoad.bind(this);
        this.createUserRequest = this.createUserRequest.bind(this);
        this.createUserRoleRequest = this.createUserRoleRequest.bind(this);
        this.onResetReceived = this.onResetReceived.bind(this);
        this.onFormInputReset = this.onFormInputReset.bind(this);

    }

    onResetReceived(){
        console.log('onResetReceived');
        let newState = Object.assign(this.state.form, {
            firstName : "",
        });

        this.setState(newState);
        console.log(this.state.form);

    }

    postWidgetLoad(widget) {
        EmailPromptModal.service = widget.services[2];//??
        let submitService = widget.services[1];//1
        let userRoleService = widget.services[2];//2
        //this.storeState({ submitService });
        let newState = Object.assign(this.state, {
            submitService: submitService,
            userRoleService: userRoleService
        });

        this.setState(newState);
    }

    validate() {
        console.log('validating pre-submit');
        let errors = Object.keys(this.state.validInputs).reduce((accum, current) => {
            console.log('state of accumulator is: ');
            console.log(accum);
            console.log('current iteration is: ' + current);

            //console.log('password and reType passwords are : ');
            //console.log(this.state.form.password + " :: " + this.state.confirmPassword );

            if (this.state.validInputs[current] === false) {
                console.log('current input is invalid');
                this.validate = this.validate.bind(this);
                if (current === 'firstName') {
                    accum.push('The first name field is either empty or contains invalid characters');
                }

                if (current === 'lastName') {
                    accum.push('The last name field is either empty or contains invalid characters');
                }

                if (current === 'email') {
                    accum.push('The email field is empty or is not a valid email address');
                }

                if (current === 'phone') {
                    accum.push('The phone field is empty or is not a valid phone number');
                }

                if (current === 'password') {
                    accum.push('The password field is empty or contain less than 5 characters or contain invalid character');
                }

                if (current === 'confirmPassword') {
                    accum.push('The passwords mismatched');
                }

                if (current === 'accessLevel') {
                    accum.push('You must select a accessLevel from the drop-down menu.');
                }
            }

            return accum;
        }, []);

        console.log('final error list looks like: ');
        console.log(errors);

        this.storeState({
            errors: errors
        });

        return errors.length === 0;
    }

    onServicesCalled() {
        let response = arguments[0][0].data;
        let roleList = [];

        if (response) {
            response.map(element => {
                roleList.push({val: element.id, text: element.role_name});
            });
        }

        let newState = Object.assign(this.state, {
            userRoles: roleList
        });

        this.setState(newState);
    }

    onFormInputChange(ev, legend) {
        let value = ev.target.value;
        let form = this.state.form;
        form[legend] = value;
        this.storeState({
            form
        });

    formElementInvalid(elem) {
        let name = elem.name;
        let stateUpdateObj = this.state.validInputs;
        stateUpdateObj[name] = false;
        this.storeState({validInputs: stateUpdateObj});

        if (name !== 'status') {
            elem.classList.add('input-error');
        } else {
            document.getElementById('status-error-field').classList.add('visible');
        }
    }

    formElementValid(elem) {
        let name = elem.name;
        let stateUpdateObj = this.state.validInputs;
        stateUpdateObj[name] = true;
        this.storeState({validInputs: stateUpdateObj});

        if (name !== 'status') {
            elem.classList.remove('input-error');
        } else {
            document.getElementById('status-error-field').classList.remove('visible');
        }
    }

    onFormSubmit() {

        if (this.validate()) {
            console.log("validate got passed");
            console.log(this.state.form);
            var id;

            // match password fields
            if (this.state.form.password !== this.state.form.confirmPassword) {
                let stateUpdateObj = this.state.validInputs;
                stateUpdateObj['confirmPassword'] = false;
                this.storeState({validInputs: stateUpdateObj});
                this.onFormSubmit();

            } else {
                jQuery.when(this.createUserRequest()).done((r) => {

                    console.log("submit for createUser is success reload!");
                    console.log(r);

                    id = r.data.id;

                    jQuery.when(this.createUserRoleRequest(id)).done((r) => {

                        console.log("submit for createUserRole is success reload!");
                        console.log(r);

                        if(r.data.wasSuccessful){
                            console.log("create UserRole is successful, So reload the table ");
                            // do page refresh here
                            window.pubsub.publish('isp.reload-control-users', {});

                            //reset the form
                            console.log("reset the form contents");
                            this.onResetReceived();

                        }

                    }).fail((xhr, status, error) => {
                        console.log(status);
                        console.error(error);
                        alert('An error occured while submitting this request, if this issue persists please contact support.');
                    });

                    let newState = Object.assign(this.state, {
                        newUserId: r.data.id
                    });

                    this.setState(newState);

                }).fail((xhr, status, error) => {
                    console.log(status);
                    console.error(error);
                    alert('An error occured while submitting this request, if this issue persists please contact support.');
                });

            }

        }
    }

    //create a record in is_auth_roles table
    createUserRoleRequest(id) {

        let config = generateJQueryAjaxConfigFromPlaceholders(this.state.userRoleService, {'userId': id});

        config.headers['Content-Type'] = 'application/json';
        config.headers['Accept'] = '*/*';
        config.data = JSON.stringify({
            'roleId': this.state.form.accessLevel,
            'type': 'add'
        });
        console.log("submit config of createUserRoleRequest() is: ");
        console.log(config);

        return jQuery.ajax(config);

    }

    createUserRequest() {
        let config = generateJQueryAjaxConfigFromPlaceholders(this.state.submitService, {});

        config.headers['Content-Type'] = 'application/json';
        config.headers['Accept'] = '*/*';
        config.data = JSON.stringify({
            firstName: this.state.form.firstName,
            lastName: this.state.form.lastName,
            username: this.state.form.username,
            phone: this.state.form.phone,
            password: this.state.form.password,
            confirmPassword: this.state.form.confirmPassword,
            email: this.state.form.email,
            accessLevel: this.state.accessLevel

        });

        console.log("submit config is: ");
        console.log(config);

        return jQuery.ajax(config);
    }

    render() {
            return (

 User  Registration

                <InputListComponent>
                                        {/*onValid={this.formElementValid} />*/}
                    <formTextInputComponent legend="firstName" label="First Name" placeholder="First Name" onChange={this.onFormInputChange} validator={formValidator.nameValidator} onInvalid={this.formElementInvalid} default = {this.state.defaultValue.firstName} value={ this.state.value}
                                        onValid={this.formElementValid} />

                    <FormInputComponent legend="lastName" label="Last Name" placeholder="Last Name" onChange={this.onFormInputChange} validator={formValidator.nameValidator} onInvalid={this.formElementInvalid} default = {this.state.defaultValue.lastName}
                                        onValid={this.formElementValid}/>
                    <FormInputComponent legend="username" label="User Name" placeholder="User Name" onChange={this.onFormInputChange} validator={formValidator.nameValidator} onInvalid={this.formElementInvalid} default = {this.state.defaultValue.username}
                                        onValid={this.formElementValid}/>
                    <FormInputPasswordComponent legend="password" label="Password" placeholder="Password" onChange={this.onFormInputChange} validator={formValidator.passwordValidator} onInvalid={this.formElementInvalid} default = {this.state.defaultValue.password}
                                                onValid={this.formElementValid}/>
                    <FormInputPasswordComponent legend="confirmPassword" label="Confirm Password" placeholder="Confirm Password" onChange={this.onFormInputChange} validator={formValidator.passwordValidator} default = {this.state.defaultValue.confirmPassword}
                                                onInvalid={this.formElementInvalid} onValid={this.formElementValid}/>
                    <FormInputComponent legend="email" label="Email Address" placeholder="Email" onChange={this.onFormInputChange} validator={formValidator.emailValidator} onInvalid={this.formElementInvalid} default = {this.state.defaultValue.email}
                                        onValid={this.formElementValid}/>
                    <FormInputComponent legend="phone" label="Phone Number" placeholder="Phone Number" onChange={this.onFormInputChange} validator={formValidator.phoneValidator} onInvalid={this.formElementInvalid} default = {this.state.defaultValue.phone}
                                        onValid={this.formElementValid}/>
                    <FormSelectComponent legend="accessLevel" data={this.state.userRoles} onChange={this.onFormInputChange} validator={formValidator.statusValidator} onInvalid={this.formElementInvalid} default = {this.state.defaultValue.accessLevel}
                                         onValid={this.formElementValid}/>
                </InputListComponent>

                <ErrorListBox errorList={this.state.errors}/>
                <button className="dataTable-modal-btn click-btn" onClick={this.onFormSubmit}>CREATE USER</button>

        );
    }
}
window.ControlPanelCreateAccounts = ControlPanelCreateAccounts;
window.CurrentWidget = window.ControlPanelCreateAccounts;```
</div>
</div>
</p>

<p>this is formInputComponent code</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
const FormInputComponent = (props) => {

    const onChangeHandler = (ev) => {
        if(props.validator(ev.target.value)) {
            props.onChange(ev, props.legend);
            props.onValid(ev.target);
        } else {
            props.onInvalid(ev.target);
        }
    };

    console.log('props.defaultValue');
    console.log(props.legend);
    console.log(props.default);
    console.log(props.value);
    return (
        <div className="form-row">
            <label>{props.label}</label><br />
            <input name={props.legend} type="text" placeholder={props.placeholder} onChange={onChangeHandler} defaultValue={props.default || ''} value={props.value}/>
        </div>
    );
};

FormInputComponent.propTypes = {
    legend: React.PropTypes.string,
    label: React.PropTypes.string,
    placeholder: React.PropTypes.string,
    onChange: React.PropTypes.func,
    validator: React.PropTypes.func,
    onInvalid: React.PropTypes.func,
    onValid: React.PropTypes.func,
    default: React.PropTypes.string,
};

export default FormInputComponent;</code>```

答:
If you want setState inside of onResetReceived to reset the form, you'll need to set the value prop of each form field. The default prop gets sent to FormInputComponent as the defaultValue of the input, but you can also see it accepts a value={props.value} as well (even though value is not defined in its PropTypes. From the parent set

```<code><FormInputComponent value={this.state.form.firstName} ... />
</code>```

This will ensure changing this.state.form via setState will update each form field.

Body:
I have a already built React form, which works fine expect reset functionality. It has used uncontrolled components bit different way. I am looking for what I need to follow, change the code to achieve my goal.

import * as React from "react";
import WidgetComponent from './../../lib/WidgetComponent';
import jQuery from 'jquery';

import InputListComponent from './components/InputListComponent';
import FormInputComponent from './components/FormInputComponent';
import formTextInputComponent from './components/formTextInputComponent';

import FormInputPasswordComponent from './components/FormInputPasswordComponent';
import FormSelectComponent from './components/FormSelectComponent';
import SubmitBtnListComponent from './components/SubmitBtnListComponent';
import SubmitBtnComponent from './components/SubmitBtnComponent';
import ErrorListBox from './components/ErrorListBox';
import EmailPromptModal from './components/EmailPromptModal';

import formHandlerInterfaceFactory from './lib/formHandlerInterface';
import formValidator from './lib/formValidators';
import {generateJQueryAjaxConfigFromPlaceholders} from './../../lib/GenerateJQueryAjaxConfig';

import './styles/registration-form.scss';

export default class ControlPanelCreateAccounts extends WidgetComponent {
    constructor(props) {
        super(props);

        this.state = {
            form: {
                firstName: "",
                lastName: "",
                username: "",
                password: "",
                confirmPassword: "",
                email: "",
                phone: "",
                accessLevel: -1,

            },
            userRoles: [],

            validInputs: {
                firstName: false,
                lastName: false,
                username: false,
                password: false,
                confirmPassword: false,
                email: false,
                phone: false,
                accessLevel: false,

            },
            defaultValue: {
                firstName: "",
                lastName: "",
                username: "",
                password: "",
                confirmPassword: "",
                email: "",
                phone: "",
                accessLevel: -1,
            },
            errors: [],
            submitService: null,
            userRoleService: null,
            newUserId: null,
        };

        this.onFormInputChange = this.onFormInputChange.bind(this);
        this.onServicesCalled = this.onServicesCalled.bind(this);
        this.onFormSubmit = this.onFormSubmit.bind(this);
        this.formElementInvalid = this.formElementInvalid.bind(this);
        this.formElementValid = this.formElementValid.bind(this);
        this.postWidgetLoad = this.postWidgetLoad.bind(this);
        this.createUserRequest = this.createUserRequest.bind(this);
        this.createUserRoleRequest = this.createUserRoleRequest.bind(this);
        this.onResetReceived = this.onResetReceived.bind(this);
        this.onFormInputReset = this.onFormInputReset.bind(this);

    }

    onResetReceived(){
        console.log('onResetReceived');
        let newState = Object.assign(this.state.form, {
            firstName : "",
        });

        this.setState(newState);
        console.log(this.state.form);

    }

    postWidgetLoad(widget) {
        EmailPromptModal.service = widget.services[2];//??
        let submitService = widget.services[1];//1
        let userRoleService = widget.services[2];//2
        //this.storeState({ submitService });
        let newState = Object.assign(this.state, {
            submitService: submitService,
            userRoleService: userRoleService
        });

        this.setState(newState);
    }

    validate() {
        console.log('validating pre-submit');
        let errors = Object.keys(this.state.validInputs).reduce((accum, current) => {
            console.log('state of accumulator is: ');
            console.log(accum);
            console.log('current iteration is: ' + current);

            //console.log('password and reType passwords are : ');
            //console.log(this.state.form.password + " :: " + this.state.confirmPassword );

            if (this.state.validInputs[current] === false) {
                console.log('current input is invalid');
                this.validate = this.validate.bind(this);
                if (current === 'firstName') {
                    accum.push('The first name field is either empty or contains invalid characters');
                }

                if (current === 'lastName') {
                    accum.push('The last name field is either empty or contains invalid characters');
                }

                if (current === 'email') {
                    accum.push('The email field is empty or is not a valid email address');
                }

                if (current === 'phone') {
                    accum.push('The phone field is empty or is not a valid phone number');
                }

                if (current === 'password') {
                    accum.push('The password field is empty or contain less than 5 characters or contain invalid character');
                }

                if (current === 'confirmPassword') {
                    accum.push('The passwords mismatched');
                }

                if (current === 'accessLevel') {
                    accum.push('You must select a accessLevel from the drop-down menu.');
                }
            }

            return accum;
        }, []);

        console.log('final error list looks like: ');
        console.log(errors);

        this.storeState({
            errors: errors
        });

        return errors.length === 0;
    }

    onServicesCalled() {
        let response = arguments[0][0].data;
        let roleList = [];

        if (response) {
            response.map(element => {
                roleList.push({val: element.id, text: element.role_name});
            });
        }

        let newState = Object.assign(this.state, {
            userRoles: roleList
        });

        this.setState(newState);
    }

    onFormInputChange(ev, legend) {
        let value = ev.target.value;
        let form = this.state.form;
        form[legend] = value;
        this.storeState({
            form
        });

    formElementInvalid(elem) {
        let name = elem.name;
        let stateUpdateObj = this.state.validInputs;
        stateUpdateObj[name] = false;
        this.storeState({validInputs: stateUpdateObj});

        if (name !== 'status') {
            elem.classList.add('input-error');
        } else {
            document.getElementById('status-error-field').classList.add('visible');
        }
    }

    formElementValid(elem) {
        let name = elem.name;
        let stateUpdateObj = this.state.validInputs;
        stateUpdateObj[name] = true;
        this.storeState({validInputs: stateUpdateObj});

        if (name !== 'status') {
            elem.classList.remove('input-error');
        } else {
            document.getElementById('status-error-field').classList.remove('visible');
        }
    }

    onFormSubmit() {

        if (this.validate()) {
            console.log("validate got passed");
            console.log(this.state.form);
            var id;

            // match password fields
            if (this.state.form.password !== this.state.form.confirmPassword) {
                let stateUpdateObj = this.state.validInputs;
                stateUpdateObj['confirmPassword'] = false;
                this.storeState({validInputs: stateUpdateObj});
                this.onFormSubmit();

            } else {
                jQuery.when(this.createUserRequest()).done((r) => {

                    console.log("submit for createUser is success reload!");
                    console.log(r);

                    id = r.data.id;

                    jQuery.when(this.createUserRoleRequest(id)).done((r) => {

                        console.log("submit for createUserRole is success reload!");
                        console.log(r);

                        if(r.data.wasSuccessful){
                            console.log("create UserRole is successful, So reload the table ");
                            // do page refresh here
                            window.pubsub.publish('isp.reload-control-users', {});

                            //reset the form
                            console.log("reset the form contents");
                            this.onResetReceived();

                        }

                    }).fail((xhr, status, error) => {
                        console.log(status);
                        console.error(error);
                        alert('An error occured while submitting this request, if this issue persists please contact support.');
                    });

                    let newState = Object.assign(this.state, {
                        newUserId: r.data.id
                    });

                    this.setState(newState);

                }).fail((xhr, status, error) => {
                    console.log(status);
                    console.error(error);
                    alert('An error occured while submitting this request, if this issue persists please contact support.');
                });

            }

        }
    }

    //create a record in is_auth_roles table
    createUserRoleRequest(id) {

        let config = generateJQueryAjaxConfigFromPlaceholders(this.state.userRoleService, {'userId': id});

        config.headers['Content-Type'] = 'application/json';
        config.headers['Accept'] = '*/*';
        config.data = JSON.stringify({
            'roleId': this.state.form.accessLevel,
            'type': 'add'
        });
        console.log("submit config of createUserRoleRequest() is: ");
        console.log(config);

        return jQuery.ajax(config);

    }

    createUserRequest() {
        let config = generateJQueryAjaxConfigFromPlaceholders(this.state.submitService, {});

        config.headers['Content-Type'] = 'application/json';
        config.headers['Accept'] = '*/*';
        config.data = JSON.stringify({
            firstName: this.state.form.firstName,
            lastName: this.state.form.lastName,
            username: this.state.form.username,
            phone: this.state.form.phone,
            password: this.state.form.password,
            confirmPassword: this.state.form.confirmPassword,
            email: this.state.form.email,
            accessLevel: this.state.accessLevel

        });

        console.log("submit config is: ");
        console.log(config);

        return jQuery.ajax(config);
    }

    render() {
            return (

 User  Registration

                <InputListComponent>
                                        {/*onValid={this.formElementValid} />*/}
                    <formTextInputComponent legend="firstName" label="First Name" placeholder="First Name" onChange={this.onFormInputChange} validator={formValidator.nameValidator} onInvalid={this.formElementInvalid} default = {this.state.defaultValue.firstName} value={ this.state.value}
                                        onValid={this.formElementValid} />

                    <FormInputComponent legend="lastName" label="Last Name" placeholder="Last Name" onChange={this.onFormInputChange} validator={formValidator.nameValidator} onInvalid={this.formElementInvalid} default = {this.state.defaultValue.lastName}
                                        onValid={this.formElementValid}/>
                    <FormInputComponent legend="username" label="User Name" placeholder="User Name" onChange={this.onFormInputChange} validator={formValidator.nameValidator} onInvalid={this.formElementInvalid} default = {this.state.defaultValue.username}
                                        onValid={this.formElementValid}/>
                    <FormInputPasswordComponent legend="password" label="Password" placeholder="Password" onChange={this.onFormInputChange} validator={formValidator.passwordValidator} onInvalid={this.formElementInvalid} default = {this.state.defaultValue.password}
                                                onValid={this.formElementValid}/>
                    <FormInputPasswordComponent legend="confirmPassword" label="Confirm Password" placeholder="Confirm Password" onChange={this.onFormInputChange} validator={formValidator.passwordValidator} default = {this.state.defaultValue.confirmPassword}
                                                onInvalid={this.formElementInvalid} onValid={this.formElementValid}/>
                    <FormInputComponent legend="email" label="Email Address" placeholder="Email" onChange={this.onFormInputChange} validator={formValidator.emailValidator} onInvalid={this.formElementInvalid} default = {this.state.defaultValue.email}
                                        onValid={this.formElementValid}/>
                    <FormInputComponent legend="phone" label="Phone Number" placeholder="Phone Number" onChange={this.onFormInputChange} validator={formValidator.phoneValidator} onInvalid={this.formElementInvalid} default = {this.state.defaultValue.phone}
                                        onValid={this.formElementValid}/>
                    <FormSelectComponent legend="accessLevel" data={this.state.userRoles} onChange={this.onFormInputChange} validator={formValidator.statusValidator} onInvalid={this.formElementInvalid} default = {this.state.defaultValue.accessLevel}
                                         onValid={this.formElementValid}/>
                </InputListComponent>

                <ErrorListBox errorList={this.state.errors}/>
                <button className="dataTable-modal-btn click-btn" onClick={this.onFormSubmit}>CREATE USER</button>

        );
    }
}
window.ControlPanelCreateAccounts = ControlPanelCreateAccounts;
window.CurrentWidget = window.ControlPanelCreateAccounts;

this is formInputComponent code

const FormInputComponent = (props) => {

    const onChangeHandler = (ev) => {
        if(props.validator(ev.target.value)) {
            props.onChange(ev, props.legend);
            props.onValid(ev.target);
        } else {
            props.onInvalid(ev.target);
        }
    };

    console.log('props.defaultValue');
    console.log(props.legend);
    console.log(props.default);
    console.log(props.value);
    return (

            {props.label}

            <input name={props.legend} type="text" placeholder={props.placeholder} onChange={onChangeHandler} defaultValue={props.default || ''} value={props.value}/>

    );
};

FormInputComponent.propTypes = {
    legend: React.PropTypes.string,
    label: React.PropTypes.string,
    placeholder: React.PropTypes.string,
    onChange: React.PropTypes.func,
    validator: React.PropTypes.func,
    onInvalid: React.PropTypes.func,
    onValid: React.PropTypes.func,
    default: React.PropTypes.string,
};

export default FormInputComponent;

Body:
If you want setState inside of onResetReceived to reset the form, you'll need to set the value prop of each form field. The default prop gets sent to FormInputComponent as the defaultValue of the input, but you can also see it accepts a value={props.value} as well (even though value is not defined in its PropTypes. From the parent set

<FormInputComponent value={this.state.form.firstName} ... />

This will ensure changing this.state.form via setState will update each form field.


问:
Unpacked javascript doesn't work
I found this script (http://coolersport.info/) and downloaded it. I want change some things in javascript code, so I opened cshout.js (unpacked version) and do changes. I saved it as "cshout.packed.js" (replaced with original packed version).

But now I go to my script index, I can't see any thing, And I see only a white blank page...

Why unpacked version doesn't work? The packed version was create from original unpacked file  (I have same problem with some other scripts...it is an example!)

I debugging it with FireBug. Firebug said:

```<code>ajaxCS is not defined
localhost/cshout/cshout.js Line 49
cshout is not defined localhost/cshout
Line 14
</code>```

答: You will need to use a Javascript debugger such as the Firebug plugin for Firefox and trace down what has broken using that. Without the javascript we can't help in determining the issue. </p>

Title: Unpacked javascript doesn't work

Body:
I found this script (http://coolersport.info/) and downloaded it. I want change some things in javascript code, so I opened cshout.js (unpacked version) and do changes. I saved it as "cshout.packed.js" (replaced with original packed version).

But now I go to my script index, I can't see any thing, And I see only a white blank page...

Why unpacked version doesn't work? The packed version was create from original unpacked file  (I have same problem with some other scripts...it is an example!)

I debugging it with FireBug. Firebug said:

ajaxCS is not defined
localhost/cshout/cshout.js Line 49
cshout is not defined localhost/cshout
Line 14


问:
How can I get the checked status of a checkbox
I have a gridview parameter in my asp.net program as follows:

Name: row.Cells[5].Controls[0]

Value: (Text="" Checked=true)

type: System.Web.UI.WebControls.CheckBox

How can I get the Checked status of such parameter?

答:
If you have specified id for that control then you can use the FindControl method, or else you can go ahead with the Controls[0]. Anyway You have to try something like this:

```<code>CheckBox chkBox = row.Cells[5].FindControl("checkBoxId") as CheckBox;
if (chkBox.Checked)
{
   // given checkbox is checked
}
else
{
  // it is not checked
}
</code>```

Or like this:

```<code>CheckBox chkBox = row.Cells[5].Controls[0] as CheckBox;
if (chkBox.Checked)
{
   // given checkbox is checked
}
else
{
  // it is not checked
}
</code>```

Body:
If you have specified id for that control then you can use the FindControl method, or else you can go ahead with the Controls[0]. Anyway You have to try something like this:

CheckBox chkBox = row.Cells[5].FindControl("checkBoxId") as CheckBox;
if (chkBox.Checked)
{
   // given checkbox is checked
}
else
{
  // it is not checked
}

Or like this:

CheckBox chkBox = row.Cells[5].Controls[0] as CheckBox;
if (chkBox.Checked)
{
   // given checkbox is checked
}
else
{
  // it is not checked
}


问:
jQuery / Javascript: Show Image when link is clicked. Then when another link clicked, show different image, while hiding the previous visible image
I have 4 images and 4 links referencing each image.

Image 1 will appear by default. When users click on link 2, image 2 will replace image 1 and so on with link 3 & 4.

I've set the html as a list item like so:

```<code><ul class="nav-tabs">

    <li>
        <img class="activeImg" src="img1.jpg" />
        <img src="img2.jpg" />
        <img src="img3.jpg" />
        <img src="img4.jpg" />
    </li>

    <li><a href="#">Link 1</a></li>
    <li><a href="#">Link 2</a></li>
    <li><a href="#">Link 3</a></li>
    <li><a href="#">Link 4</a></li>

</ul>
</code>```

Css:

```<code>.nav-tabs li img.activeImg{
    visibility: visible;
    }
</code>```

jQuery:

```<code>$('.nav-tabs li:nth-child(2)').click(function(){
    $('.nav-tabs li img:nth-child(1)').addClass("activeImg");
    $('.nav-tabs li img:nth-child(2)').hide();
});

$('.nav-tabs li:nth-child(3)').click(function(){
    $('.nav-tabs li img:nth-child(2)').addClass("activeImg");
    $('.nav-tabs li img:nth-child(1)').hide();
});
</code>```

This doesn't work well since it hides everything.

I need help as you can see. Please provide some working examples in either jquery or javascript.

答:
I ended up using this code from w3c which works well for my case and a lot more simpler than what my mind was conjuring up:</p>

```<code><img id="myImg" src="compman.gif" width="107" height="98">

<script>
function myFunction() {
    document.getElementById("myImg").src = "hackanm.gif";
}
</script>
</code>```

Body:
I have 4 images and 4 links referencing each image.

Image 1 will appear by default. When users click on link 2, image 2 will replace image 1 and so on with link 3 & 4.

I've set the html as a list item like so:

Link 1

Link 2

Link 3

Link 4

Css:

.nav-tabs li img.activeImg{
    visibility: visible;
    }

jQuery:

$('.nav-tabs li:nth-child(2)').click(function(){
    $('.nav-tabs li img:nth-child(1)').addClass("activeImg");
    $('.nav-tabs li img:nth-child(2)').hide();
});

$('.nav-tabs li:nth-child(3)').click(function(){
    $('.nav-tabs li img:nth-child(2)').addClass("activeImg");
    $('.nav-tabs li img:nth-child(1)').hide();
});

This doesn't work well since it hides everything.

I need help as you can see. Please provide some working examples in either jquery or javascript.

Body:
I ended up using this code from w3c which works well for my case and a lot more simpler than what my mind was conjuring up:

<img id="myImg" src="compman.gif" width="107" height="98">

<script>
function myFunction() {
    document.getElementById("myImg").src = "hackanm.gif";
}
</script>


问:
How can I find the first occurrence in a string that is not numeric in java
I'm working on my own method in Java that will be able to calculate math equations given a string. Basically my calculator gets something like "698+33-47*2".
I want to split the parts (using substring and finding the characters '+', '-', '*', '/') but I'm not sure how to find the first non numeric character. My method is like this so far:</p>

```<code>public void DoEquation() {
  String s = storedData.getText() + data.getText();
  s = s.replaceAll(" ", "");

  ArrayList<String> list = new ArrayList<>();
  boolean checking = true;
  while (checking) {
    if (!s.contains("+") && !s.contains("-") && !s.contains("*") && !s.contains("/") {
      checking = false;
      break;
    }
    // Logic for extracting the numbers into the list
    // Then extract the mathamatical sign and place into list
  }
  System.out.println(list); // For testing
}
</code>```

答:
As said in comment, you may want to write a parser for proper handling for future enhancements.

With regarding to this specific question, by using a regex should make your life easy.  Different from other answers, you can get the list of tokens with only 1 split by this regex:

```<code>(?<=\d)(?=[+\-*/])|(?<=[+\-*/])(?=\d)
</code>```

This find a zero-length position that is having digit in front of it and having symbol behind it (and vice versa).

Example :

```<code>String input = "698+33-47*2";
String[] result = input.split("(?<=\\d)(?=[+\\-*/])|(?<=[+\\-*/])(?=\\d)")));
// result will be [698, +, 33, -, 47, *, 2]
</code>```

Body:
I'm working on my own method in Java that will be able to calculate math equations given a string. Basically my calculator gets something like "698+33-47*2".
I want to split the parts (using substring and finding the characters '+', '-', '*', '/') but I'm not sure how to find the first non numeric character. My method is like this so far:

public void DoEquation() {
  String s = storedData.getText() + data.getText();
  s = s.replaceAll(" ", "");

  ArrayList<String> list = new ArrayList<>();
  boolean checking = true;
  while (checking) {
    if (!s.contains("+") && !s.contains("-") && !s.contains("*") && !s.contains("/") {
      checking = false;
      break;
    }
    // Logic for extracting the numbers into the list
    // Then extract the mathamatical sign and place into list
  }
  System.out.println(list); // For testing
}

Body:
As said in comment, you may want to write a parser for proper handling for future enhancements.

With regarding to this specific question, by using a regex should make your life easy.  Different from other answers, you can get the list of tokens with only 1 split by this regex:

(?<=\d)(?=[+\-*/])|(?<=[+\-*/])(?=\d)

This find a zero-length position that is having digit in front of it and having symbol behind it (and vice versa).

Example :

String input = "698+33-47*2";
String[] result = input.split("(?<=\\d)(?=[+\\-*/])|(?<=[+\\-*/])(?=\\d)")));
// result will be [698, +, 33, -, 47, *, 2]