问:
Await all Tasks in the list, and after that update the list base on task result
I want to run all tasks with WhenAll (not one by one).
But after that I need to update list (LastReport property) base on result.

I think I have solution but I would like to check if there is better way.

Idea is to:

Run all tasks

Remember relation between configuration and task

Update configuration

My solution is:

```<code>var lastReportAllTasks = new List<Task<Dictionary<string, string>>>();
var configurationTaskRelation = new Dictionary<int, Task<Dictionary<string, string>>>();
foreach (var configuration in MachineConfigurations)
{
    var task = machineService.GetReports(configuration);
    lastReportAllTasks.Add(task);
    configurationTaskRelation.Add(configuration.Id, task);
}

await Task.WhenAll(lastReportAllTasks);
foreach (var configuration in MachineConfigurations)
{
    var lastReportTask = configurationTaskRelation[configuration.Id];
    configuration.LastReport = await lastReportTask;
}
</code>```

答:
```<code>using System.Linq;

var taskResultsWithConfiguration = MachineConfigurations.Select(conf =>
    new { Conf = conf, Task = machineService.GetReports(conf) }).ToList();
await Task.WhenAll(taskResultsWithConfiguration.Select(pair => pair.Task));

foreach (var pair in taskResultsWithConfiguration)
      pair.Conf.LastReport = pair.Task.Result;
</code>```

Body:
I want to run all tasks with WhenAll (not one by one).
But after that I need to update list (LastReport property) base on result.

I think I have solution but I would like to check if there is better way.

Idea is to:

Run all tasks

Remember relation between configuration and task

Update configuration

My solution is:

var lastReportAllTasks = new List<Task<Dictionary<string, string>>>();
var configurationTaskRelation = new Dictionary<int, Task<Dictionary<string, string>>>();
foreach (var configuration in MachineConfigurations)
{
    var task = machineService.GetReports(configuration);
    lastReportAllTasks.Add(task);
    configurationTaskRelation.Add(configuration.Id, task);
}

await Task.WhenAll(lastReportAllTasks);
foreach (var configuration in MachineConfigurations)
{
    var lastReportTask = configurationTaskRelation[configuration.Id];
    configuration.LastReport = await lastReportTask;
}


来源: stackexchange

问:
Set tag id as an object attribute
```<code>buttons = buttons.map(function(assetf,index){
          return(
            assetf.map(function(asset, index){
              return(
                <select class="btn btn-info dropdown-toggle" id=asset._id>
             )
            }
          )
         }
</code>```

So basicly I want to set the id of the select tag to the _id variable in the passed asset object. How can I do this?

Thanks, Ed.

答:
Use curly brackets.</p>

```<code><select class="btn btn-info dropdown-toggle" id={asset._id}>
</code>```

ContentLicense: CC BY-SA 3.0

Title: Set tag id as an object attribute

Body:
buttons = buttons.map(function(assetf,index){
          return(
            assetf.map(function(asset, index){
              return(
                <select class="btn btn-info dropdown-toggle" id=asset._id>
             )
            }
          )
         }

So basicly I want to set the id of the select tag to the _id variable in the passed asset object. How can I do this?

Thanks, Ed.

Body:
Use curly brackets.

<select class="btn btn-info dropdown-toggle" id={asset._id}>


问:
Applying style to particular cell in knockout JS dynamic table depending upon it value
I don't have any experience in Knockout js but since I have to implement the functionality and struggling to get my hands on this scenario.

JSP files are fetching JSON data and it is passed to HTML template to create dynamic table.But i have to match particular values and give different styling to cells(Need to change color).

I explored and found out if Foreach is used and using if condition to apply css class can work but since table is getting created dynamically so finding it difficult to achieve it.

Providing the code below,i know angular way to do it but since its in knockout JS am struggling.

The above JSON data fetching dynamically from DB, if App Server is responding then map to “Yes” otherwise map to “No”, in additionally I have to set Yes mean green color, No means Red color.
I mapped responding values, it is working fine.
But I am not able to set colors for responding values (Yes means green and No means red color) in Knockout js. Can you please suggest me on this

```<code> <table  id="monitorTable" summary="Table Data Test" aria-label="Table Data Test"
                        contextmenu="empty"
                        data-bind="ojComponent: {component: 'ojTable',
                        data: testdatasource,
                        columnsDefault: {sortable: 'disabled'},
                        columns: tableColumns,
                        scrollPolicy: scrollPolicy,
                        scrollPolicyOptions: scrollPolicyOptions}"></table>
</code>```

Below here is the JSOn data fetched from server and passed to table

```<code> {
    "label": "App Server",
    "collection": [{
        "responding": "Yes",
        "appserver": "DEFAULT",
        "className": "success",
        "id": 1
    }, {
        "responding": "No",
        "appserver": "ORACLEQUEUE",
        "className": "failed",
        "id": 2
    }, {
        "responding": "No",
        "appserver": "SECONDARY",
        "className": "failed",
        "id": 3
    }, {
        "responding": "No",
        "appserver": "TERTIARY",
        "className": "failed",
        "id": 4
    }],
    "serverTimestamp": "2017-07-07T03:51:21.949+0000",
    "dataTimestamp": "2017-07-07T03:51:21.949+0000",
    "tableColumns": [{
        "headerText": "App Server",
        "field": "appserver",
        "sortable": "disabled"
    }, {
        "headerText": "Responding",
        "field": "responding",
        "sortable": "disabled",
        "className": ""
    }],
    "scrollPolicy": "auto",
    "scrollPolicyOptions": {
        "fetchSize": "15",
        "maxCount": "1000"
    }
}
</code>```

Here is the code which fetches data from server by JSP files

```<code>function addScalabilityMonitors() {
            console.log("moved to scalability");
            //App Scalability
            monitors.addMonitorPoint(sts.apiBaseUrl() + 'ScalabilityAppServer1.jsp', 'oj-masonrylayout-tile-3x2', true, 15000, 'grid', 'scalability');
            //Web Scalability
            monitors.addMonitorPoint(sts.apiBaseUrl() + 'ScalabilityWebServer1.jsp', 'oj-masonrylayout-tile-3x2', true, 15000, 'grid', 'scalability');
            //Response Time
            monitors.addMonitorPoint(sts.apiBaseUrl() + 'Scalability.json', 'oj-masonrylayout-tile-3x2', true, 15000, 'gauge', 'scalability');
            //Log files
            monitors.addMonitorPoint(sts.apiBaseUrl() + 'logfile.json', 'oj-masonrylayout-tile-3x2', true, 15000, 'grid', 'scalability');
            monitors.addMonitorPoint(sts.apiBaseUrl() + 'ProcessSchedules.json', 'oj-masonrylayout-tile-3x2', true, 15000, 'grid', 'scalability');
            monitors.addMonitorPoint(sts.apiBaseUrl() + 'BusinessSequence.json', 'oj-masonrylayout-tile-3x2', true, 15000, 'grid', 'scalability');
            monitors.addMonitorPoint(sts.apiBaseUrl() + 'DatabaseJobs.json', 'oj-masonrylayout-tile-3x2', true, 15000, 'grid', 'scalability');
            //myPostProcessingLogic();
        }
</code>```

I tried to read the documentation for this, also tried various things but failed to implement.

答:
Assuming you have access to the css this is pretty simple. If not, it's only slightly simple. Knockout has a databinding specifically for css. Here's an example.

function Server(data) {
  var self = this;

  self.Name = ko.observable(data.Name);
  self.Status = ko.observable(data.Status);
}

function viewModel() {
  var self = this;

  self.Servers = ko.observableArray();

  self.Load = function() {
    self.Servers.push(new Server({
      Name: "Email",
      Status: "Online"
    }));
    self.Servers.push(new Server({
      Name: "TPS Reports",
      Status: "Offline"
    }));
  };

  self.Load();

}

ko.applyBindings(new viewModel());```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.red {
  background-color: red;
}

.blue {
  background-color: blue;
}</code>```

 CSS Control

       Server Name
       Server Status

 No CSS Control

       Server Name
       Server Status

```

With your code, you would just make some additions to the data-binding in question.

Body:
I don't have any experience in Knockout js but since I have to implement the functionality and struggling to get my hands on this scenario.

JSP files are fetching JSON data and it is passed to HTML template to create dynamic table.But i have to match particular values and give different styling to cells(Need to change color).

I explored and found out if Foreach is used and using if condition to apply css class can work but since table is getting created dynamically so finding it difficult to achieve it.

Providing the code below,i know angular way to do it but since its in knockout JS am struggling.

The above JSON data fetching dynamically from DB, if App Server is responding then map to “Yes” otherwise map to “No”, in additionally I have to set Yes mean green color, No means Red color.
I mapped responding values, it is working fine.
But I am not able to set colors for responding values (Yes means green and No means red color) in Knockout js. Can you please suggest me on this

Below here is the JSOn data fetched from server and passed to table

 {
    "label": "App Server",
    "collection": [{
        "responding": "Yes",
        "appserver": "DEFAULT",
        "className": "success",
        "id": 1
    }, {
        "responding": "No",
        "appserver": "ORACLEQUEUE",
        "className": "failed",
        "id": 2
    }, {
        "responding": "No",
        "appserver": "SECONDARY",
        "className": "failed",
        "id": 3
    }, {
        "responding": "No",
        "appserver": "TERTIARY",
        "className": "failed",
        "id": 4
    }],
    "serverTimestamp": "2017-07-07T03:51:21.949+0000",
    "dataTimestamp": "2017-07-07T03:51:21.949+0000",
    "tableColumns": [{
        "headerText": "App Server",
        "field": "appserver",
        "sortable": "disabled"
    }, {
        "headerText": "Responding",
        "field": "responding",
        "sortable": "disabled",
        "className": ""
    }],
    "scrollPolicy": "auto",
    "scrollPolicyOptions": {
        "fetchSize": "15",
        "maxCount": "1000"
    }
}

Here is the code which fetches data from server by JSP files

function addScalabilityMonitors() {
            console.log("moved to scalability");
            //App Scalability
            monitors.addMonitorPoint(sts.apiBaseUrl() + 'ScalabilityAppServer1.jsp', 'oj-masonrylayout-tile-3x2', true, 15000, 'grid', 'scalability');
            //Web Scalability
            monitors.addMonitorPoint(sts.apiBaseUrl() + 'ScalabilityWebServer1.jsp', 'oj-masonrylayout-tile-3x2', true, 15000, 'grid', 'scalability');
            //Response Time
            monitors.addMonitorPoint(sts.apiBaseUrl() + 'Scalability.json', 'oj-masonrylayout-tile-3x2', true, 15000, 'gauge', 'scalability');
            //Log files
            monitors.addMonitorPoint(sts.apiBaseUrl() + 'logfile.json', 'oj-masonrylayout-tile-3x2', true, 15000, 'grid', 'scalability');
            monitors.addMonitorPoint(sts.apiBaseUrl() + 'ProcessSchedules.json', 'oj-masonrylayout-tile-3x2', true, 15000, 'grid', 'scalability');
            monitors.addMonitorPoint(sts.apiBaseUrl() + 'BusinessSequence.json', 'oj-masonrylayout-tile-3x2', true, 15000, 'grid', 'scalability');
            monitors.addMonitorPoint(sts.apiBaseUrl() + 'DatabaseJobs.json', 'oj-masonrylayout-tile-3x2', true, 15000, 'grid', 'scalability');
            //myPostProcessingLogic();
        }

I tried to read the documentation for this, also tried various things but failed to implement.

Body:
Assuming you have access to the css this is pretty simple. If not, it's only slightly simple. Knockout has a databinding specifically for css. Here's an example.

function Server(data) {
  var self = this;

  self.Name = ko.observable(data.Name);
  self.Status = ko.observable(data.Status);
}

function viewModel() {
  var self = this;

  self.Servers = ko.observableArray();

  self.Load = function() {
    self.Servers.push(new Server({
      Name: "Email",
      Status: "Online"
    }));
    self.Servers.push(new Server({
      Name: "TPS Reports",
      Status: "Offline"
    }));
  };

  self.Load();

}

ko.applyBindings(new viewModel());

.red {
  background-color: red;
}

.blue {
  background-color: blue;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<h3> CSS Control</h3>
<table border=1>
  <thead>
    <tr>
      <th> Server Name</th>
      <th> Server Status</th>
    </tr>
  </thead>
  <tbody data-bind="foreach: Servers">
    <tr>
      <td> <span data-bind="text: Name"> </span> </td>
      <td data-bind="css: { red: Status() == 'Offline', blue: Status() == 'Online' } "> <span data-bind="text: Status"> </span> </td>
    </tr>
  </tbody>
</table>
<br><br><br><br>
<h3> No CSS Control</h3>
<table border=1>
  <thead>
    <tr>
      <th> Server Name</th>
      <th> Server Status</th>
    </tr>
  </thead>
  <tbody data-bind="foreach: Servers">
    <tr>
      <td> <span data-bind="text: Name"> </span> </td>
      <!-- Note: anything with a hyphen must be surrounded in single quotes -->
      <td data-bind="style: { 'background-color': Status() == 'Online' ? 'green' : 'black' } "> <span data-bind="text: Status"> </span> </td>
    </tr>
  </tbody>
</table>

With your code, you would just make some additions to the data-binding in question.


问:
Trying to pivot a table using Apache spark Java API
I have a dataset in csv file, Can anyone tell me how to pivot the dataset on a particular column using Apache spark java program.

Sample data:

```<code>id | name | city
1    john   Newyork
2    smith  LA
3    mike   Boston
</code>```

I am trying to do pivot on city column

Outcome should be:

```<code>id | name | Newyork | LA | Boston
1   john      1        0     0
2   smith     0        1     0
3   mike      0        0     1
</code>```

..Thanks and in advance

Body:
I have a dataset in csv file, Can anyone tell me how to pivot the dataset on a particular column using Apache spark java program.

Sample data:

id | name | city
1    john   Newyork
2    smith  LA
3    mike   Boston

I am trying to do pivot on city column

Outcome should be:

id | name | Newyork | LA | Boston
1   john      1        0     0
2   smith     0        1     0
3   mike      0        0     1

..Thanks and in advance

Body: Df.groupby(col("id")).pivot("city")


问:
Numbers in SELECT statements
I encountered sql queries like 'SELECT 1 FROM TABLE_NAME' or 'SELECT 2 FROM TABLE_NAME' while debugging a program. I am curious as to what the numbers in the queries do and what result set does it return.

Thanks

答:
Select 1 from your_table --> On execution , you get the value 1 for every row in your_table.

'Select *' and 'Select 1 or 2' have the same performance when executing without an EXIST condition. My personal choice is using 'Select 1 or 2' when there are conditions to check for  existing rows as it is slightly faster, for eg. when querying with VIEWS or temp tables having millions of rows and lot many columns.

ContentLicense: CC BY-SA 2.5

Title: Numbers in SELECT statements


问:
Would merge --squash cause conflicts with cherry picks already in develop
We are using the git flow model merge feature branches into the develop branch via pull request, after theyhave been rebased onto develop.

Sometimes one feature branch cherry picks from another one, and one of them will be merged into develop first. When the second one then rebases onto develop, those cherry picks are fast forwarded.

My question: currenty we just use merge (which could easy be replaced with --ff-only I assume as we always rebase), but could we alsod o --squash --ff-only? Would that then cause conflicts when the cherry picked commits are rebased onto develop when those commits are already in there?

The reason why I fear additional conflicts would arise is as follows: Let's assume both commit1 and commit2 make changes in one file. If they are merged into develop and then the second branch that cherry picked them makes a rebase, it would recognise that those two commits are already in there.

In case those two commits are squashed and it tries to rebase on top of it, it would no longer see that and when replaying the first commit on top of the rebase would already contain the commit2 and thus cause a conflict.

```<code>feat1: ... A -- B
feat2  ... A (cherry picked) -- B (cherry picked)
</code>```

feat1 is merged with squash into develop

```<code>develop .... S
</code>```

Would rebasing feat2 onto develop cause a conflict if both A and B edit the same file?

答: Absolutely squashing the commits would thwart patch ID detection, so that rebase could no longer protect you from conflicts arising from the cherry picked commits.  (And conversely, if the commit sequence makes and reverts changes, then potential conflicts could be eliminated by squashing - but that's more of an aside.)</p>

Body:
We are using the git flow model merge feature branches into the develop branch via pull request, after theyhave been rebased onto develop.

Sometimes one feature branch cherry picks from another one, and one of them will be merged into develop first. When the second one then rebases onto develop, those cherry picks are fast forwarded.

My question: currenty we just use merge (which could easy be replaced with --ff-only I assume as we always rebase), but could we alsod o --squash --ff-only? Would that then cause conflicts when the cherry picked commits are rebased onto develop when those commits are already in there?

The reason why I fear additional conflicts would arise is as follows: Let's assume both commit1 and commit2 make changes in one file. If they are merged into develop and then the second branch that cherry picked them makes a rebase, it would recognise that those two commits are already in there.

In case those two commits are squashed and it tries to rebase on top of it, it would no longer see that and when replaying the first commit on top of the rebase would already contain the commit2 and thus cause a conflict.

feat1: ... A -- B
feat2  ... A (cherry picked) -- B (cherry picked)

feat1 is merged with squash into develop

develop .... S

Would rebasing feat2 onto develop cause a conflict if both A and B edit the same file?


问:
How to debug a "String index out of range" error in a Java program?
```<code>["Exception in thread "main"
java.lang.StringIndexOutOfBoundsException: String index out of range: 2
    at java.lang.String.charAt(Unknown Source)
    at Haupt.main(Haupt.java:21)"]
</code>```

And here is my code. Why did I get this error?

```<code>import java.util.Scanner;

public class Haupt {

    public static void main(String[] args) {
        String Wort="";
        String WortCpy="";
        String WortRev="";
        int i=0;
        Scanner scan = new Scanner(System.in);

        System.out.print("Geben Sie ein Wort ein : "); //Ausgabe
        Wort = scan.nextLine(); //Eingabe
        scan.close();
        for(i=0;i < Wort.length();i++) {
            WortCpy= WortCpy +  Wort.charAt(i); //Speichert jeden Buchstaben einzeln in Wortcpy ab
        }
        for(i=Wort.length();i>=0;i--) {
            WortRev = WortRev +  Wort.charAt(i);
        }

        System.out.println("Wort : " + Wort);
        System.out.println("Wort Kopiert : " + WortCpy);
        System.out.println("Wort umgedreht : " + WortRev);

    }

}
</code>```

答:
Indexes start from 0 for a String object. So you have not index which number equals to Wort.length()

Try this;

```<code> for(i=Wort.length()-1;i>=0;i--) {
        WortRev = WortRev +  Wort.charAt(i);
    }
</code>```

Body:
["Exception in thread "main"
java.lang.StringIndexOutOfBoundsException: String index out of range: 2
    at java.lang.String.charAt(Unknown Source)
    at Haupt.main(Haupt.java:21)"]

And here is my code. Why did I get this error?

import java.util.Scanner;

public class Haupt {

    public static void main(String[] args) {
        String Wort="";
        String WortCpy="";
        String WortRev="";
        int i=0;
        Scanner scan = new Scanner(System.in);

        System.out.print("Geben Sie ein Wort ein : "); //Ausgabe
        Wort = scan.nextLine(); //Eingabe
        scan.close();
        for(i=0;i < Wort.length();i++) {
            WortCpy= WortCpy +  Wort.charAt(i); //Speichert jeden Buchstaben einzeln in Wortcpy ab
        }
        for(i=Wort.length();i>=0;i--) {
            WortRev = WortRev +  Wort.charAt(i);
        }

        System.out.println("Wort : " + Wort);
        System.out.println("Wort Kopiert : " + WortCpy);
        System.out.println("Wort umgedreht : " + WortRev);

    }

}

Body:
Indexes start from 0 for a String object. So you have not index which number equals to Wort.length()

Try this;

 for(i=Wort.length()-1;i>=0;i--) {
        WortRev = WortRev +  Wort.charAt(i);
    }


问:
React js break when match happens
I am wanting to stop a loop that i have when it matches a condition but its just not breaking ive tried try catch loops with throw e and throw new typeerror but its just not breaking how do i get it to break here is the code i want to break

```<code>LoginAuth = (Res) => {
    try {
        if (Res.username === this.state.Username && Res.password === this.state.Password) {
            return (
                this.setState({
                    isLoggedIn: true,
                }, function () {

                }),
                this.hideModal()
            );
        } else {
            console.log("Gets to login auth and false");
        }
}
</code>```

I want to make it stop when the user input in state.username and state.password are equal to the one in the variable Res but i cant get it to stop looping how do i do this.

this is the function that calls this one

```<code>CheckLoginAuth() {
    console.log("gets to check login auth");
    console.log(this.state.AuthRes);
    console.log("Username=" + this.state.Username);
    console.log("Password=" + this.state.Password);
    var self = this;
    this.props.AuthRes.forEach(function (Res) {
        return (
            console.log("ID=" + Res.id),
            console.log("Username=" + Res.username),
            console.log("Password=" + Res.password),
            self.LoginAuth(Res)
        );
    });
}
</code>```

edit

```<code>CheckLoginAuth() {
    console.log("gets to check login auth");
    console.log(this.state.AuthRes);
    console.log("Username=" + this.state.Username);
    console.log("Password=" + this.state.Password);
    this.props.AuthRes.some(function (Res) {
        console.log("ID=" + Res.id);
        console.log("Username=" + Res.username);
        console.log("Password=" + Res.password);
        if (Res.username === this.state.Username && Res.password === this.state.Password) {// the error is on this line saying it doesnt know what Username or Password are in the state
            return (
                this.setState({
                    isLoggedIn: true,
                }, function () {
                }),
                this.hideModal()
            );
        } else {
            console.log("Gets to login auth and false");
        }
    });
}
</code>```

error is Cannot read property 'state' of undefined

```<code>LoginAuth = (Res) => {
    if (Res.username === this.state.Username && Res.password === this.state.Password) {
        return (
            this.setState({
                isLoggedIn: true,
            }, function () {
            }),
            this.hideModal()
        );
    } else {
        console.log("Gets to login auth and false");
    }
}
CheckLoginAuth() {
    console.log("gets to check login auth");
    console.log(this.state.AuthRes);
    console.log("Username=" + this.state.Username);
    console.log("Password=" + this.state.Password);
    var self = this;
    this.props.AuthRes.every(function (Res) {
        console.log("ID=" + Res.id);
        console.log("Username=" + Res.username);
        console.log("Password=" + Res.password);
        return (
            self.LoginAuth(Res)
        );
    });
}
</code>```

loops through but stops on the first one weather its true or false

答:
There is no way to stop execution of a forEach(). In fact, the MDN states:

There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behavior, the forEach() method is the wrong tool. Use a plain loop instead. If you are testing the array elements for a predicate and need a Boolean return value, you can use every() or some() instead.

So, as suggested, you could use some() instead.

some() executes the callback function once for each element present in the array until it finds one where callback returns a truthy value (a value that becomes true when converted to a Boolean). If such an element is found, some() immediately returns true. Otherwise, some() returns false.

So your function could instead be written as:

```<code>this.props.AuthRes.some(function (Res) {
    return (
        console.log("ID=" + Res.id),
        console.log("Username=" + Res.username),
        console.log("Password=" + Res.password),
        self.LoginAuth(Res)
    );
});
</code>```

this will stop the iteration once the callback returns true, or until you run out of elements to iterate through.

Edit

To solve the Cannot read property 'state' of undefined error, the simplest way is to use an arrow function:

```<code>this.props.AuthRes.some((Res) => {
</code>```

Title: React js break when match happens

Body:
I am wanting to stop a loop that i have when it matches a condition but its just not breaking ive tried try catch loops with throw e and throw new typeerror but its just not breaking how do i get it to break here is the code i want to break

LoginAuth = (Res) => {
    try {
        if (Res.username === this.state.Username && Res.password === this.state.Password) {
            return (
                this.setState({
                    isLoggedIn: true,
                }, function () {

                }),
                this.hideModal()
            );
        } else {
            console.log("Gets to login auth and false");
        }
}

I want to make it stop when the user input in state.username and state.password are equal to the one in the variable Res but i cant get it to stop looping how do i do this.

this is the function that calls this one

CheckLoginAuth() {
    console.log("gets to check login auth");
    console.log(this.state.AuthRes);
    console.log("Username=" + this.state.Username);
    console.log("Password=" + this.state.Password);
    var self = this;
    this.props.AuthRes.forEach(function (Res) {
        return (
            console.log("ID=" + Res.id),
            console.log("Username=" + Res.username),
            console.log("Password=" + Res.password),
            self.LoginAuth(Res)
        );
    });
}

edit

CheckLoginAuth() {
    console.log("gets to check login auth");
    console.log(this.state.AuthRes);
    console.log("Username=" + this.state.Username);
    console.log("Password=" + this.state.Password);
    this.props.AuthRes.some(function (Res) {
        console.log("ID=" + Res.id);
        console.log("Username=" + Res.username);
        console.log("Password=" + Res.password);
        if (Res.username === this.state.Username && Res.password === this.state.Password) {// the error is on this line saying it doesnt know what Username or Password are in the state
            return (
                this.setState({
                    isLoggedIn: true,
                }, function () {
                }),
                this.hideModal()
            );
        } else {
            console.log("Gets to login auth and false");
        }
    });
}

error is Cannot read property 'state' of undefined

LoginAuth = (Res) => {
    if (Res.username === this.state.Username && Res.password === this.state.Password) {
        return (
            this.setState({
                isLoggedIn: true,
            }, function () {
            }),
            this.hideModal()
        );
    } else {
        console.log("Gets to login auth and false");
    }
}
CheckLoginAuth() {
    console.log("gets to check login auth");
    console.log(this.state.AuthRes);
    console.log("Username=" + this.state.Username);
    console.log("Password=" + this.state.Password);
    var self = this;
    this.props.AuthRes.every(function (Res) {
        console.log("ID=" + Res.id);
        console.log("Username=" + Res.username);
        console.log("Password=" + Res.password);
        return (
            self.LoginAuth(Res)
        );
    });
}

loops through but stops on the first one weather its true or false

Body:
There is no way to stop execution of a forEach(). In fact, the MDN states:

There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behavior, the forEach() method is the wrong tool. Use a plain loop instead. If you are testing the array elements for a predicate and need a Boolean return value, you can use every() or some() instead.

So, as suggested, you could use some() instead.

some() executes the callback function once for each element present in the array until it finds one where callback returns a truthy value (a value that becomes true when converted to a Boolean). If such an element is found, some() immediately returns true. Otherwise, some() returns false.

So your function could instead be written as:

this.props.AuthRes.some(function (Res) {
    return (
        console.log("ID=" + Res.id),
        console.log("Username=" + Res.username),
        console.log("Password=" + Res.password),
        self.LoginAuth(Res)
    );
});

this will stop the iteration once the callback returns true, or until you run out of elements to iterate through.

Edit

To solve the Cannot read property 'state' of undefined error, the simplest way is to use an arrow function:

this.props.AuthRes.some((Res) => {


问:
Convert String to ByteArray in C#
I want to convert a String to ByteArray in C# for Decrypt some data.

When I get de String from the ByteArray created, it shows question marks (?).

Example code:

```<code>        byte[] strTemp = Encoding.ASCII.GetBytes(strData);

        MessageBox.Show(strData);
        MessageBox.Show(Encoding.ASCII.GetString(strTemp));
</code>```

The string is "Ê<,,l"x¡" (With the double quotation mark) and the result to convert again to string is: ???l?x?

答:
For specific of that input, this BigEndianUnicode encoding seems works fine

```<code>byte[] strTemp = Encoding.BigEndianUnicode.GetBytes(strData);

MessageBox.Show(strData);
MessageBox.Show(Encoding.BigEndianUnicode.GetString(strTemp));
</code>```

`

Title: Convert String to ByteArray in C#

Body:
I want to convert a String to ByteArray in C# for Decrypt some data.

When I get de String from the ByteArray created, it shows question marks (?).

Example code:

        byte[] strTemp = Encoding.ASCII.GetBytes(strData);

        MessageBox.Show(strData);
        MessageBox.Show(Encoding.ASCII.GetString(strTemp));

The string is "Ê<,,l"x¡" (With the double quotation mark) and the result to convert again to string is: ???l?x?

Body:
For specific of that input, this BigEndianUnicode encoding seems works fine

byte[] strTemp = Encoding.BigEndianUnicode.GetBytes(strData);

MessageBox.Show(strData);
MessageBox.Show(Encoding.BigEndianUnicode.GetString(strTemp));

`


问:
C# Identify parent,child elements in XML file
I found this on internet.

```<code>string xml = @"
<food>
  <child>
    <nested />
  </child>
  <child>
    <other>
    </other>
  </child>
</food>
";

XmlReader rdr = XmlReader.Create(new System.IO.StringReader(xml));
while (rdr.Read())
{
  if (rdr.NodeType == XmlNodeType.Element)
  {
  Console.WriteLine(rdr.LocalName);
  }
}
</code>```

The result of the above will be

```<code>food
child
nested
child
other
</code>```

This is working perfect, Just i need to identify which elements contains child elements.

for example, I need this output

```<code>startParent_food
    startParent_child
        nested
    endParent_child
    startParent_child
        other
    endParent_child
endParent_food
</code>```

答:
For checking child elements, your code will look something like below:

```<code>    System.Xml.Linq.XElement _x;
    _x = System.Xml.Linq.XElement.Parse(xml);

    if (_x.HasElements)
    {
        // your req element
    }
</code>```

you will have to make it recursive to check all elements.

Body:
I found this on internet.

string xml = @"
<food>
  <child>
    <nested />
  </child>
  <child>
    <other>
    </other>
  </child>
</food>
";

XmlReader rdr = XmlReader.Create(new System.IO.StringReader(xml));
while (rdr.Read())
{
  if (rdr.NodeType == XmlNodeType.Element)
  {
  Console.WriteLine(rdr.LocalName);
  }
}

The result of the above will be

food
child
nested
child
other

This is working perfect, Just i need to identify which elements contains child elements.

for example, I need this output

startParent_food
    startParent_child
        nested
    endParent_child
    startParent_child
        other
    endParent_child
endParent_food

Body:
For checking child elements, your code will look something like below:

    System.Xml.Linq.XElement _x;
    _x = System.Xml.Linq.XElement.Parse(xml);

    if (_x.HasElements)
    {
        // your req element
    }

you will have to make it recursive to check all elements.


问:
object-oriented shell for linux?
Is there anything similar to Microsoft Powershell (an object-oriented shell built on the .NET framework) for Linux (possibly built on Java, GObject, or its own object type/nothing)?

edit: especially if similar to bash or powershell or cmd etc. syntax (=''standard'' shell syntax)

答: Hotwire</p>

Title: object-oriented shell for linux?

Body: Hotwire


问:
Read facebook URL in java
I searched a lot, read many blogs, articles, tutorials. But still there is no straight forward solution to my thought about reading facebook URL in java.

I know that I have to use OAuth, some other autorizations. All of them explains for the app login only.

I am reading this Url https://www.facebook.com/mohan.sunder.12 in my Java code using URLConnection.

I am reading the response from the connection in html file.Then, I am opening the html file in browser, but the page shows only login page of facebook.

How do I see this page as it is from java code.

答:
You should add facebook cookie like this.you can get facebook cookie from page inspect.Now facebook hide their HTML so you can not read HTML file like this.</p>

```<code>URL url = new URL("http://www.har.com");
                System.out.println(url);
                URLConnection conn = url.openConnection();
                conn.setRequestProperty(
                        "Cookie",
                        "datr=llhfWUipxjYoopesqYRfwauu; "
                                + "fr=05mmYQ8tPzse8Vh8A.AWUygf3_G8-tUg15fdgsOeopVuI.BZX1iW.dw.AAA.0.0.BZX1ij.AWUtvdAb; "
                                + "lu=gA; "
                                + "locale=en_US; "
                                + "c_user=100019219509174; "
                                + "xs=16%3ALUjK-gCfcctnLA%3A3%3A1499420835%3A-1%3A-1");
</code>```

Title: Read facebook URL in java

Body:
You should add facebook cookie like this.you can get facebook cookie from page inspect.Now facebook hide their HTML so you can not read HTML file like this.

URL url = new URL("http://www.har.com");
                System.out.println(url);
                URLConnection conn = url.openConnection();
                conn.setRequestProperty(
                        "Cookie",
                        "datr=llhfWUipxjYoopesqYRfwauu; "
                                + "fr=05mmYQ8tPzse8Vh8A.AWUygf3_G8-tUg15fdgsOeopVuI.BZX1iW.dw.AAA.0.0.BZX1ij.AWUtvdAb; "
                                + "lu=gA; "
                                + "locale=en_US; "
                                + "c_user=100019219509174; "
                                + "xs=16%3ALUjK-gCfcctnLA%3A3%3A1499420835%3A-1%3A-1");


问:
Five star rating component: How to get rid of all JavaScript code and replace it with only CSS?
I built a five star simple component (to be used for ranking). The component works fine. I used JavaScript to save the result (when user click on a star (which is not shown here) ).

The problem I have is that I didn't found a proper way to simulate the mouseover event (when you pass the mouse over a star and before clicking). So I did it using JavaScript.

Is there a proper way to use only CSS to achieve this (instead of all those JS lines)?

I'm sharing what I already did.

document.getElementById('star1').addEventListener('mouseover', function(){
 this.classList.remove("fa-star-o");
 this.classList.add("fa-star");
});
document.getElementById('star1').addEventListener('mouseout', function(){
 this.classList.remove("fa-star");
 this.classList.add("fa-star-o");
});

document.getElementById('star2').addEventListener('mouseover', function(){
 this.classList.remove("fa-star-o");
 this.classList.add("fa-star");
 document.getElementById('star1').classList.remove("fa-star-o");
 document.getElementById('star1').classList.add("fa-star");
});
document.getElementById('star2').addEventListener('mouseout', function(){
 this.classList.remove("fa-star");
 this.classList.add("fa-star-o");
 document.getElementById('star1').classList.remove("fa-star");
 document.getElementById('star1').classList.add("fa-star-o");
});

document.getElementById('star3').addEventListener('mouseover', function(){
 this.classList.remove("fa-star-o");
 this.classList.add("fa-star");
 document.getElementById('star1').classList.remove("fa-star-o");
 document.getElementById('star1').classList.add("fa-star");
 document.getElementById('star2').classList.remove("fa-star-o");
 document.getElementById('star2').classList.add("fa-star");
});
document.getElementById('star3').addEventListener('mouseout', function(){
 this.classList.remove("fa-star");
 this.classList.add("fa-star-o");
 document.getElementById('star1').classList.remove("fa-star");
 document.getElementById('star1').classList.add("fa-star-o");
 document.getElementById('star2').classList.remove("fa-star");
 document.getElementById('star2').classList.add("fa-star-o");
});

document.getElementById('star4').addEventListener('mouseover', function(){
 this.classList.remove("fa-star-o");
 this.classList.add("fa-star");
 document.getElementById('star1').classList.remove("fa-star-o");
 document.getElementById('star1').classList.add("fa-star");
 document.getElementById('star2').classList.remove("fa-star-o");
 document.getElementById('star2').classList.add("fa-star");
 document.getElementById('star3').classList.remove("fa-star-o");
 document.getElementById('star3').classList.add("fa-star");
});
document.getElementById('star4').addEventListener('mouseout', function(){
 this.classList.remove("fa-star");
 this.classList.add("fa-star-o");
 document.getElementById('star1').classList.remove("fa-star");
 document.getElementById('star1').classList.add("fa-star-o");
 document.getElementById('star2').classList.remove("fa-star");
 document.getElementById('star2').classList.add("fa-star-o");
 document.getElementById('star3').classList.remove("fa-star");
 document.getElementById('star3').classList.add("fa-star-o");
});

document.getElementById('star5').addEventListener('mouseover', function(){
 this.classList.remove("fa-star-o");
 this.classList.add("fa-star");
 document.getElementById('star1').classList.remove("fa-star-o");
 document.getElementById('star1').classList.add("fa-star");
 document.getElementById('star2').classList.remove("fa-star-o");
 document.getElementById('star2').classList.add("fa-star");
 document.getElementById('star3').classList.remove("fa-star-o");
 document.getElementById('star3').classList.add("fa-star");
 document.getElementById('star4').classList.remove("fa-star-o");
 document.getElementById('star4').classList.add("fa-star");
});
document.getElementById('star5').addEventListener('mouseout', function(){
 this.classList.remove("fa-star");
 this.classList.add("fa-star-o");
 document.getElementById('star1').classList.remove("fa-star");
 document.getElementById('star1').classList.add("fa-star-o");
 document.getElementById('star2').classList.remove("fa-star");
 document.getElementById('star2').classList.add("fa-star-o");
 document.getElementById('star3').classList.remove("fa-star");
 document.getElementById('star3').classList.add("fa-star-o");
 document.getElementById('star4').classList.remove("fa-star");
 document.getElementById('star4').classList.add("fa-star-o");
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.content > span > i{
    font-size: 50px;
    margin-right: 10px;
    color: #f0d124;
 cursor: pointer;
}
#star1:hover #star1{
 /*an example: I don't know what to do here???*/
}</code>```

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>

```

答:
This will do the full job. Looks "dirty" but works.

.content > span > i,.content > span > span{
    font-size: 50px;
    margin-right: 10px;
    color: #f0d124;
 cursor: pointer;
}

span > i:before{
  content:"\f006"
}

.content > span{
  position: relative;
  width: 56px;
  display: inline-block;
}

span > span{
  position: absolute;
}

span > i{
  position: absolute;
  z-index:1
}

.back{
  z-index:0;
}

.left_1{
  left:-60px;
}

.left_2{
  left:calc(-60px*2);
}

.left_3{
  left:calc(-60px*3);
}

.left_4{
  left:calc(-60px*4);
}

span:hover > i:before, span:hover > span:before {
   content:"\f005"
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>

<div class="content">
    <span><i id="star1" class="fa fa-star-o"></i></span>
    <span>
      <span class="fa fa-star-o back left_1"></span>
      <i id="star2" class="fa fa-star-o"></i>
    </span>
    <span>
      <span class="fa fa-star-o back left_2"></span>
      <span class="fa fa-star-o back left_1"></span>
      <i id="star3" class="fa fa-star-o"></i>
    </span>
    <span>
      <span class="fa fa-star-o back left_3"></span>
      <span class="fa fa-star-o back left_2"></span>
      <span class="fa fa-star-o back left_1"></span>
      <i id="star4" class="fa fa-star-o"></i>
    </span>
    <span>
      <span class="fa fa-star-o back left_4"></span>
      <span class="fa fa-star-o back left_3"></span>
      <span class="fa fa-star-o back left_2"></span>
      <span class="fa fa-star-o back left_1"></span>
      <i id="star5" class="fa fa-star-o"></i>
    </span>
</div></code>```

Body:
I built a five star simple component (to be used for ranking). The component works fine. I used JavaScript to save the result (when user click on a star (which is not shown here) ).

The problem I have is that I didn't found a proper way to simulate the mouseover event (when you pass the mouse over a star and before clicking). So I did it using JavaScript.

Is there a proper way to use only CSS to achieve this (instead of all those JS lines)?

I'm sharing what I already did.

document.getElementById('star1').addEventListener('mouseover', function(){
 this.classList.remove("fa-star-o");
 this.classList.add("fa-star");
});
document.getElementById('star1').addEventListener('mouseout', function(){
 this.classList.remove("fa-star");
 this.classList.add("fa-star-o");
});

document.getElementById('star2').addEventListener('mouseover', function(){
 this.classList.remove("fa-star-o");
 this.classList.add("fa-star");
 document.getElementById('star1').classList.remove("fa-star-o");
 document.getElementById('star1').classList.add("fa-star");
});
document.getElementById('star2').addEventListener('mouseout', function(){
 this.classList.remove("fa-star");
 this.classList.add("fa-star-o");
 document.getElementById('star1').classList.remove("fa-star");
 document.getElementById('star1').classList.add("fa-star-o");
});

document.getElementById('star3').addEventListener('mouseover', function(){
 this.classList.remove("fa-star-o");
 this.classList.add("fa-star");
 document.getElementById('star1').classList.remove("fa-star-o");
 document.getElementById('star1').classList.add("fa-star");
 document.getElementById('star2').classList.remove("fa-star-o");
 document.getElementById('star2').classList.add("fa-star");
});
document.getElementById('star3').addEventListener('mouseout', function(){
 this.classList.remove("fa-star");
 this.classList.add("fa-star-o");
 document.getElementById('star1').classList.remove("fa-star");
 document.getElementById('star1').classList.add("fa-star-o");
 document.getElementById('star2').classList.remove("fa-star");
 document.getElementById('star2').classList.add("fa-star-o");
});

document.getElementById('star4').addEventListener('mouseover', function(){
 this.classList.remove("fa-star-o");
 this.classList.add("fa-star");
 document.getElementById('star1').classList.remove("fa-star-o");
 document.getElementById('star1').classList.add("fa-star");
 document.getElementById('star2').classList.remove("fa-star-o");
 document.getElementById('star2').classList.add("fa-star");
 document.getElementById('star3').classList.remove("fa-star-o");
 document.getElementById('star3').classList.add("fa-star");
});
document.getElementById('star4').addEventListener('mouseout', function(){
 this.classList.remove("fa-star");
 this.classList.add("fa-star-o");
 document.getElementById('star1').classList.remove("fa-star");
 document.getElementById('star1').classList.add("fa-star-o");
 document.getElementById('star2').classList.remove("fa-star");
 document.getElementById('star2').classList.add("fa-star-o");
 document.getElementById('star3').classList.remove("fa-star");
 document.getElementById('star3').classList.add("fa-star-o");
});

document.getElementById('star5').addEventListener('mouseover', function(){
 this.classList.remove("fa-star-o");
 this.classList.add("fa-star");
 document.getElementById('star1').classList.remove("fa-star-o");
 document.getElementById('star1').classList.add("fa-star");
 document.getElementById('star2').classList.remove("fa-star-o");
 document.getElementById('star2').classList.add("fa-star");
 document.getElementById('star3').classList.remove("fa-star-o");
 document.getElementById('star3').classList.add("fa-star");
 document.getElementById('star4').classList.remove("fa-star-o");
 document.getElementById('star4').classList.add("fa-star");
});
document.getElementById('star5').addEventListener('mouseout', function(){
 this.classList.remove("fa-star");
 this.classList.add("fa-star-o");
 document.getElementById('star1').classList.remove("fa-star");
 document.getElementById('star1').classList.add("fa-star-o");
 document.getElementById('star2').classList.remove("fa-star");
 document.getElementById('star2').classList.add("fa-star-o");
 document.getElementById('star3').classList.remove("fa-star");
 document.getElementById('star3').classList.add("fa-star-o");
 document.getElementById('star4').classList.remove("fa-star");
 document.getElementById('star4').classList.add("fa-star-o");
});

.content > span > i{
    font-size: 50px;
    margin-right: 10px;
    color: #f0d124;
 cursor: pointer;
}
#star1:hover #star1{
 /*an example: I don't know what to do here???*/
}

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>

Body:
This will do the full job. Looks "dirty" but works.

.content > span > i,.content > span > span{
    font-size: 50px;
    margin-right: 10px;
    color: #f0d124;
 cursor: pointer;
}

span > i:before{
  content:"\f006"
}

.content > span{
  position: relative;
  width: 56px;
  display: inline-block;
}

span > span{
  position: absolute;
}

span > i{
  position: absolute;
  z-index:1
}

.back{
  z-index:0;
}

.left_1{
  left:-60px;
}

.left_2{
  left:calc(-60px*2);
}

.left_3{
  left:calc(-60px*3);
}

.left_4{
  left:calc(-60px*4);
}

span:hover > i:before, span:hover > span:before {
   content:"\f005"
}

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>

<div class="content">
    <span><i id="star1" class="fa fa-star-o"></i></span>
    <span>
      <span class="fa fa-star-o back left_1"></span>
      <i id="star2" class="fa fa-star-o"></i>
    </span>
    <span>
      <span class="fa fa-star-o back left_2"></span>
      <span class="fa fa-star-o back left_1"></span>
      <i id="star3" class="fa fa-star-o"></i>
    </span>
    <span>
      <span class="fa fa-star-o back left_3"></span>
      <span class="fa fa-star-o back left_2"></span>
      <span class="fa fa-star-o back left_1"></span>
      <i id="star4" class="fa fa-star-o"></i>
    </span>
    <span>
      <span class="fa fa-star-o back left_4"></span>
      <span class="fa fa-star-o back left_3"></span>
      <span class="fa fa-star-o back left_2"></span>
      <span class="fa fa-star-o back left_1"></span>
      <i id="star5" class="fa fa-star-o"></i>
    </span>
</div>


问:
Push Notification not registering with requested tag
I am following the Azure Mobile Services e-book for setting up Push Notifications:

https://adrianhall.github.io/develop-mobile-apps-with-csharp-and-azure/chapter5/android/#registering-for-push-notifications

But am having problems with registering with a Tag:

```<code>            var registrationId = GcmClient.GetRegistrationId(RootView);
            //var push = client.GetPush();
            //await push.RegisterAsync(registrationId);

            var installation = new DeviceInstallation
            {
                InstallationId = client.InstallationId,
                Platform = "gcm",
                PushChannel = registrationId
            };
            // Set up tags to request
            installation.Tags.Add("topic:Sports");
            // Set up templates to request
            PushTemplate genericTemplate = new PushTemplate
            {
                Body = @"{""data"":{""message"":""$(message)""}}"
            };
            installation.Templates.Add("genericTemplate", genericTemplate);

            // Register with NH
            var response = await client.InvokeApiAsync<DeviceInstallation, DeviceInstallation>(
                $"/push/installations/{client.InstallationId}",
                installation,
                HttpMethod.Put,
                new Dictionary<string, string>());
</code>```

I have ensured that the tag is listed in the Azure Portal as a "Client Requested" tag, but still my registrations appear without the tag in the Device Registrations:

Any ideas what I am doing wrong?

答:
It would appear that the e-book is out of date and is dealing with the old version of Mobile Services instead of Azure App Service Mobile Apps (seriously, how is anyone supposed to google around for the different versions when they are named so similarly?!)

https://github.com/Azure-Samples/app-service-mobile-dotnet-backend-quickstart/blob/master/README.md#push-to-users

(Emphasis is mine)

When a mobile app registers for push notifications using an Azure App Service Mobile Apps backend, there are two default tags that can get added to the registration in Azure Notification Hubs: the installation ID, which is unique to the app on a given device, and the user ID, which is only added when the user has been previously authenticated. Any other tags that get supplied by the client are ignored, which is by design. (Note that this differs from Mobile Services, where the client could supply any tag and there were hooks into the registration process on the backend to validate tags on incoming registrations.)

Because the client can’t add tags and at the same time there are no service-side hooks into the push notification registration process, the client needs to do the work of adding new tags to a given registration.

So the reason it was not working was because the code in the e-book is out of date and does not work with the latest version.

I had to create an Api Controller to allow the Tag to be registered using the code in the above link.  Then the client apps have to call this endpoint just after they have called the two commented methods in the sample code in my question.

Body:
I am following the Azure Mobile Services e-book for setting up Push Notifications:

https://adrianhall.github.io/develop-mobile-apps-with-csharp-and-azure/chapter5/android/#registering-for-push-notifications

But am having problems with registering with a Tag:

            var registrationId = GcmClient.GetRegistrationId(RootView);
            //var push = client.GetPush();
            //await push.RegisterAsync(registrationId);

            var installation = new DeviceInstallation
            {
                InstallationId = client.InstallationId,
                Platform = "gcm",
                PushChannel = registrationId
            };
            // Set up tags to request
            installation.Tags.Add("topic:Sports");
            // Set up templates to request
            PushTemplate genericTemplate = new PushTemplate
            {
                Body = @"{""data"":{""message"":""$(message)""}}"
            };
            installation.Templates.Add("genericTemplate", genericTemplate);

            // Register with NH
            var response = await client.InvokeApiAsync<DeviceInstallation, DeviceInstallation>(
                $"/push/installations/{client.InstallationId}",
                installation,
                HttpMethod.Put,
                new Dictionary<string, string>());

I have ensured that the tag is listed in the Azure Portal as a "Client Requested" tag, but still my registrations appear without the tag in the Device Registrations:

Any ideas what I am doing wrong?


问:
Linking Curl to Windows Runtime VC++ Project [UWP 10 Mobile App]
am trying to link curl in a C++ Windows Runtime Component Project . I did the following 1. Installed curl packages from nugget . So referenced Packages are rmt_curl, rmt_openssl, rmt_libssh2, openssl, rmt_zlib, zlib, libssh2, curl. 2. Preprocess Defintions I added WIN32_LEAN_AND_MEAN, CURL_STATIC_LIB . I did not add static library dependency because: a. I could not find libcurl.lib compiled for ARM platform. 2. Because I installed it through nugget.

Error

Severity Code Description Project File Line Suppression State Error LNK2019 unresolved external symbol curl_easy_init referenced in function "public: virtual void __cdecl WindowsRuntimeComponent2::Class1::[WindowsRuntimeComponent2::__IClass1PublicNonVirtuals]::test(void)" (?test@?Q__IClass1PublicNonVirtuals@WindowsRuntimeComponent2@@Class1@2@U$AAAXXZ) WindowsRunentimeComponent2 c:\Users\Abhishek\documents\visual studio 2015\Projects\WindowsRuntimeComponent2\WindowsRuntimeComponent2\Class1.obj

Can somebody please help. Attached in the screenshot of project settings.

Vc++ Project Settings

答: Don't know if this will help, but it's CURL_STATICLIB not CURL_STATIC_LIB</p>


问:
Bootstrap modal in iframe
I have a page with iframe on it and where jquery.js and bootstrap.js are loaded before the body tag.

```<code><html>
<head></head>
<body>
<iframe src="test.html"></iframe>
<script src="/assets/8bf00db7/jquery.js"></script>
<script src="/assets/383389f4/js/bootstrap.js"></script>
</body>
</html>
</code>```

In test.html scripts are loaded in the same way.

```<code><html>
<head></head>
<body>
<button>Click</button>
<div class="modal">Model content here</div>
<script src="/assets/8bf00db7/jquery.js"></script>
<script src="/assets/383389f4/js/bootstrap.js"></script>
<script src="/js/main.js"></script>
</body>
</html>
</code>```

There is also main.js file with this code.

```<code>$(function() {
    $('button').click(function() {
        $('.modal').modal('show');
    });
});
</code>```

When I click, I get an error: Uncaught TypeError: $(...).modal is not a function. Please help to fix it.

答:
Imports must be done in the header tag:

```<code><html>
<head>

<script src="/assets/8bf00db7/jquery.js"></script>
<script src="/assets/383389f4/js/bootstrap.js"></script>
<script src="/js/main.js"></script>

</head>
<body>
<button>Click</button>
<div class="modal">Model content here</div>

</body>
</html>
</code>```

simple working example of bootstrap modal: http://jsfiddle.net/h3WDq/

Title: Bootstrap modal in iframe

Body:
I have a page with iframe on it and where jquery.js and bootstrap.js are loaded before the body tag.

In test.html scripts are loaded in the same way.

<button>Click</button>

Model content here

There is also main.js file with this code.

$(function() {
    $('button').click(function() {
        $('.modal').modal('show');
    });
});

When I click, I get an error: Uncaught TypeError: $(...).modal is not a function. Please help to fix it.

Body:
Imports must be done in the header tag:

<html>
<head>

<script src="/assets/8bf00db7/jquery.js"></script>
<script src="/assets/383389f4/js/bootstrap.js"></script>
<script src="/js/main.js"></script>

</head>
<body>
<button>Click</button>
<div class="modal">Model content here</div>

</body>
</html>

simple working example of bootstrap modal: http://jsfiddle.net/h3WDq/


问:
Junit Test is Not working
I'm getting below exception when Debugging my application using Junit

IDE Used-Eclipse Mar

Application Details-

JDK-1.7,Spring4 and Junit4 and hamcrest-all-1.3.jar

CodeBase-

```<code>import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.app.api.facade.LoginServiceFacade;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:/test-spring.xml")
public class LoginApi4JunitTest {
    @Autowired
    private LoginServiceFacade loginServiceFacade;

    @Test
    public void testIsUserExist()throws Exception{
        Boolean isUserExist=loginServiceFacade.isUserExist("xyz");
        Assert.assertEquals(Boolean.TRUE, isUserExist);
    }

}
</code>```

Exception-

```<code>java.lang.NoClassDefFoundError: org/junit/runner/manipulation/Filter
     at java.lang.Class.forName0(Native Method)
     at java.lang.Class.forName(Class.java:191)
      at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.loadTestLoaderClass(RemoteTestRunner.java:320)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.createRawTestLoader(RemoteTestRunner.java:310)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.createLoader(RemoteTestRunner.java:305)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.defaultInit(RemoteTestRunner.java:283)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.init(RemoteTestRunner.java:207)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:191)
Caused by: java.lang.ClassNotFoundException: org.junit.runner.manipulation.Filter
    at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
    ... 8 more
</code>```

I already added Junit4 and  hamcrest-all-1.3.jar in myBuild path.

答:
As have seen this when there is a broken/missing maven container.
Edit .classpath and remove the entry:

classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER"

Title: Junit Test is Not working

Body:
I'm getting below exception when Debugging my application using Junit

IDE Used-Eclipse Mar

Application Details-

JDK-1.7,Spring4 and Junit4 and hamcrest-all-1.3.jar

CodeBase-

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.app.api.facade.LoginServiceFacade;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:/test-spring.xml")
public class LoginApi4JunitTest {
    @Autowired
    private LoginServiceFacade loginServiceFacade;

    @Test
    public void testIsUserExist()throws Exception{
        Boolean isUserExist=loginServiceFacade.isUserExist("xyz");
        Assert.assertEquals(Boolean.TRUE, isUserExist);
    }

}

Exception-

java.lang.NoClassDefFoundError: org/junit/runner/manipulation/Filter
     at java.lang.Class.forName0(Native Method)
     at java.lang.Class.forName(Class.java:191)
      at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.loadTestLoaderClass(RemoteTestRunner.java:320)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.createRawTestLoader(RemoteTestRunner.java:310)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.createLoader(RemoteTestRunner.java:305)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.defaultInit(RemoteTestRunner.java:283)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.init(RemoteTestRunner.java:207)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:191)
Caused by: java.lang.ClassNotFoundException: org.junit.runner.manipulation.Filter
    at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
    ... 8 more

I already added Junit4 and  hamcrest-all-1.3.jar in myBuild path.


问:
Deployed Firebase Function Cannot Execute HTTP GET to external API?
I am attempting to create my first Google Home Action as with the same functinality of my Amazon Alexa Skill.  The way this action works is, you execute an intent, and that calls a function in my code.  When the function is called, it sends off a GET to an external API to pull some data.

Now when I run this locally using: firebase serve --only functions and ngrok.  These will allow me to test the function on API.AI and it works fine.

But when I decide to deploy this to firebase using: firebase deploy --only functions, it simply does not work and throws this error:

```<code>error: { RequestError: Error: getaddrinfo EAI_AGAIN newsapi.org:443
    at new RequestError (/user_code/node_modules/request-promise/node_modules/request-promise-core/lib/errors.js:14:15)
    at Request.plumbing.callback (/user_code/node_modules/request-promise/node_modules/request-promise-core/lib/plumbing.js:87:29)
    at Request.RP$callback [as _callback] (/user_code/node_modules/request-promise/node_modules/request-promise-core/lib/plumbing.js:46:31)
    at self.callback (/user_code/node_modules/request/request.js:188:22)
    at emitOne (events.js:96:13)
    at Request.emit (events.js:188:7)
    at Request.onRequestError (/user_code/node_modules/request/request.js:884:8)
    at emitOne (events.js:96:13)
    at ClientRequest.emit (events.js:188:7)
    at TLSSocket.socketErrorListener (_http_client.js:310:9)
    at emitOne (events.js:96:13)
    at TLSSocket.emit (events.js:188:7)
    at connectErrorNT (net.js:1020:8)
    at _combinedTickCallback (internal/process/next_tick.js:74:11)
    at process._tickDomainCallback (internal/process/next_tick.js:122:9)
  name: 'RequestError',
  message: 'Error: getaddrinfo EAI_AGAIN newsapi.org:443',
  cause:
   { Error: getaddrinfo EAI_AGAIN newsapi.org:443
       at Object.exports._errnoException (util.js:1026:11)
       at errnoException (dns.js:33:15)
       at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:76:26)
     code: 'EAI_AGAIN',
     errno: 'EAI_AGAIN',
     syscall: 'getaddrinfo',
     hostname: 'newsapi.org',
     host: 'newsapi.org',
     port: 443 },
  error:
   { Error: getaddrinfo EAI_AGAIN newsapi.org:443
       at Object.exports._errnoException (util.js:1026:11)
       at errnoException (dns.js:33:15)
       at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:76:26)
     code: 'EAI_AGAIN',
     errno: 'EAI_AGAIN',
     syscall: 'getaddrinfo',
     hostname: 'newsapi.org',
     host: 'newsapi.org',
     port: 443 },
  options:
   { uri: 'https://newsapi.org/v1/articles?source=hacker-news&sortBy=top&apiKey=8b87b4978b22493cadeb351cce01d52a',
     headers: { 'User-Agent': 'Request-Promise' },
     family: 4,
     json: true,
     callback: [Function: RP$callback],
     transform: undefined,
     simple: true,
     resolveWithFullResponse: false,
     transform2xxOnly: false },
  response: undefined }
</code>```

I cannot seem to find any reason why this would not work, as I can test it locally and get the data by hitting the same URL that is used in the request.  In this example, I am using request-promise to complete the request, but I have also used the libraries: got, request, and https.

How can I overcome this problem?

答: The only thing that I found for this could be that I am not using a paid Firebase plan</p>

Body:
I am attempting to create my first Google Home Action as with the same functinality of my Amazon Alexa Skill.  The way this action works is, you execute an intent, and that calls a function in my code.  When the function is called, it sends off a GET to an external API to pull some data.

Now when I run this locally using: firebase serve --only functions and ngrok.  These will allow me to test the function on API.AI and it works fine.

But when I decide to deploy this to firebase using: firebase deploy --only functions, it simply does not work and throws this error:

error: { RequestError: Error: getaddrinfo EAI_AGAIN newsapi.org:443
    at new RequestError (/user_code/node_modules/request-promise/node_modules/request-promise-core/lib/errors.js:14:15)
    at Request.plumbing.callback (/user_code/node_modules/request-promise/node_modules/request-promise-core/lib/plumbing.js:87:29)
    at Request.RP$callback [as _callback] (/user_code/node_modules/request-promise/node_modules/request-promise-core/lib/plumbing.js:46:31)
    at self.callback (/user_code/node_modules/request/request.js:188:22)
    at emitOne (events.js:96:13)
    at Request.emit (events.js:188:7)
    at Request.onRequestError (/user_code/node_modules/request/request.js:884:8)
    at emitOne (events.js:96:13)
    at ClientRequest.emit (events.js:188:7)
    at TLSSocket.socketErrorListener (_http_client.js:310:9)
    at emitOne (events.js:96:13)
    at TLSSocket.emit (events.js:188:7)
    at connectErrorNT (net.js:1020:8)
    at _combinedTickCallback (internal/process/next_tick.js:74:11)
    at process._tickDomainCallback (internal/process/next_tick.js:122:9)
  name: 'RequestError',
  message: 'Error: getaddrinfo EAI_AGAIN newsapi.org:443',
  cause:
   { Error: getaddrinfo EAI_AGAIN newsapi.org:443
       at Object.exports._errnoException (util.js:1026:11)
       at errnoException (dns.js:33:15)
       at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:76:26)
     code: 'EAI_AGAIN',
     errno: 'EAI_AGAIN',
     syscall: 'getaddrinfo',
     hostname: 'newsapi.org',
     host: 'newsapi.org',
     port: 443 },
  error:
   { Error: getaddrinfo EAI_AGAIN newsapi.org:443
       at Object.exports._errnoException (util.js:1026:11)
       at errnoException (dns.js:33:15)
       at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:76:26)
     code: 'EAI_AGAIN',
     errno: 'EAI_AGAIN',
     syscall: 'getaddrinfo',
     hostname: 'newsapi.org',
     host: 'newsapi.org',
     port: 443 },
  options:
   { uri: 'https://newsapi.org/v1/articles?source=hacker-news&sortBy=top&apiKey=8b87b4978b22493cadeb351cce01d52a',
     headers: { 'User-Agent': 'Request-Promise' },
     family: 4,
     json: true,
     callback: [Function: RP$callback],
     transform: undefined,
     simple: true,
     resolveWithFullResponse: false,
     transform2xxOnly: false },
  response: undefined }

I cannot seem to find any reason why this would not work, as I can test it locally and get the data by hitting the same URL that is used in the request.  In this example, I am using request-promise to complete the request, but I have also used the libraries: got, request, and https.

How can I overcome this problem?


问:
How can I allow multiple users to access/edit a microsoft access database?
Now I know right off the bat that Microsoft access isn't the ideal client for multiple users accessing it but it's the only one I've got right now. I have built a small program as a sort of inventory management system. There are currently three users that will be using it regularly and at the same time. One issue I am running into with this is that sometimes the database will not be accessible and will give an error stating that the file is already in use by "so and so" user. The other issue is that I'm getting a similar error every now and then where it states "The database has been placed in a state by user  on machine  that prevents it from being opened or locked". I am connecting to the database through an ACE OLEDB connection using the line below

```<code>con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=P:\Tool & Cutter Grinding\Tool Cutter Database.accdb;Persist Security Info = False"
</code>```

I have also changed some of the settings in the actual access database such as:

Enable all macros

Add the folder the database is in to the trusted locations list

Confirm that the database is set to open in shared mode by default

I don't know if there is something small I've missed or a setting I need to change but as of yet, the problem is still persisting.

Below is an example of how I am using the database. I am using string based SQL commands but am not too familiar with DataSet/DataTable/etc. items, so I may be doing something incorrectly.

```<code> 'close connection from any previous session
    con.Close()

    'clear dataset so as not to append data
    ds.Clear()

    'Select SQL query that selects ALL records from a table
    Dim str As String = "SELECT * FROM " & "[" & table & "]" & ""
    con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=P:\Tool & Cutter Grinding\Tool Cutter Database.accdb;Persist Security Info = False"

    'use try catch statement to open the connection
    Try
        con.Open()
    Catch ex As Exception
        MsgBox(Convert.ToString(ex))
    End Try

    'use try catch statement to add a table (dt) to the dataset (ds) in order to store values
    Try
        ds.Tables.Add(dt)
    Catch ex As Exception

    End Try

    'create new dataadapter object using the sql string from above and the connection created above
    da = New OleDbDataAdapter(str, con)

    'create new command builder in order to excecute the SELECT SQL statement using the dataadapter created (da)
    'specify prefix and suffix for cb
    Dim cb = New OleDbCommandBuilder(da) With {
        .QuotePrefix = "[",
        .QuoteSuffix = "]"
    }

    'use try catch statement to fill the datatable (dt) using the dataadapter (da)
    Try
        da.Fill(dt)
    Catch ex As Exception
        MsgBox(Convert.ToString(ex))
    End Try

    'set the datasource of the datagridview to the datatable
    dgv.DataSource = dt.DefaultView

    'close the connection to the database
    con.Close()
</code>```

答:
but its [sic] the only one I've got right now

Actually, it's not.

Have a look at SQL Server Compact. It's free, it's small and it handles multiple users with aplomb.

You can add all the references you need using NuGet.

Body:
Now I know right off the bat that Microsoft access isn't the ideal client for multiple users accessing it but it's the only one I've got right now. I have built a small program as a sort of inventory management system. There are currently three users that will be using it regularly and at the same time. One issue I am running into with this is that sometimes the database will not be accessible and will give an error stating that the file is already in use by "so and so" user. The other issue is that I'm getting a similar error every now and then where it states "The database has been placed in a state by user  on machine  that prevents it from being opened or locked". I am connecting to the database through an ACE OLEDB connection using the line below

con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=P:\Tool & Cutter Grinding\Tool Cutter Database.accdb;Persist Security Info = False"

I have also changed some of the settings in the actual access database such as:

Enable all macros

Add the folder the database is in to the trusted locations list

Confirm that the database is set to open in shared mode by default

I don't know if there is something small I've missed or a setting I need to change but as of yet, the problem is still persisting.

Below is an example of how I am using the database. I am using string based SQL commands but am not too familiar with DataSet/DataTable/etc. items, so I may be doing something incorrectly.

 'close connection from any previous session
    con.Close()

    'clear dataset so as not to append data
    ds.Clear()

    'Select SQL query that selects ALL records from a table
    Dim str As String = "SELECT * FROM " & "[" & table & "]" & ""
    con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=P:\Tool & Cutter Grinding\Tool Cutter Database.accdb;Persist Security Info = False"

    'use try catch statement to open the connection
    Try
        con.Open()
    Catch ex As Exception
        MsgBox(Convert.ToString(ex))
    End Try

    'use try catch statement to add a table (dt) to the dataset (ds) in order to store values
    Try
        ds.Tables.Add(dt)
    Catch ex As Exception

    End Try

    'create new dataadapter object using the sql string from above and the connection created above
    da = New OleDbDataAdapter(str, con)

    'create new command builder in order to excecute the SELECT SQL statement using the dataadapter created (da)
    'specify prefix and suffix for cb
    Dim cb = New OleDbCommandBuilder(da) With {
        .QuotePrefix = "[",
        .QuoteSuffix = "]"
    }

    'use try catch statement to fill the datatable (dt) using the dataadapter (da)
    Try
        da.Fill(dt)
    Catch ex As Exception
        MsgBox(Convert.ToString(ex))
    End Try

    'set the datasource of the datagridview to the datatable
    dgv.DataSource = dt.DefaultView

    'close the connection to the database
    con.Close()


问:
Identify the .Net framework version
How can I find which dotnet Framework version is installed via Powershell?

I found some code but it is not working, or I do not know how to run it.

Can you please help me develop any script which can be run on cmd and collect .Net framework version?.

答:
There was an error in the PowerShell code in your linked Question, here's the working version of it which gives an output like this:

```
v2.0.50727 2.0.50727.4927 SP 2
v3.0 3.0.30729.4926 SP 2
v3.5 3.5.30729.4926 SP 1
v4 Client 4.6.01586
v4 Full 4.6.01586
v4.0 Client 4.0.0.0
```

```<code>function Get-KeyPropertyValue($key, $property) {
    if ($key.Property -contains $property) {
        Get-ItemProperty $key.PSPath -name $property | Select-Object -expand $property
    }
}

function Get-VersionName($key) {
    $name = Get-KeyPropertyValue $key Version
    $sp = Get-KeyPropertyValue $key SP
    if ($sp) {
        "$($_.PSChildName) $name SP $sp"
    }
    else {
        "$($_.PSChildName) $name"
    }
}

function Get-FrameworkVersion {
    Get-ChildItem "hklm:\SOFTWARE\Microsoft\NET Framework Setup\NDP\" | Where-Object {$_.PSChildName -like "v*"} | ForEach-Object {
        if ( $_.Property -contains "Version") {
            Get-VersionName $_
        }
        else {
            $parent = $_
            Get-ChildItem $_.PSPath | ForEach-Object {
                $versionName = Get-VersionName $_
                "$($parent.PSChildName) $versionName"
            }
        }
    }
}

Get-FrameworkVersion
</code>```

EDIT:

```<code>if (Test-Path "hklm:\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full") {
    switch (Get-KeyPropertyValue (Get-Item $v4Directory) Release) {
        378389 {".NET Framework 4.5"; break; }
        378675 {".NET Framework 4.5.1 installed with Windows 8.1 or Windows Server 2012 R2"; break; }
        378758 {".NET Framework 4.5.1 installed on Windows 8, Windows 7 SP1, or Windows Vista SP2"; break; }
        379893 {".NET Framework 4.5.2"; break; }
        { 393295, 393297 -contains $_} {".NET Framework 4.6"; break; }
        { 394254, 394271 -contains $_} {".NET Framework 4.6.1"; break; }
        { 394802, 394806 -contains $_} {".NET Framework 4.6.2"; break; }
    }
}
</code>```

Title: Identify the .Net framework version

Body:
There was an error in the PowerShell code in your linked Question, here's the working version of it which gives an output like this:

v2.0.50727 2.0.50727.4927 SP 2
v3.0 3.0.30729.4926 SP 2
v3.5 3.5.30729.4926 SP 1
v4 Client 4.6.01586
v4 Full 4.6.01586
v4.0 Client 4.0.0.0

function Get-KeyPropertyValue($key, $property) {
    if ($key.Property -contains $property) {
        Get-ItemProperty $key.PSPath -name $property | Select-Object -expand $property
    }
}

function Get-VersionName($key) {
    $name = Get-KeyPropertyValue $key Version
    $sp = Get-KeyPropertyValue $key SP
    if ($sp) {
        "$($_.PSChildName) $name SP $sp"
    }
    else {
        "$($_.PSChildName) $name"
    }
}

function Get-FrameworkVersion {
    Get-ChildItem "hklm:\SOFTWARE\Microsoft\NET Framework Setup\NDP\" | Where-Object {$_.PSChildName -like "v*"} | ForEach-Object {
        if ( $_.Property -contains "Version") {
            Get-VersionName $_
        }
        else {
            $parent = $_
            Get-ChildItem $_.PSPath | ForEach-Object {
                $versionName = Get-VersionName $_
                "$($parent.PSChildName) $versionName"
            }
        }
    }
}

Get-FrameworkVersion

EDIT:

if (Test-Path "hklm:\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full") {
    switch (Get-KeyPropertyValue (Get-Item $v4Directory) Release) {
        378389 {".NET Framework 4.5"; break; }
        378675 {".NET Framework 4.5.1 installed with Windows 8.1 or Windows Server 2012 R2"; break; }
        378758 {".NET Framework 4.5.1 installed on Windows 8, Windows 7 SP1, or Windows Vista SP2"; break; }
        379893 {".NET Framework 4.5.2"; break; }
        { 393295, 393297 -contains $_} {".NET Framework 4.6"; break; }
        { 394254, 394271 -contains $_} {".NET Framework 4.6.1"; break; }
        { 394802, 394806 -contains $_} {".NET Framework 4.6.2"; break; }
    }
}


问:
Cannot determine how to use Redux and React-router on the same component
I am starting to learn typescript and the is a behaviour that I don't understand.

I got this error:

```<code>Type 'ComponentClass<{}>' is not assignable to type 'StatelessComponent<void | RouteComponentProps<any>> | ComponentClass<void | RouteComponentProps<a...'.
  Type 'ComponentClass<{}>' is not assignable to type 'ComponentClass<void | RouteComponentProps<any>>'.
    Type '{}' is not assignable to type 'void | RouteComponentProps<any>'.
      Type '{}' is not assignable to type 'RouteComponentProps<any>'.
</code>```

Here is my App component :

```<code>interface AppProps extends React.Props<void> {
  todos: TodoItemData[];
  actions: typeof TodoActions;
};

interface AppState {
  /* empty */
}

class App extends React.Component<AppProps, AppState>{
  render() {return (<div></div>);
  }
}

function mapStateToProps(state: RootState) {
  return {
    todos: state.todos
  };
}

function mapDispatchToProps(dispatch) {
  return {
    actions: bindActionCreators(TodoActions as any, dispatch)
  };
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(App);
</code>```

If I change in the declaration of my App component AppProps by void or React.Props I got no errors but I always have one with AppProps.

I don't understang why it's not working, AppProps is extending from React.Props. Did you see the mistake ?

答:
This has to do with react-router and redux you have to add types to your connect function:</p>

```<code>interface AppProps {
  todos: TodoItemData[];
};

interface DispatchProps {
  actions: typeof TodoActions;
}

interface AppState {
  /* empty */
}

class App extends React.Component<AppProps & DispatchProps & RouteComponentProps, AppState>{
  render() {return (<div></div>);
  }
}

function mapStateToProps(state: RootState) {
  return {
    todos: state.todos
  };
}

function mapDispatchToProps(dispatch) {
  return {
    actions: bindActionCreators(TodoActions as any, dispatch)
  };
}

export default connect<AppProps, DispatchProps, RouteComponentProps<any>(
  mapStateToProps,
  mapDispatchToProps
)(App);
</code>```

Body:
I am starting to learn typescript and the is a behaviour that I don't understand.

I got this error:

Type 'ComponentClass<{}>' is not assignable to type 'StatelessComponent<void | RouteComponentProps<any>> | ComponentClass<void | RouteComponentProps<a...'.
  Type 'ComponentClass<{}>' is not assignable to type 'ComponentClass<void | RouteComponentProps<any>>'.
    Type '{}' is not assignable to type 'void | RouteComponentProps<any>'.
      Type '{}' is not assignable to type 'RouteComponentProps<any>'.

Here is my App component :

interface AppProps extends React.Props<void> {
  todos: TodoItemData[];
  actions: typeof TodoActions;
};

interface AppState {
  /* empty */
}

class App extends React.Component<AppProps, AppState>{
  render() {return (

);
  }
}

function mapStateToProps(state: RootState) {
  return {
    todos: state.todos
  };
}

function mapDispatchToProps(dispatch) {
  return {
    actions: bindActionCreators(TodoActions as any, dispatch)
  };
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(App);

If I change in the declaration of my App component AppProps by void or React.Props I got no errors but I always have one with AppProps.

I don't understang why it's not working, AppProps is extending from React.Props. Did you see the mistake ?

Body:
This has to do with react-router and redux you have to add types to your connect function:

interface AppProps {
  todos: TodoItemData[];
};

interface DispatchProps {
  actions: typeof TodoActions;
}

interface AppState {
  /* empty */
}

class App extends React.Component<AppProps & DispatchProps & RouteComponentProps, AppState>{
  render() {return (<div></div>);
  }
}

function mapStateToProps(state: RootState) {
  return {
    todos: state.todos
  };
}

function mapDispatchToProps(dispatch) {
  return {
    actions: bindActionCreators(TodoActions as any, dispatch)
  };
}

export default connect<AppProps, DispatchProps, RouteComponentProps<any>(
  mapStateToProps,
  mapDispatchToProps
)(App);


问:
How can I monkey-patch an instance method in Perl?
I'm trying to monkey-patch (duck-punch :-) a LWP::UserAgent instance, like so:

```<code>sub _user_agent_get_basic_credentials_patch {
  return ($username, $password);
}

my $agent = LWP::UserAgent->new();
$agent->get_basic_credentials = _user_agent_get_basic_credentials_patch;
</code>```

This isn't the right syntax -- it yields:

Can't modify non-lvalue subroutine
  call at [module] line [lineno].

As I recall (from Programming Perl), dispatch lookup is performed dynamically based on the blessed package (ref($agent), I believe), so I'm not sure how instance monkey patching would even work without affecting the blessed package.

I know that I can subclass the UserAgent, but I would prefer the more concise monkey-patched approach. Consenting adults and what have you. ;-)

OwnerDisplayName: cdleary

Body:
I'm trying to monkey-patch (duck-punch :-) a LWP::UserAgent instance, like so:

sub _user_agent_get_basic_credentials_patch {
  return ($username, $password);
}

my $agent = LWP::UserAgent->new();
$agent->get_basic_credentials = _user_agent_get_basic_credentials_patch;

This isn't the right syntax -- it yields:

Can't modify non-lvalue subroutine
  call at [module] line [lineno].

As I recall (from Programming Perl), dispatch lookup is performed dynamically based on the blessed package (ref($agent), I believe), so I'm not sure how instance monkey patching would even work without affecting the blessed package.

I know that I can subclass the UserAgent, but I would prefer the more concise monkey-patched approach. Consenting adults and what have you. ;-)

LastEditorDisplayName: cdleary

OwnerDisplayName: Fayland Lam


问:
zend form email validation
I have the following code to generate an input field for user's email address

```<code>$email = new Zend_Form_Element_Text('email');
$email->setLabel('Email:')
    ->addFilters(array('StringTrim', 'StripTags'))
    ->addValidator('EmailAddress')
    ->addValidator(new Zend_Validate_Db_NoRecordExists(
                                                        array(
                                                                'adapter'=>Zend_Registry::get('user_db'),
                                                                'field'=>'email',
                                                                'table'=>'tbl_user'
                                                                )))
    ->setRequired(true)
    ->setDecorators(array(
                            array('Label', array('escape'=>false, 'placement'=>'append')),
                            array('ViewHelper'),
                            array('Errors'),
                            array('Description',array('escape'=>false,'tag'=>'div')),
                            array('HtmlTag', array('tag' => 'div')),
                        ));
$this->addElement($email);
</code>```

now the problem is if user enter invalid hostname for email, it generate 3 errors. lets say user enter 'admin@l' as email address, and the errors will be

* 'l' is no valid hostname for email address 'admin@l'

* 'l' does not match the expected structure for a DNS hostname

* 'l' appears to be a local network name but local network names are not allowed

I just want it to give only one custom error instead of all these. If I set error message "Invalid Email Address" by addErrorMessage method, it will again generate the same message against the db_validation.

答:
```<code>$email->addErrorMessage("Please Enter Valid Email Address");
</code>```

you can use custom validator. create a file Email.php inside folder Validate in your library folder at the root of project

```<code>class Validate_Email extends Zend_Validate_Abstract
{

    const INVALID = 'Email is required';
    protected $_messageTemplates = array(
    self::INVALID => "Invalid Email Address",
    self::ALREADYUSED => "Email is already registered"
    );

     public function isValid($value)
     {
          if(preg_match($email_regex, trim($value))){
            $dataModel = new Application_Model_Data(); //check if the email exists
            if(!$dataModel->email_exists($value)){
                return true;
            }
            else{
                $this->_error(self::ALREADYUSED);
                return false;
            }
          }
          else
          {
            $this->_error(self::INVALID);
            return false;
          }
     }
}
</code>```

and in you  form.php file

```<code>    $mailValidator = new Validate_Email();
    $email->addValidator($mailValidator, true);
</code>```

Don't know if it works or not but for me it worked in case of telephone. Courtesy of  http://softwareobjects.net/technology/other/zend-framework-1-10-7-telephone-validator/

Title: zend form email validation

Body:
I have the following code to generate an input field for user's email address

$email = new Zend_Form_Element_Text('email');
$email->setLabel('Email:')
    ->addFilters(array('StringTrim', 'StripTags'))
    ->addValidator('EmailAddress')
    ->addValidator(new Zend_Validate_Db_NoRecordExists(
                                                        array(
                                                                'adapter'=>Zend_Registry::get('user_db'),
                                                                'field'=>'email',
                                                                'table'=>'tbl_user'
                                                                )))
    ->setRequired(true)
    ->setDecorators(array(
                            array('Label', array('escape'=>false, 'placement'=>'append')),
                            array('ViewHelper'),
                            array('Errors'),
                            array('Description',array('escape'=>false,'tag'=>'div')),
                            array('HtmlTag', array('tag' => 'div')),
                        ));
$this->addElement($email);

now the problem is if user enter invalid hostname for email, it generate 3 errors. lets say user enter 'admin@l' as email address, and the errors will be

* 'l' is no valid hostname for email address 'admin@l'

* 'l' does not match the expected structure for a DNS hostname

* 'l' appears to be a local network name but local network names are not allowed

I just want it to give only one custom error instead of all these. If I set error message "Invalid Email Address" by addErrorMessage method, it will again generate the same message against the db_validation.

Body:
$email->addErrorMessage("Please Enter Valid Email Address");

you can use custom validator. create a file Email.php inside folder Validate in your library folder at the root of project

class Validate_Email extends Zend_Validate_Abstract
{

    const INVALID = 'Email is required';
    protected $_messageTemplates = array(
    self::INVALID => "Invalid Email Address",
    self::ALREADYUSED => "Email is already registered"
    );

     public function isValid($value)
     {
          if(preg_match($email_regex, trim($value))){
            $dataModel = new Application_Model_Data(); //check if the email exists
            if(!$dataModel->email_exists($value)){
                return true;
            }
            else{
                $this->_error(self::ALREADYUSED);
                return false;
            }
          }
          else
          {
            $this->_error(self::INVALID);
            return false;
          }
     }
}

and in you  form.php file

    $mailValidator = new Validate_Email();
    $email->addValidator($mailValidator, true);

Don't know if it works or not but for me it worked in case of telephone. Courtesy of  http://softwareobjects.net/technology/other/zend-framework-1-10-7-telephone-validator/


问:
What is a semaphore?
A semaphore is a programming concept that is frequently used to solve multi-threading problems.  My question to the community:

What is a semaphore and how do you use it?

答:
Consider, a taxi that can accommodate a total of 3(rear)+2(front) persons including the driver. So, a semaphore allows only 5 persons inside a car at a time.
And a mutex allows only 1 person on a single seat of the car.

Therefore, Mutex is to allow exclusive access for a resource (like an OS thread) while a Semaphore is to allow access for n number of resources at a time.

OwnerDisplayName: Dalroth

Title: What is a semaphore?

ContentLicense: CC BY-SA 4.0


问:
Javascript Browserify, require function and run it
I have this little browserify problem. I want to require a self made module and run it instantly.

Main File:

```<code>(function() {
    require('./modules/initScrollReveal')();
    require('./modules/initChart')();
    require('./modules/initDatamap')();
  })();
</code>```

Module:

```<code>exports.initChart = function () {
  // do stuff
};
</code>```

now i get an error with the Message
"require(...) is not a function" at require('./modules/initScrollReveal')();

Browserify is running via Watchify with

```<code>watchify public-modules/res/js/main.js -o public/res/js/main.js
</code>```

答:
Try:

(function() {
    require('./modules/initScrollReveal').initScrollReveal();
    require('./modules/initChart').initChart();
    require('./modules/initDatamap').initDatamap();
  })();```
</div>
</div>
</p>

<p>if your modules looks like:</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-js lang-js prettyprint-override"><code>exports.initScrollReveal= function () {
  // do stuff
};

exports.initChart = function () {
  // do stuff
};

exports.initDatamap= function () {
  // do stuff
};</code>```

Body:
I have this little browserify problem. I want to require a self made module and run it instantly.

Main File:

(function() {
    require('./modules/initScrollReveal')();
    require('./modules/initChart')();
    require('./modules/initDatamap')();
  })();

Module:

exports.initChart = function () {
  // do stuff
};

now i get an error with the Message
"require(...) is not a function" at require('./modules/initScrollReveal')();

Browserify is running via Watchify with

watchify public-modules/res/js/main.js -o public/res/js/main.js

Body:
Try:

(function() {
    require('./modules/initScrollReveal').initScrollReveal();
    require('./modules/initChart').initChart();
    require('./modules/initDatamap').initDatamap();
  })();

if your modules looks like:

exports.initScrollReveal= function () {
  // do stuff
};

exports.initChart = function () {
  // do stuff
};

exports.initDatamap= function () {
  // do stuff
};


问:
Allowing users to 'toggle' up_vote and down_vote using thumbs_up gem in Rails
I'm using the thumbs_up gem to allow 'likes' in my app.

The gem includes this code to make sure that one user cannot vote twice -

```<code>Code '1'
# Comment out the line below to allow multiple votes per user.
validates_uniqueness_of :voteable_id, :scope => [:voteable_type, :voter_type, :voter_id]
</code>```

But I want my users to be able to 'up_vote' once, then 'down_vote' if they happen to like by mistake (for user experience's sake). I tried to change the scope to:

```<code>validates_uniqueness_of :voteable_id, :scope => [:voteable_type]
</code>```

But that would allow users to 'up_vote' twice in a row. Users, instead, should only be able to 'down_vote' if the voteable object is already 'up_vote'd, and vice versa.

I can think of doing this by using a conditional in my view, as such:

```<code><% if !current_user.voted_for?(voteable_name) %>
     <%= link_to('Like', vote_up_question_answer_path(voteable_name), :method => :post) %>
<% else %>
     <br>
     <%= link_to('Unlike', vote_down_question_answer_path(voteable_name), :method => :post) %>
<% end %>
</code>```

And commenting out Code '1', but is there a better way to make users permitted to only 'toggle'-ing between the votes through the controller?

Thanks.

答: Should probably implement the flipping in application code instead of changing the existing behavior of the library.</p>

Body:
I'm using the thumbs_up gem to allow 'likes' in my app.

The gem includes this code to make sure that one user cannot vote twice -

Code '1'
# Comment out the line below to allow multiple votes per user.
validates_uniqueness_of :voteable_id, :scope => [:voteable_type, :voter_type, :voter_id]

But I want my users to be able to 'up_vote' once, then 'down_vote' if they happen to like by mistake (for user experience's sake). I tried to change the scope to:

validates_uniqueness_of :voteable_id, :scope => [:voteable_type]

But that would allow users to 'up_vote' twice in a row. Users, instead, should only be able to 'down_vote' if the voteable object is already 'up_vote'd, and vice versa.

I can think of doing this by using a conditional in my view, as such:

<% if !current_user.voted_for?(voteable_name) %>
     <%= link_to('Like', vote_up_question_answer_path(voteable_name), :method => :post) %>
<% else %>

     <%= link_to('Unlike', vote_down_question_answer_path(voteable_name), :method => :post) %>
<% end %>

And commenting out Code '1', but is there a better way to make users permitted to only 'toggle'-ing between the votes through the controller?

Thanks.


问:
Read-Only error: Convert all sheets of an xls workbook into separate CSV files
I have to convert an xls workbook with multiple sheets in it into CSV format.
The programming language I'm using is VBScript, and thus far the code below gives a 'cannot access read-only document' error.</p>

```<code>Dim oExcel
Set oExcel = CreateObject("Excel.Application")
Dim oBook
'xls is the path to the xls file
WScript.Echo xls
Set oBook = oExcel.Workbooks.Open(xls)

Dim Worksheet
For Each Worksheet in oBook.Sheets
    If oExcel.Application.WorksheetFunction.CountA(Worksheet.Cells) <> 0 Then
        Worksheet.SaveAs strPath & "\" & Worksheet.Name & ".csv", 6
    End If
Next

oBook.Close False
oExcel.Quit
WScript.Echo "Done"
</code>```

答:
strPath is never set in your code. Your comment says xls is the path to the workbook. It needs to be the full file specification to open the workbook.

Worksheet is a class in Excel.Application. Use

```<code>Dim oWorksheet
For Each oWorksheet in oBook.Sheets
    If oExcel.Application.WorksheetFunction.CountA(oWorksheet.Cells) <> 0 Then
        oWorksheet.SaveAs oBook.Path & "\" & oWorksheet.Name & ".csv", 6
    End If
Next
</code>```

Body:
I have to convert an xls workbook with multiple sheets in it into CSV format.
The programming language I'm using is VBScript, and thus far the code below gives a 'cannot access read-only document' error.

Dim oExcel
Set oExcel = CreateObject("Excel.Application")
Dim oBook
'xls is the path to the xls file
WScript.Echo xls
Set oBook = oExcel.Workbooks.Open(xls)

Dim Worksheet
For Each Worksheet in oBook.Sheets
    If oExcel.Application.WorksheetFunction.CountA(Worksheet.Cells) <> 0 Then
        Worksheet.SaveAs strPath & "\" & Worksheet.Name & ".csv", 6
    End If
Next

oBook.Close False
oExcel.Quit
WScript.Echo "Done"

Body:
strPath is never set in your code. Your comment says xls is the path to the workbook. It needs to be the full file specification to open the workbook.

Worksheet is a class in Excel.Application. Use

Dim oWorksheet
For Each oWorksheet in oBook.Sheets
    If oExcel.Application.WorksheetFunction.CountA(oWorksheet.Cells) <> 0 Then
        oWorksheet.SaveAs oBook.Path & "\" & oWorksheet.Name & ".csv", 6
    End If
Next