问:
Angularjs Unexpected token JSON
I have a problem with angularjs and JSON.

This is my code.

list_user.jsp (this is the page where I print the table)

```<code><tr ng-repeat="per in persons">
  <td>{{ per.user }}</td>
  <td>{{ per.password }}</td>
  <td>{{ per.profile }}</td>
</tr>
</code>```

controller.js

```<code> $http({
      method : 'POST',
      url : 'views/user/user.json'
    }).success(function(data){
      $scope.persons = data;
    });
</code>```

user.json

```<code> [
        {
            "user": "Quarterback",
            "password": 5,
            "profile": "ppp"
        },
        {
            "user": "Wide Receiver",
            "password": 89,
            "profile": "oooo"
        }
    ]
</code>```

This way the table is generated correctly, but the json is fixed.
Now I'll paste the code with which I want to print the data by taking them from a query

controller.js

```<code> $http({
        method : 'POST',
        url : 'views/user/user.jsp'
    }).success(function(data){

        /*
        var jsonStr="your json string";
        var json=JSON.stringify(data);
        json=JSON.parse(json)
        console.log(json);
        */
        console.log(data);
        $scope.persons = data;
    });
</code>```

The code between / * .. * / left them to show that I also tried that road without success.

user.jsp

```<code>JSONArray jdata = new JSONArray();
UserRest as = new UserRest();
jdata = as.getAll();
logger.info("jdata in user.jsp "+jdata);
</code>```

UserRest.class (just paste the code where I create the JSON)

```<code> while (iter.hasNext()) {
      User ut = (User) iter.next();
      JSONObject jtemp = new JSONObject();
      jtemp.put("user", ut.getUserName());
      jtemp.put("password", ut.getPassword());
      jtemp.put("profilo", ut.getProfilo());
      jarray.put(jtemp);
    }
    return  jarray;
</code>```

the result of logger.info("jdata in user.jsp "+jdata) in user.jsp

```<code>jdata in user.jsp [{"user":"aaaaaaa","password":"1111111","profile":"0"},{"user":"bbbbbbbb","password":"222222222","profile":"1"}]
</code>```

As you can see the json looks the same, but when in the browser I call the list_user.jsp page in the console the value "data" in controller.js returns me

```<code> <? Xml version = "1.0" encoding = "utf-8"?>
</code>```

I also tried with JSON.parse or JSON.stringify but it does not work.
I also added "track by $ index" here:

```<code><tr ng-repeat = "for people track by $ index">
</code>```

in list_user.jsp but it does not work.

Please help me because I do not know how to do it anymore.

答:
I resolve the problem with servlet, but I would like call a REST api.
I prefer don't use the servlet.
I change my code.

controller.js

```<code>angular.module('inspinia')
.controller("DataTable",['$scope','$http',function($scope,$http){
$http({
        method : 'GET',
        url : '/api/utenti'
    }).success(function(data){
        $scope.persons = data;
    });
</code>```

web.xml

```<code><servlet>
      <servlet-name>SpringServlet</servlet-name>
      <servlet-class>com.xxx.yyy.userInterface.servlet.SpringServlet</servlet-class>
      <load-on-startup>3</load-on-startup>
    </servlet>
    <listener>
      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <servlet-mapping>
        <servlet-name>SpringServlet</servlet-name>
        <url-pattern>/api/*</url-pattern>
    </servlet-mapping>
</code>```

UtentiController.class

```<code>@Path("/utenti")
@Component
@Scope("request")
public class UtentiController {

    @GET
    @Produces("application/json")
    public JSONArray getAll() {
       /* call the interface that return a json */

       return jarray;
    }
}
</code>```

the error in the console is:

```<code>HTTP Status [404] – [Not Found]

Type Status Report

Message /api/utenti/

Description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.
</code>```

Thanks for your help

Title: Angularjs Unexpected token JSON

Body:
I have a problem with angularjs and JSON.

This is my code.

list_user.jsp (this is the page where I print the table)

  {{ per.user }}
  {{ per.password }}
  {{ per.profile }}

controller.js

 $http({
      method : 'POST',
      url : 'views/user/user.json'
    }).success(function(data){
      $scope.persons = data;
    });

user.json

 [
        {
            "user": "Quarterback",
            "password": 5,
            "profile": "ppp"
        },
        {
            "user": "Wide Receiver",
            "password": 89,
            "profile": "oooo"
        }
    ]

This way the table is generated correctly, but the json is fixed.
Now I'll paste the code with which I want to print the data by taking them from a query

controller.js

 $http({
        method : 'POST',
        url : 'views/user/user.jsp'
    }).success(function(data){

        /*
        var jsonStr="your json string";
        var json=JSON.stringify(data);
        json=JSON.parse(json)
        console.log(json);
        */
        console.log(data);
        $scope.persons = data;
    });

The code between / * .. * / left them to show that I also tried that road without success.

user.jsp

JSONArray jdata = new JSONArray();
UserRest as = new UserRest();
jdata = as.getAll();
logger.info("jdata in user.jsp "+jdata);

UserRest.class (just paste the code where I create the JSON)

 while (iter.hasNext()) {
      User ut = (User) iter.next();
      JSONObject jtemp = new JSONObject();
      jtemp.put("user", ut.getUserName());
      jtemp.put("password", ut.getPassword());
      jtemp.put("profilo", ut.getProfilo());
      jarray.put(jtemp);
    }
    return  jarray;

the result of logger.info("jdata in user.jsp "+jdata) in user.jsp

jdata in user.jsp [{"user":"aaaaaaa","password":"1111111","profile":"0"},{"user":"bbbbbbbb","password":"222222222","profile":"1"}]

As you can see the json looks the same, but when in the browser I call the list_user.jsp page in the console the value "data" in controller.js returns me

 <? Xml version = "1.0" encoding = "utf-8"?>

I also tried with JSON.parse or JSON.stringify but it does not work.
I also added "track by $ index" here:

in list_user.jsp but it does not work.

Please help me because I do not know how to do it anymore.

Body:
I resolve the problem with servlet, but I would like call a REST api.
I prefer don't use the servlet.
I change my code.

controller.js

angular.module('inspinia')
.controller("DataTable",['$scope','$http',function($scope,$http){
$http({
        method : 'GET',
        url : '/api/utenti'
    }).success(function(data){
        $scope.persons = data;
    });

web.xml

<servlet>
      <servlet-name>SpringServlet</servlet-name>
      <servlet-class>com.xxx.yyy.userInterface.servlet.SpringServlet</servlet-class>
      <load-on-startup>3</load-on-startup>
    </servlet>
    <listener>
      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <servlet-mapping>
        <servlet-name>SpringServlet</servlet-name>
        <url-pattern>/api/*</url-pattern>
    </servlet-mapping>

UtentiController.class

@Path("/utenti")
@Component
@Scope("request")
public class UtentiController {

    @GET
    @Produces("application/json")
    public JSONArray getAll() {
       /* call the interface that return a json */

       return jarray;
    }
}

the error in the console is:

HTTP Status [404] – [Not Found]

Type Status Report

Message /api/utenti/

Description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.

Thanks for your help


来源: stackexchange

问:
Comparing file contents in F#
I wrote a quick and dirty function to compare file contents (BTW, I have already tested that they are of equal size):

```<code>let eqFiles f1 f2 =
  let bytes1 = Seq.ofArray (File.ReadAllBytes f1)
  let bytes2 = Seq.ofArray (File.ReadAllBytes f2)
  let res = Seq.compareWith (fun x y -> (int x) - (int y)) bytes1 bytes2
  res = 0
</code>```

I'm not happy with reading the whole contents into an array. I'd rather have a lazy sequence of bytes, but I can't find the right API in F#.

答: You don't need anything new in F# for this - I would just define a sequence that yields bytes using a FileStream underneath instead of using File.ReadAllBytes. Then you can compare two such sequences the "F# way".

ContentLicense: CC BY-SA 2.5

Title: Comparing file contents in F#

Body:
I wrote a quick and dirty function to compare file contents (BTW, I have already tested that they are of equal size):

let eqFiles f1 f2 =
  let bytes1 = Seq.ofArray (File.ReadAllBytes f1)
  let bytes2 = Seq.ofArray (File.ReadAllBytes f2)
  let res = Seq.compareWith (fun x y -> (int x) - (int y)) bytes1 bytes2
  res = 0

I'm not happy with reading the whole contents into an array. I'd rather have a lazy sequence of bytes, but I can't find the right API in F#.


问:
Is there a shorter way to do exactly this?
I'm trying to find away to do this in a shorter way I don't like not using else in the end because it looks weird without it. This works for me for some reason. If I add the, " else: return True" it will only look at the first true from the list and then return True but won't check the rest... and will end the function</p>

```<code>b = [[True, True, True], [True, True, True], [True, True, False]]

for i in range(3):
    for j in range(3):
        if b[i][j] == False:
             return False
return True
</code>```

答:
You can use either all or any to do this:

```<code>all(all(x) for x in b)
</code>```

OR

```<code>not any(not y for x in b for y in x)
</code>```

In either case, the value of the expression will be the same as the return value of your original function. Like your original loop, both of these expressions are short-circuiting: they will stop as soon as a False element in encountered in the nested lists.

In your original code, returning True on the first element naturally ends the function. That's just how return works. If you absolutely must have an else clause to please your inner aesthete (I would recommend against it), use else: continue instead. This is totally superfluous (and therefore generally undesirable), but it will instruct the loop to continue until a False is found instead of returning from the function immediately.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to find away to do this in a shorter way I don't like not using else in the end because it looks weird without it. This works for me for some reason. If I add the, " else: return True" it will only look at the first true from the list and then return True but won't check the rest... and will end the function

b = [[True, True, True], [True, True, True], [True, True, False]]

for i in range(3):
    for j in range(3):
        if b[i][j] == False:
             return False
return True

Body:
You can use either all or any to do this:

all(all(x) for x in b)

OR

not any(not y for x in b for y in x)

In either case, the value of the expression will be the same as the return value of your original function. Like your original loop, both of these expressions are short-circuiting: they will stop as soon as a False element in encountered in the nested lists.

In your original code, returning True on the first element naturally ends the function. That's just how return works. If you absolutely must have an else clause to please your inner aesthete (I would recommend against it), use else: continue instead. This is totally superfluous (and therefore generally undesirable), but it will instruct the loop to continue until a False is found instead of returning from the function immediately.


问:
Curl download to HDFS
I had this code:

```<code>curl -o fileName.csv url | xargs hdfs dfs -moveFromLocal $1 /somePath/
</code>```

When i execute this code, curl put the values from request inside fileName.csv, the file are moved to HDFS. I wanna know if i can, mantain the curl output in memory, send to pipe and just write the values inside HDFS?

Something like this(that works):

```<code>curl url | xargs hdfs dfs -put $1 /somePath
</code>```

答:
The hdfs dfs -put command can accept file input from stdin, using the familiar idiom of specifying - to mean stdin:

```<code>> curl -sS https://www.google.com/robots.txt | hdfs dfs -put - /robots.txt
> hdfs dfs -ls /robots.txt
-rw-r--r--   3 cnauroth supergroup       6880 2017-07-06 09:07 /robots.txt
</code>```

Another option is to use shell process substitution to allow treating the stdout of curl (or really any command you choose) as if it were a file input to another command:

```<code>> hdfs dfs -put <(curl -sS https://www.google.com/robots.txt) /robots.txt
> hdfs dfs -ls /robots.txt
-rw-r--r--   3 cnauroth supergroup       6880 2017-07-05 15:07 /robots.txt
</code>```

Title: Curl download to HDFS

Body:
I had this code:

curl -o fileName.csv url | xargs hdfs dfs -moveFromLocal $1 /somePath/

When i execute this code, curl put the values from request inside fileName.csv, the file are moved to HDFS. I wanna know if i can, mantain the curl output in memory, send to pipe and just write the values inside HDFS?

Something like this(that works):

curl url | xargs hdfs dfs -put $1 /somePath

Body:
The hdfs dfs -put command can accept file input from stdin, using the familiar idiom of specifying - to mean stdin:

> curl -sS https://www.google.com/robots.txt | hdfs dfs -put - /robots.txt
> hdfs dfs -ls /robots.txt
-rw-r--r--   3 cnauroth supergroup       6880 2017-07-06 09:07 /robots.txt

Another option is to use shell process substitution to allow treating the stdout of curl (or really any command you choose) as if it were a file input to another command:

> hdfs dfs -put <(curl -sS https://www.google.com/robots.txt) /robots.txt
> hdfs dfs -ls /robots.txt
-rw-r--r--   3 cnauroth supergroup       6880 2017-07-05 15:07 /robots.txt


问:
How to do selection in PostgreSQL with join when more than one row satisfies requirements?
How to do selection to get JSON array in one cell when doing INNER JOIN when there are more than 1 values to join?

ex Tables:

T1:

```<code>id | name
1    Tom
2    Dom
</code>```

T2:

```<code>user_id | product
1         Milk
2         Cookies
2         Banana
</code>```

Naturally I do SELECT * FROM T1 INNER JOIN T2 ON T1.id = T2.user_id.
But then I get:

```<code>id | Name | product
1   Tom     Milk
2   Dom     Cookies
2   Dom     Banana
</code>```

But I want to get:

```<code>id | Name | product
1   Tom     [{"product":"Milk}]
2   Dom     [{"product":"Cookies"}, {"product":"Banana"}]
</code>```

If I do something with agg functions, then I need to put everything else in GROUP BY, where I have at least 10 arguments. And whole query takes more than 5 minutes.

My T1 is around 4000 rows and T2 around 300 000 rows, each associated with some row in T1.

Is there a better way?

答:
Using LATERAL you can solve it as given example below:</p>

```<code>-- The query
SELECT  *
FROM    table1 t1,
LATERAL (   SELECT  jsonb_agg(
                        jsonb_build_object( 'product', product )
                    )
            FROM    table2
            WHERE   user_id = t1.id
        ) t2( product );

-- Result
 id | name |                     product
----+------+-------------------------------------------------
  1 | Tom  | [{"product": "Milk"}]
  2 | Dom  | [{"product": "Cookies"}, {"product": "Banana"}]
(2 rows)

-- Test data
CREATE TABLE IF NOT EXISTS table1 (
    id      int,
    "name"  text
);

INSERT INTO table1
VALUES  ( 1, 'Tom' ),
        ( 2, 'Dom' );

CREATE TABLE IF NOT EXISTS table2 (
    user_id     int,
    product     text
);

INSERT INTO table2
VALUES  ( 1, 'Milk' ),
        ( 2, 'Cookies' ),
        ( 2, 'Banana' );
</code>```

Body:
How to do selection to get JSON array in one cell when doing INNER JOIN when there are more than 1 values to join?

ex Tables:

T1:

id | name
1    Tom
2    Dom

T2:

user_id | product
1         Milk
2         Cookies
2         Banana

Naturally I do SELECT * FROM T1 INNER JOIN T2 ON T1.id = T2.user_id.
But then I get:

id | Name | product
1   Tom     Milk
2   Dom     Cookies
2   Dom     Banana

But I want to get:

id | Name | product
1   Tom     [{"product":"Milk}]
2   Dom     [{"product":"Cookies"}, {"product":"Banana"}]

If I do something with agg functions, then I need to put everything else in GROUP BY, where I have at least 10 arguments. And whole query takes more than 5 minutes.

My T1 is around 4000 rows and T2 around 300 000 rows, each associated with some row in T1.

Is there a better way?

Body:
Using LATERAL you can solve it as given example below:

-- The query
SELECT  *
FROM    table1 t1,
LATERAL (   SELECT  jsonb_agg(
                        jsonb_build_object( 'product', product )
                    )
            FROM    table2
            WHERE   user_id = t1.id
        ) t2( product );

-- Result
 id | name |                     product
----+------+-------------------------------------------------
  1 | Tom  | [{"product": "Milk"}]
  2 | Dom  | [{"product": "Cookies"}, {"product": "Banana"}]
(2 rows)

-- Test data
CREATE TABLE IF NOT EXISTS table1 (
    id      int,
    "name"  text
);

INSERT INTO table1
VALUES  ( 1, 'Tom' ),
        ( 2, 'Dom' );

CREATE TABLE IF NOT EXISTS table2 (
    user_id     int,
    product     text
);

INSERT INTO table2
VALUES  ( 1, 'Milk' ),
        ( 2, 'Cookies' ),
        ( 2, 'Banana' );


问:
How do I get the old value of a changed cell in Excel VBA?
I'm detecting changes in the values of certain cells in an Excel spreadsheet like this...

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
Dim cell As Range
Dim old_value As String
Dim new_value As String

For Each cell In Target

    If Not (Intersect(cell, Range("cell_of_interest")) Is Nothing) Then
        new_value = cell.Value
        old_value = ' what here?
        Call DoFoo (old_value, new_value)
    End If

Next cell

End Sub
</code>```

Assuming this isn't too bad a way of coding this, how do I get the value of the cell before the change?

答:
Just a thought, but Have you tried using application.undo

This will set the values back again. You can then simply read the original value.  It should not be too difficult to store the new values first, so you change them back again if you like.

Body:
I'm detecting changes in the values of certain cells in an Excel spreadsheet like this...

Private Sub Worksheet_Change(ByVal Target As Range)
Dim cell As Range
Dim old_value As String
Dim new_value As String

For Each cell In Target

    If Not (Intersect(cell, Range("cell_of_interest")) Is Nothing) Then
        new_value = cell.Value
        old_value = ' what here?
        Call DoFoo (old_value, new_value)
    End If

Next cell

End Sub

Assuming this isn't too bad a way of coding this, how do I get the value of the cell before the change?


问:
Extremely strange behavior in Internet Explorer with large GWT app
I have a loader on my page which is removed once I receive a successful response to my RPC.  If the RPC call fails, the page is instantly refreshed.

Anytime I load my page for the first time in IE 7 or 8, it will never load AND never reach the rpc call has failed method.  Every time I manually refresh that failed load, it works.  I've been able to reproduce this about 30 times.  This is a problem because the page just sits there with a loader on the screen.

I have no idea what could be happening.  Try it out for yourself:

1) Open up IE7 or IE8.
2) Go to http://www.foodtrucksmap.com/
3) The page will say done and sit there with a loader on the screen forever.
4) Refresh the page and it should work.

I've only been able to come up with one bad solution... create a timer for 30 seconds and if the loader is still on the screen, refresh the page.  I'd rather discover whats happening though.

UPDATE

As a second temporary solution, I'm going to add a cookie that expires immediately and reload if its ie accessing for the first time in the session.

答:
Based on what limited information you have posted and what I was able to pull out of your site I am wondering if you are hitting a request timout or other server related issue. For instance you have 36 un-compressed javascript files loading (35 of which completing) and a whole host of 407 proxy errors.

You have to be amazingly careful with your load order of js files and where you place your script tags. IE is especially sensitive about this.

You have two options:

Try adding defer to your script tags; this should force it to load the js after the content is loaded.

As yahoo suggests move the script tags to just above your closing body tag () and then try it to see if it makes a difference.  I bet that it is waiting to load the content based on the javascript files have not finished loading and the whole thing times out.


问:
Conversion of scientific notation into real in systemverilog
I have a string which has the following form

str = "1e-06"
```

<p>The content of the string is a number which is expressed in scientific notation. I would like obtain the content of the string in real format to use in next blocks of my systemverilog code. Can anybody help me to find the solution?</p>

<p>Example:</p>

<pre class="lang-vhdl prettyprint-override"><code>string str = "1e-06";
real number;
number = str.atoreal();
$display("%f", number);
</code>```

At the output of this snippet, I was expecting 1e-06 but I am obtaining 1

答:
Use %e instead of %f. This is why it's very important to show a complete example.

Here's an example of a complete example

module top;
string str = "1e-06";
real number;
initial begin
  number = str.atoreal();
  $display("%e", number); // %f displays a fixed point number, you want %e or %g
  end
endmodule
```

Body:
I have a string which has the following form

str = "1e-06"

The content of the string is a number which is expressed in scientific notation. I would like obtain the content of the string in real format to use in next blocks of my systemverilog code. Can anybody help me to find the solution?

Example:

string str = "1e-06";
real number;
number = str.atoreal();
$display("%f", number);

At the output of this snippet, I was expecting 1e-06 but I am obtaining 1


问:
Why aren't my Space Invaders moving?
I am making a Space Invaders clone and I am almost done, but I am having issues with my Space Invaders moving. I have tried using += to move the Space Invaders but this still isn't working. Here is my code so far for the enemies:

```<code>//pushes enemy values into the array
for (var i = 0; i < cols; i++) {
  enemies[i] = [];

  for (var j = 0; j < rows; j++) {
    enemies[i][j] = {
      x: 0,
      y: 0,
      alive: true,
    };
  }
}

for (var i = cols - 1; i >= 0; i--) {
  for (var j = rows - 1; j >= 0; j--) {
    var b = enemies[i][j];

    if (b.alive === true) {
      var enemyX = (j * 40) + enemyPadding / 2;
      var enemyY = (i * 40) + enemyPadding / 1.5;
      b.x = enemyX;
      b.y = enemyY;
      ctx.beginPath();
      ctx.fillStyle = "rgb(0, 0, 255)";
      ctx.strokeStyle = "rgb(0, 0, 0)";
      ctx.rect(enemyX += 1, enemyY, enemyWidth, enemyHeight);
      ctx.stroke();
      ctx.fill();
      ctx.closePath();

      if (b.y + enemyHeight >= canvas.height) {
        b.x = (j * 40) + enemyPadding / 2;
        b.y = (i * 40) + enemyPadding / 1.5;
        lives--;
      }

      for (var a = 0; a < bullets.length; a++) {
        var w = bullets[a];

        if (w.x + w.w >= b.x && w.x <= b.x + enemyWidth && w.y + w.h > b.y && w.y < b.y + enemyHeight) {
          bullets.splice(a, 1);
          b.alive = false;
          score += 20;
        }
      }
    }
  }
}
</code>```

Here is a snippet:

//defines variables for drawing
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var width = canvas.width;
var height = canvas.height;

//bullet variables
var bullets = [];
var bulletWidth = 7;
var bulletHeight = 15;
var bulletSpeed = 5;
var cols = 5;
var rows = 12;

//enemy variables
var enemies = [];
var enemyWidth = 20;
var enemyHeight = 20;
var enemySpeed = 3;
var enemyPadding = 40;

//other important variables
var leftPressed = false;
var rightPressed = false;
var upPressed = false;
var wait = 0;
var score = 0;
var lives = 3;
var time = 0;

//movement
document.addEventListener("keydown", d);
document.addEventListener("keyup", u);

function d(e) {
  if (e.keyCode === 37) {
    leftPressed = true;
  } else if (e.keyCode === 39) {
    rightPressed = true;
  }

  if (e.keyCode === 38) {
    upPressed = true;
  }
}

function u(e) {
  if (e.keyCode === 37) {
    leftPressed = false;
  } else if (e.keyCode === 39) {
    rightPressed = false;
  }

  if (e.keyCode === 38) {
    upPressed = false;
  }
}

//pushes enemy values into the array
for (var i = 0; i < cols; i++) {
  enemies[i] = [];
  for (var j = 0; j < rows; j++) {
    enemies[i][j] = {
      x: 0,
      y: 0,
      alive: true,
    };
  }
}

function drawText() {
  ctx.font = "20px Arial";
  ctx.fillStyle = "rgb(255, 255, 255)";
  ctx.fillText("Score: " + score, 10, 20);
  ctx.fillText("Lives: " + lives, width - 75, 20);
}

function drawEnemy() {
  for (var i = cols - 1; i >= 0; i--) {
    for (var j = rows - 1; j >= 0; j--) {
      var b = enemies[i][j];
      if (b.alive === true) {
        var enemyX = (j * 40) + enemyPadding / 2;
        var enemyY = (i * 40) + enemyPadding / 1.5;
        b.x = enemyX;
        b.y = enemyY;
        ctx.beginPath();
        ctx.fillStyle = "rgb(0, 0, 255)";
        ctx.strokeStyle = "rgb(0, 0, 0)";
        ctx.rect(enemyX += 1, enemyY, enemyWidth, enemyHeight);
        ctx.stroke();
        ctx.fill();
        ctx.closePath();

        if (b.y + enemyHeight >= canvas.height) {
          b.x = (j * 40) + enemyPadding / 2;
          b.y = (i * 40) + enemyPadding / 1.5;
          lives--;
        }

        for (var a = 0; a < bullets.length; a++) {
          var w = bullets[a];
          if (w.x + w.w >= b.x && w.x <= b.x + enemyWidth && w.y + w.h > b.y && w.y < b.y + enemyHeight) {
            bullets.splice(a, 1);
            b.alive = false;
            score += 20;
          }
        }
      }
    }
  }
}

function drawBullet() {
  for (var i = 0; i < bullets.length; i++) {
    var b = bullets[i];

    ctx.fillStyle = "rgb(255, 0, 0)";
    ctx.fillRect(b.x, b.y -= b.s, b.w, b.h);

    if (b.y < -b.h) {
      bullets.splice(i, 1);
    }
  }
}

function Player() {
  this.x = width / 2;
  this.h = 20;
  this.y = height - this.h;
  this.w = 15;
  this.fill = "rgb(255, 255, 255)";
  this.speed = 4;

  this.render = function(ctx, rx, ry, rw, rh, col, rspeed) {
    ctx.fillStyle = col;
    ctx.fillRect(rx, ry, rw, rh);
  }
}

var player = new Player();

function draw() {
  ctx.fillStyle = "black";
  ctx.fillRect(0, 0, width, height);

  drawText();
  drawEnemy();
  drawBullet();

  player.render(ctx, player.x, player.y, player.w, player.h, player.fill, player.speed);

  if (leftPressed && player.x >= 0) {
    player.x -= player.speed;
  } else if (rightPressed && player.x < width - player.w) {
    player.x += player.speed;
  }

  if (upPressed && wait <= 0) {
    bullets.push({
      "x": player.x + player.w / 4,
      "y": player.y,
      "w": bulletWidth,
      "h": bulletHeight,
      "s": bulletSpeed
    });
    //wait = 25;
  }
}

function update() {
  if (wait > 0) {
    wait--;
  }
  time++;
  draw();
  requestAnimationFrame(update);
}
update();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
  <title> Space Invaders </title>
  <style>
    body {
      margin: 10px 0px 0px 10px;
      font-family: Helvetica;
    }
  </style>
</head>

<body>
  <canvas width="500" height="500" id="canvas"></canvas> <br> <br>
  <script src="space_invaders.js"></script>
</body>

</html></code>```

答:
Every time you get an initial position of the invaders. You don't save it in array. check out the solution jsfiddle</p>

```<code>var enemyX = b.x || (j*40)+enemyPadding/2;
var enemyY = b.y || (i*40)+enemyPadding/1.5;
b.x = enemyX;
b.y = enemyY+1;
ctx.beginPath();
ctx.fillStyle = "rgb(0, 0, 255)";
ctx.strokeStyle = "rgb(0, 0, 0)";
ctx.rect(b.x, b.y, enemyWidth, enemyHeight);
ctx.stroke();
ctx.fill();
ctx.closePath();
</code>```

Title: Why aren't my Space Invaders moving?

Body:
I am making a Space Invaders clone and I am almost done, but I am having issues with my Space Invaders moving. I have tried using += to move the Space Invaders but this still isn't working. Here is my code so far for the enemies:

//pushes enemy values into the array
for (var i = 0; i < cols; i++) {
  enemies[i] = [];

  for (var j = 0; j < rows; j++) {
    enemies[i][j] = {
      x: 0,
      y: 0,
      alive: true,
    };
  }
}

for (var i = cols - 1; i >= 0; i--) {
  for (var j = rows - 1; j >= 0; j--) {
    var b = enemies[i][j];

    if (b.alive === true) {
      var enemyX = (j * 40) + enemyPadding / 2;
      var enemyY = (i * 40) + enemyPadding / 1.5;
      b.x = enemyX;
      b.y = enemyY;
      ctx.beginPath();
      ctx.fillStyle = "rgb(0, 0, 255)";
      ctx.strokeStyle = "rgb(0, 0, 0)";
      ctx.rect(enemyX += 1, enemyY, enemyWidth, enemyHeight);
      ctx.stroke();
      ctx.fill();
      ctx.closePath();

      if (b.y + enemyHeight >= canvas.height) {
        b.x = (j * 40) + enemyPadding / 2;
        b.y = (i * 40) + enemyPadding / 1.5;
        lives--;
      }

      for (var a = 0; a < bullets.length; a++) {
        var w = bullets[a];

        if (w.x + w.w >= b.x && w.x <= b.x + enemyWidth && w.y + w.h > b.y && w.y < b.y + enemyHeight) {
          bullets.splice(a, 1);
          b.alive = false;
          score += 20;
        }
      }
    }
  }
}

Here is a snippet:

//defines variables for drawing
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var width = canvas.width;
var height = canvas.height;

//bullet variables
var bullets = [];
var bulletWidth = 7;
var bulletHeight = 15;
var bulletSpeed = 5;
var cols = 5;
var rows = 12;

//enemy variables
var enemies = [];
var enemyWidth = 20;
var enemyHeight = 20;
var enemySpeed = 3;
var enemyPadding = 40;

//other important variables
var leftPressed = false;
var rightPressed = false;
var upPressed = false;
var wait = 0;
var score = 0;
var lives = 3;
var time = 0;

//movement
document.addEventListener("keydown", d);
document.addEventListener("keyup", u);

function d(e) {
  if (e.keyCode === 37) {
    leftPressed = true;
  } else if (e.keyCode === 39) {
    rightPressed = true;
  }

  if (e.keyCode === 38) {
    upPressed = true;
  }
}

function u(e) {
  if (e.keyCode === 37) {
    leftPressed = false;
  } else if (e.keyCode === 39) {
    rightPressed = false;
  }

  if (e.keyCode === 38) {
    upPressed = false;
  }
}

//pushes enemy values into the array
for (var i = 0; i < cols; i++) {
  enemies[i] = [];
  for (var j = 0; j < rows; j++) {
    enemies[i][j] = {
      x: 0,
      y: 0,
      alive: true,
    };
  }
}

function drawText() {
  ctx.font = "20px Arial";
  ctx.fillStyle = "rgb(255, 255, 255)";
  ctx.fillText("Score: " + score, 10, 20);
  ctx.fillText("Lives: " + lives, width - 75, 20);
}

function drawEnemy() {
  for (var i = cols - 1; i >= 0; i--) {
    for (var j = rows - 1; j >= 0; j--) {
      var b = enemies[i][j];
      if (b.alive === true) {
        var enemyX = (j * 40) + enemyPadding / 2;
        var enemyY = (i * 40) + enemyPadding / 1.5;
        b.x = enemyX;
        b.y = enemyY;
        ctx.beginPath();
        ctx.fillStyle = "rgb(0, 0, 255)";
        ctx.strokeStyle = "rgb(0, 0, 0)";
        ctx.rect(enemyX += 1, enemyY, enemyWidth, enemyHeight);
        ctx.stroke();
        ctx.fill();
        ctx.closePath();

        if (b.y + enemyHeight >= canvas.height) {
          b.x = (j * 40) + enemyPadding / 2;
          b.y = (i * 40) + enemyPadding / 1.5;
          lives--;
        }

        for (var a = 0; a < bullets.length; a++) {
          var w = bullets[a];
          if (w.x + w.w >= b.x && w.x <= b.x + enemyWidth && w.y + w.h > b.y && w.y < b.y + enemyHeight) {
            bullets.splice(a, 1);
            b.alive = false;
            score += 20;
          }
        }
      }
    }
  }
}

function drawBullet() {
  for (var i = 0; i < bullets.length; i++) {
    var b = bullets[i];

    ctx.fillStyle = "rgb(255, 0, 0)";
    ctx.fillRect(b.x, b.y -= b.s, b.w, b.h);

    if (b.y < -b.h) {
      bullets.splice(i, 1);
    }
  }
}

function Player() {
  this.x = width / 2;
  this.h = 20;
  this.y = height - this.h;
  this.w = 15;
  this.fill = "rgb(255, 255, 255)";
  this.speed = 4;

  this.render = function(ctx, rx, ry, rw, rh, col, rspeed) {
    ctx.fillStyle = col;
    ctx.fillRect(rx, ry, rw, rh);
  }
}

var player = new Player();

function draw() {
  ctx.fillStyle = "black";
  ctx.fillRect(0, 0, width, height);

  drawText();
  drawEnemy();
  drawBullet();

  player.render(ctx, player.x, player.y, player.w, player.h, player.fill, player.speed);

  if (leftPressed && player.x >= 0) {
    player.x -= player.speed;
  } else if (rightPressed && player.x < width - player.w) {
    player.x += player.speed;
  }

  if (upPressed && wait <= 0) {
    bullets.push({
      "x": player.x + player.w / 4,
      "y": player.y,
      "w": bulletWidth,
      "h": bulletHeight,
      "s": bulletSpeed
    });
    //wait = 25;
  }
}

function update() {
  if (wait > 0) {
    wait--;
  }
  time++;
  draw();
  requestAnimationFrame(update);
}
update();

<!DOCTYPE html>

  <title> Space Invaders </title>

  <canvas width="500" height="500" id="canvas"></canvas>

Body:
Every time you get an initial position of the invaders. You don't save it in array. check out the solution jsfiddle

var enemyX = b.x || (j*40)+enemyPadding/2;
var enemyY = b.y || (i*40)+enemyPadding/1.5;
b.x = enemyX;
b.y = enemyY+1;
ctx.beginPath();
ctx.fillStyle = "rgb(0, 0, 255)";
ctx.strokeStyle = "rgb(0, 0, 0)";
ctx.rect(b.x, b.y, enemyWidth, enemyHeight);
ctx.stroke();
ctx.fill();
ctx.closePath();


问:
How do I define an optional parameter in my Laravel routes?
I would like to define {id} an optional parameter in the following route:

```<code>Route::get('profile/edit/{id}', array('uses' => 'BusinessController@editProfile', 'as' => 'profile.edit'));
</code>```

How can I do this and also define a default parameter if one isn't provided?

答:
Just like the other answers, but as for the default part: I asked almost the same question a few days ago and the answer is:

```<code>Route::get('profile/edit/{id?}', array('uses' => 'BusinessController@editProfile', 'as' => 'profile.edit'))
    ->defaults('id', 'defaultValue');
</code>```

The important things are

The questionmark

The defaults function

Body:
I would like to define {id} an optional parameter in the following route:

Route::get('profile/edit/{id}', array('uses' => 'BusinessController@editProfile', 'as' => 'profile.edit'));

How can I do this and also define a default parameter if one isn't provided?

Body:
Just like the other answers, but as for the default part: I asked almost the same question a few days ago and the answer is:

Route::get('profile/edit/{id?}', array('uses' => 'BusinessController@editProfile', 'as' => 'profile.edit'))
    ->defaults('id', 'defaultValue');

The important things are

The questionmark

The defaults function


问:
Why isn't it printing (file handling)?
I am not very sure where I have gone wrong.

I am trying to print the contents from the page in files.

Here is the code

```<code>File>>> If you fell down yesterday, stand up today
</code>```

```<code>text_file = open("files.txt", "r")
print(text_file)
</code>```

答:
Take a look at the file objects documentation. An example of iterating over the file includes:

```<code>for line in text_file:
    print(line)
</code>```

Or use text_file.readlines() to receive a list of lines:

```<code>['If you fell down yesterday, stand up today']
</code>```

Title: Why isn't it printing (file handling)?

Body:
I am not very sure where I have gone wrong.

I am trying to print the contents from the page in files.

Here is the code

File>>> If you fell down yesterday, stand up today

text_file = open("files.txt", "r")
print(text_file)

Body:
Take a look at the file objects documentation. An example of iterating over the file includes:

for line in text_file:
    print(line)

Or use text_file.readlines() to receive a list of lines:

['If you fell down yesterday, stand up today']


问:
Running Jupyter program using shell script
I am trying to run my Jupyter program using shell script. However I am unsure of how to do so. I want to run my program on Jenkins, which is a platform that will require my code to be run in shell script in order to test it.</p>

答:
This appears to be covered in the docs.  Example:</p>

```<code>jupyter nbconvert --to notebook --execute mynotebook.ipynb
</code>```

Body:
This appears to be covered in the docs.  Example:

jupyter nbconvert --to notebook --execute mynotebook.ipynb


问:
Android Populate Spinner Content From Another Spinner
I am trying to populate cities by selecting a country from spinner. It should populate second spinner's content based on the first spinner's choice. My strings.xml and MainActivity.java file is like this:

strings.xml

```<code> <!-- Countries -->
<string-array name="country_names">
    <item>Turkey</item>
    <item>Spain</item>
</string-array>

<!-- Cities -->
<string-array name="Turkey">
    <item>Istanbul</item>
    <item>Adana</item>
</string-array>

<string-array name="Spain">
    <item>Madrid</item>
    <item>Barcelona</item>
</string-array>
</code>```

MainActivity.java

```<code>    citySpinner = (Spinner) findViewById(R.id.input_city);
    countrySpinner = (Spinner) findViewById(R.id.input_country);

    countryAdapter = ArrayAdapter.createFromResource(this,R.array.country_names,android.R.layout.simple_spinner_item);
    countryAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    final String[] country = new String[1];
    countrySpinner.setAdapter(countryAdapter);
    countrySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l)
        {
            country[0] = adapterView.getItemAtPosition(i).toString();
            Toast.makeText(mContext, adapterView.getItemAtPosition(i) + " selected", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView)
        {

        }
    });

    cityAdapter = ArrayAdapter.createFromResource(this,R.array.Turkey,android.R.layout.simple_spinner_item);
    cityAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    citySpinner.setAdapter(cityAdapter);
</code>```

I need to give a variable inside the cityAdapter = ArrayAdapter.createFromResource(...) line instead of writing Turkey or any country name.

I couldn't come up anything useful in the web, this is my last hope :)

答:
try this :</p>

```<code>countrySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                country[0] = adapterView.getItemAtPosition(i).toString();
                Toast.makeText(mContext, adapterView.getItemAtPosition(i) + " selected", Toast.LENGTH_SHORT).show();
                switch (i) {
                    case 0:
                        cityAdapter = ArrayAdapter.createFromResource(this, R.array.Turkey, android.R.layout.simple_spinner_item);
                        break;
                    case 1:
                        cityAdapter = ArrayAdapter.createFromResource(this, R.array.Madrid, android.R.layout.simple_spinner_item);
                        break;
                }
                cityAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                citySpinner.setAdapter(cityAdapter);
            }

        @Override
        public void onNothingSelected (AdapterView < ? > adapterView)
        {

        }
    });
</code>```

Body:
I am trying to populate cities by selecting a country from spinner. It should populate second spinner's content based on the first spinner's choice. My strings.xml and MainActivity.java file is like this:

strings.xml

<string-array name="country_names">
    <item>Turkey</item>
    <item>Spain</item>
</string-array>

<string-array name="Turkey">
    <item>Istanbul</item>
    <item>Adana</item>
</string-array>

<string-array name="Spain">
    <item>Madrid</item>
    <item>Barcelona</item>
</string-array>

MainActivity.java

    citySpinner = (Spinner) findViewById(R.id.input_city);
    countrySpinner = (Spinner) findViewById(R.id.input_country);

    countryAdapter = ArrayAdapter.createFromResource(this,R.array.country_names,android.R.layout.simple_spinner_item);
    countryAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    final String[] country = new String[1];
    countrySpinner.setAdapter(countryAdapter);
    countrySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l)
        {
            country[0] = adapterView.getItemAtPosition(i).toString();
            Toast.makeText(mContext, adapterView.getItemAtPosition(i) + " selected", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView)
        {

        }
    });

    cityAdapter = ArrayAdapter.createFromResource(this,R.array.Turkey,android.R.layout.simple_spinner_item);
    cityAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    citySpinner.setAdapter(cityAdapter);

I need to give a variable inside the cityAdapter = ArrayAdapter.createFromResource(...) line instead of writing Turkey or any country name.

I couldn't come up anything useful in the web, this is my last hope :)

Body:
try this :

countrySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                country[0] = adapterView.getItemAtPosition(i).toString();
                Toast.makeText(mContext, adapterView.getItemAtPosition(i) + " selected", Toast.LENGTH_SHORT).show();
                switch (i) {
                    case 0:
                        cityAdapter = ArrayAdapter.createFromResource(this, R.array.Turkey, android.R.layout.simple_spinner_item);
                        break;
                    case 1:
                        cityAdapter = ArrayAdapter.createFromResource(this, R.array.Madrid, android.R.layout.simple_spinner_item);
                        break;
                }
                cityAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                citySpinner.setAdapter(cityAdapter);
            }

        @Override
        public void onNothingSelected (AdapterView < ? > adapterView)
        {

        }
    });


问:
Google GeoCharts Data not loading
So here is the problem in attached code. I have a GeoCharts div with a form div next to it, in the background there are multiple CSV documents that are managing the data. The goal is to load the data by the current selection of filters in the form div when the #showButton is pressed.

So when the page is loaded the 'general' CSV document is loaded to represent the data and when the user wants to see data by the current filters selection the other CSV document is loaded when the user presses #showButton. But the thing is that that happens only when the #showButton is pressed twice with nothing changing in the filters the second times.

Everything else like the displayMode (markers) variable that is passed to the function and the colorForSex variable gets loaded and applied to the GeoCharts div but the CSV file and all the data gets loaded only the second time that the button is pressed (again - without changing the filters the second time it is pressed).

```<code>/*

Coded by : Roland Stojkoski;

Contact : roland.roland.roli@gmail.com

*/

/* CSV handling - START */

var processedData = [];

var newData = [];

var region = $('select[name="region"] option:selected').val();
var sex = $('select[name="sex"] option:selected').val();
var age = $('select[name="age"] option:selected').val();
var permOrNot = $('select[name="permOrNot"] option:selected').val();
var permSelect = $('select[name="permSelect"] option:selected').val();

getFile('csv/Residence_All.csv');

/* CSV handling - END */

var chart;
var data;

$(document).ready(function(){

    /* Google Charts */

    google.charts.load('current', {
        'packages':['geochart'],
        'mapsApiKey': 'AIzaSyBHggo3wq70fGWUJwvCCHNnQm0E4R2G_l8 ',
        'callback': drawRegionsMap
    });
    google.charts.setOnLoadCallback(drawRegionsMap);

    function drawRegionsMap() {
        region = $('select[name="region"] option:selected').val();
        data = google.visualization.arrayToDataTable(processedData);

        var options = {
            region: region,
            backgroundColor: 'none',
            chartArea: { width: '100%', height: '100%' },
            colorAxis: {colors: ['#ddd','#ff1a1a']},
            datalessRegionColor: 'white',
            displayMode: 'markers',
            legend: {
                numberFormat: '.##',
                textStyle: {
                    fontName: 'Nunito Sans',
                    color: '#ff1a1a',
                    fontSize: 14,
                }
            }
        };

        chart = new google.visualization.GeoChart(document.getElementById('chart_div'));

        chart.draw(data, options);
    }

    $('#showButton').click(function(){
        if($('select[name="region"] option:selected').val() === 'world' && $('select[name="sex"] option:selected').val() === 'all' && $('select[name="age"] option:selected').val() === 'all' ){
            loadData('csv/Origin_All.csv', '#a80000', 'regions');
        }else if ($('select[name="region"] option:selected').val() === 'world' && $('select[name="sex"] option:selected').val() === 'female'){
            loadData('csv/Origin_Sex_Female.csv', '#ff9933', 'regions');
        }else if ($('select[name="region"] option:selected').val() === 'CH'){
            loadData('csv/Residence_All.csv', '#a80000', 'text');
        }
    });

    $('select').change(function(){
        if($('select[name="region"] option:selected').val() === 'world'){
            $('select[name="age"]').fadeIn();
            $('select[name="permOrNot"]').fadeOut();
            if($('select[name="sex"] option:selected').val() != 'all'){
                $('select[name="age"]').fadeOut();
            }else{
                $('select[name="age"]').fadeIn();
            }
            if($('select[name="age"] option:selected').val() != 'all'){
                $('select[name="sex"]').fadeOut();
            }else{
                $('select[name="sex"]').fadeIn();
            }
        }else if($('select[name="region"] option:selected').val() === 'CH'){
            $('select[name="age"]').fadeOut();
            $('select[name="permOrNot"]').fadeIn();
            if($('select[name="permOrNot"] option:selected').val() === 'perm'){
                $('select[name="permSelect"]').fadeIn();
            }else{
                $('select[name="permSelect"]').fadeOut();
            }
        }
    });

    $(document).scrollTop(0);

    $('#menu').velocity({
        top: 0
    }, 900);

    $('#content > p').velocity({
        opacity: 1
    }, 1500, 'linear');

    $('#categories').velocity({
        marginLeft: '2%'
    },900, 'linear');

    $('#chart_div').velocity({
        opacity: 1
    },900, 'linear');

    setTimeout(introAnimation, 800);

    function introAnimation() {

        $('#logo').velocity({
            opacity: 1
        }, 900, 'linear');

        $('nav > ul > li').velocity({
            opacity: 1
        }, 900, 'linear');

        $('#data').velocity({
            opacity: 1
        }, 900, 'linear');

        $('#social').velocity({
            opacity: 1
        }, 900, 'linear');

    }

    $('.facebook, .facebook > i').hover(function(){
        $('.facebook > i').css('color', '#3b5998');
    });

    $('.facebook').mouseout(function(){
        $('.facebook > i').css('color', '#ddd');
    });

    $('.facebook > i').mouseout(function(){
        $('.facebook > i').css('color', '#3b5998');
    });

    $('.twitter, .twitter > i').hover(function(){
        $('.twitter > i').css('color', '#1da1f2');
    });

    $('.twitter').mouseout(function(){
        $('.twitter > i').css('color', '#ddd');
    });

    $('.twitter > i').mouseout(function(){
        $('.twitter > i').css('color', '#1da1f2');
    });

    $('.googlePlus, .googlePlus > i').hover(function(){
        $('.googlePlus > i').css('color', '#e53935');
    });

    $('.googlePlus').mouseout(function(){
        $('.googlePlus > i').css('color', '#ddd');
    });

    $('.googlePlus > i').mouseout(function(){
        $('.googlePlus > i').css('color', '#e53935');
    });

    /* Show button - End */

});

function loadData(file, colorForSex, marker){

    var region = $('select[name="region"] option:selected').val();

    getFile(file);

    var data = google.visualization.arrayToDataTable(processedData);

    var options = {
        region: region,
        backgroundColor: 'none',
        chartArea: { width: '100%', height: '100%' },
        colorAxis: {colors: ['#ddd', colorForSex]},
        datalessRegionColor: 'white',
        displayMode: marker,
        legend: {
            numberFormat: '.##',
            textStyle: {
                fontName: 'Verdana',
                color: '#ff1a1a',
                fontSize: 14
            }
        }
    };

    chart.draw(data, options);
    chart.draw(data, options);
}

function getFile(fileUrl){
    $.get(fileUrl+'?q='+Math.random(), function(data) {

            processedData = $.csv.toArrays(data);

            var j = 1;

            for (var i = 1; i < processedData.length; i++) {
                for(var k = 0; k < processedData[i][j].length; k++){
                    if(processedData[i][j].charAt(k) == ','){
                        processedData[i][j]=processedData[i][j].substring(0,k)+processedData[i][j].substring(k+1,processedData[i][j].length-1);
                    }
                }
                processedData[i][j] = parseFloat(processedData[i][j]);
            }

    }, 'text');

    return processedData;
}
</code>```

And here is my HTML code

```<code><!DOCTYPE html>
<html>
<head>

    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Nunito+Sans:900|Roboto:400,700"/>
    <link rel="stylesheet" href="style.css"/>
    <link rel="stylesheet" href="font-awesome-4.7.0/css/font-awesome.min.css"/>
    <title>Facts About Migration | Home</title>

    <script type="text/javascript" src="jquery-3.2.1.min.js"></script>
    <script type="text/javascript" src="jquery.csv.min.js"></script>
    <script type="text/javascript" src="velocity.min.js"></script>
    <script type="text/javascript" src="velocity.ui.min.js"></script>

    <!-- Fav Icon -->

    <link rel="apple-touch-icon" sizes="57x57" href="images/favIco/apple-icon-57x57.png">
    <link rel="apple-touch-icon" sizes="60x60" href="images/favIco/apple-icon-60x60.png">
    <link rel="apple-touch-icon" sizes="72x72" href="images/favIco/apple-icon-72x72.png">
    <link rel="apple-touch-icon" sizes="76x76" href="images/favIco/apple-icon-76x76.png">
    <link rel="apple-touch-icon" sizes="114x114" href="images/favIco/apple-icon-114x114.png">
    <link rel="apple-touch-icon" sizes="120x120" href="images/favIco/apple-icon-120x120.png">
    <link rel="apple-touch-icon" sizes="144x144" href="images/favIco/apple-icon-144x144.png">
    <link rel="apple-touch-icon" sizes="152x152" href="images/favIco/apple-icon-152x152.png">
    <link rel="apple-touch-icon" sizes="180x180" href="images/favIco/apple-icon-180x180.png">
    <link rel="icon" type="image/png" sizes="192x192"  href="images/favIco/android-icon-192x192.png">
    <link rel="icon" type="image/png" sizes="32x32" href="images/favIco/favicon-32x32.png">
    <link rel="icon" type="image/png" sizes="96x96" href="images/favIco/favicon-96x96.png">
    <link rel="icon" type="image/png" sizes="16x16" href="images/favIco/favicon-16x16.png">
    <link rel="manifest" href="images/favIco/manifest.json">
    <meta name="msapplication-TileColor" content="#ffffff">
    <meta name="msapplication-TileImage" content="images/favIco/ms-icon-144x144.png">
    <meta name="theme-color" content="#ffffff">

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

    <!-- Fav Icon - End -->
</head>
<body>
    <div id="menu">
            <div id="logo">
                <a href="#"><img id="logoImg" src="images/logo.png"/></a>
            </div>
            <ul>
                <li class="navLi"><a class="nav" href="#" id="activeNav">HOME</a></li>
                <li class="navLi"><a class="nav" href="#">ABOUT US</a></li>
                <li class="navLi"><a class="nav" href="#">SPONSORS</a></li>
                <li class="navLi"><a class="nav" href="#">CONTACT US</a></li>
                <div id="socialDiv">
                    <li class="facebook social"><a href="#"><i class="fa fa-facebook-square" aria-hidden="true"></i></a></li>
                    <li class="twitter social"><a href="#"><i class="fa fa-twitter-square" aria-hidden="true"></i></a></li>
                    <li class="googlePlus social"><a href="#"><i class="fa fa-google-plus-square" aria-hidden="true"></i></a></li>
                </div>
            </ul>
    </div>
    <div id="mainApp">
        <main>
            <form name="categories" id="categories">
                <select name="region">
                    <option value="world" selected>Show All</option>
                    <option value="CH">Switzerland</option>
                </select>
                <select name="sex">
                    <option value="all" selected>Sex (Both)</option>
                    <option value="male">Male</option>
                    <option value="female">Female</option>
                </select>
                <select name="age">
                    <option value="all" selected>Age (All)</option>
                    <option value="0-14">0 - 14</option>
                    <option value="15-19">15 - 19</option>
                    <option value="20-39">20 - 39</option>
                    <option value="40-64">40 - 64</option>
                    <option value="65-79">65 - 79</option>
                    <option value="80+">80+</option>
                </select>
                <select name="permOrNot">
                    <option value="all">Permanent and Non permanent
Foreign residents</option>
                    <option value="perm">Permanent foreign resident population</option>
                    <option value="not">Non permanent
Foreign residents </option>
                </select>
                <select name="permSelect">
                    <option value="all">All Permanent foreign resident population</option>
                    <option value="short">Short-term residents (L)</option>
                    <option value="residents">Residents (B)</option>
                    <option value="settled">Settled (C)</option>
                </select>
                <input type="button" name="categoriesButton" id="showButton" value="SHOW ON MAP"/>
            </form>
            <div id="chart_div">

            </div>
        </main>
    </div>
    <div id="content">
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec eget ipsum ut urna convallis elementum. Etiam a fringilla felis. Pellentesque iaculis eu turpis et placerat. Maecenas posuere rutrum turpis, non cursus justo. Vivamus vestibulum tincidunt felis et elementum. Duis dapibus interdum leo quis euismod. Nulla ullamcorper elementum felis et malesuada. Integer pharetra sem vel fermentum gravida. Ut facilisis placerat pellentesque.</p>
        <p>Vestibulum maximus arcu non est luctus, sit amet pharetra lorem consectetur. Duis vitae risus ac metus sagittis gravida. Aenean vulputate magna ac leo feugiat ornare. Sed laoreet nulla vel nibh blandit, sed mollis elit placerat. Ut vel diam finibus, lacinia lectus id, iaculis nisi. Sed hendrerit dui risus, a dictum purus varius a. Curabitur congue, mi eget ullamcorper bibendum, odio nisi egestas nunc, venenatis rutrum magna ipsum ac purus.</p>
    </div>
    <div class="windowBox box1">

    </div>
    <footer>
        <a href="#">
        <div class="sponsors">
            <img src="images/logoExample.png"/>
        </div>
        </a>
        <a href="#">
        <div class="sponsors">
            <img src="images/logoExample.png"/>
        </div>
        </a>
        <a href="#">
        <div class="sponsors">
            <img src="images/logoExample.png"/>
        </div>
        </a>
        <a href="#">
        <div class="sponsors">
            <img src="images/logoExample.png"/>
        </div>
        </a>
        <a href="#">
        <div class="sponsors">
            <img src="images/logoExample.png"/>
        </div>
        </a>
    </footer>
    <div id="bottom">
        <ul id="bottomLeft">
            <li>Copyright © 2017. All rights reserved.</li>
            <li><a href="#">Home</a></li>
            <li><a href="#">About Us</a></li>
            <li><a href="#">Sponsors</a></li>
            <li><a href="#">Contact Us</a></li>
        </ul>
        <ul id="bottomRight">
                <a href="#" class="facebookFooter"><li class="facebookFooter"><i class="fa fa-facebook-square facebookFooter" aria-hidden="true"></i></li></a>
                <a href="#" class="twitterFooter"><li class="twitterFooter"><i class="fa fa-twitter-square twitterFooter" aria-hidden="true"></i></li></a>
                <a href="#" class="googlePlusFooter"><li class="googlePlusFooter"><i class="fa fa-google-plus-square googlePlusFooter" aria-hidden="true"></i></li></a>
        </ul>
    </div>
</body>
</html>
</code>```

答: I have found a solution. It was hiding in the ajax setup settings. The code at the start of the script file was enough to solve the problem - $.ajaxSetup({async:false});

Title: Google GeoCharts Data not loading

Body:
So here is the problem in attached code. I have a GeoCharts div with a form div next to it, in the background there are multiple CSV documents that are managing the data. The goal is to load the data by the current selection of filters in the form div when the #showButton is pressed.

So when the page is loaded the 'general' CSV document is loaded to represent the data and when the user wants to see data by the current filters selection the other CSV document is loaded when the user presses #showButton. But the thing is that that happens only when the #showButton is pressed twice with nothing changing in the filters the second times.

Everything else like the displayMode (markers) variable that is passed to the function and the colorForSex variable gets loaded and applied to the GeoCharts div but the CSV file and all the data gets loaded only the second time that the button is pressed (again - without changing the filters the second time it is pressed).

/*

Coded by : Roland Stojkoski;

Contact : roland.roland.roli@gmail.com

*/

/* CSV handling - START */

var processedData = [];

var newData = [];

var region = $('select[name="region"] option:selected').val();
var sex = $('select[name="sex"] option:selected').val();
var age = $('select[name="age"] option:selected').val();
var permOrNot = $('select[name="permOrNot"] option:selected').val();
var permSelect = $('select[name="permSelect"] option:selected').val();

getFile('csv/Residence_All.csv');

/* CSV handling - END */

var chart;
var data;

$(document).ready(function(){

    /* Google Charts */

    google.charts.load('current', {
        'packages':['geochart'],
        'mapsApiKey': 'AIzaSyBHggo3wq70fGWUJwvCCHNnQm0E4R2G_l8 ',
        'callback': drawRegionsMap
    });
    google.charts.setOnLoadCallback(drawRegionsMap);

    function drawRegionsMap() {
        region = $('select[name="region"] option:selected').val();
        data = google.visualization.arrayToDataTable(processedData);

        var options = {
            region: region,
            backgroundColor: 'none',
            chartArea: { width: '100%', height: '100%' },
            colorAxis: {colors: ['#ddd','#ff1a1a']},
            datalessRegionColor: 'white',
            displayMode: 'markers',
            legend: {
                numberFormat: '.##',
                textStyle: {
                    fontName: 'Nunito Sans',
                    color: '#ff1a1a',
                    fontSize: 14,
                }
            }
        };

        chart = new google.visualization.GeoChart(document.getElementById('chart_div'));

        chart.draw(data, options);
    }

    $('#showButton').click(function(){
        if($('select[name="region"] option:selected').val() === 'world' && $('select[name="sex"] option:selected').val() === 'all' && $('select[name="age"] option:selected').val() === 'all' ){
            loadData('csv/Origin_All.csv', '#a80000', 'regions');
        }else if ($('select[name="region"] option:selected').val() === 'world' && $('select[name="sex"] option:selected').val() === 'female'){
            loadData('csv/Origin_Sex_Female.csv', '#ff9933', 'regions');
        }else if ($('select[name="region"] option:selected').val() === 'CH'){
            loadData('csv/Residence_All.csv', '#a80000', 'text');
        }
    });

    $('select').change(function(){
        if($('select[name="region"] option:selected').val() === 'world'){
            $('select[name="age"]').fadeIn();
            $('select[name="permOrNot"]').fadeOut();
            if($('select[name="sex"] option:selected').val() != 'all'){
                $('select[name="age"]').fadeOut();
            }else{
                $('select[name="age"]').fadeIn();
            }
            if($('select[name="age"] option:selected').val() != 'all'){
                $('select[name="sex"]').fadeOut();
            }else{
                $('select[name="sex"]').fadeIn();
            }
        }else if($('select[name="region"] option:selected').val() === 'CH'){
            $('select[name="age"]').fadeOut();
            $('select[name="permOrNot"]').fadeIn();
            if($('select[name="permOrNot"] option:selected').val() === 'perm'){
                $('select[name="permSelect"]').fadeIn();
            }else{
                $('select[name="permSelect"]').fadeOut();
            }
        }
    });

    $(document).scrollTop(0);

    $('#menu').velocity({
        top: 0
    }, 900);

    $('#content > p').velocity({
        opacity: 1
    }, 1500, 'linear');

    $('#categories').velocity({
        marginLeft: '2%'
    },900, 'linear');

    $('#chart_div').velocity({
        opacity: 1
    },900, 'linear');

    setTimeout(introAnimation, 800);

    function introAnimation() {

        $('#logo').velocity({
            opacity: 1
        }, 900, 'linear');

        $('nav > ul > li').velocity({
            opacity: 1
        }, 900, 'linear');

        $('#data').velocity({
            opacity: 1
        }, 900, 'linear');

        $('#social').velocity({
            opacity: 1
        }, 900, 'linear');

    }

    $('.facebook, .facebook > i').hover(function(){
        $('.facebook > i').css('color', '#3b5998');
    });

    $('.facebook').mouseout(function(){
        $('.facebook > i').css('color', '#ddd');
    });

    $('.facebook > i').mouseout(function(){
        $('.facebook > i').css('color', '#3b5998');
    });

    $('.twitter, .twitter > i').hover(function(){
        $('.twitter > i').css('color', '#1da1f2');
    });

    $('.twitter').mouseout(function(){
        $('.twitter > i').css('color', '#ddd');
    });

    $('.twitter > i').mouseout(function(){
        $('.twitter > i').css('color', '#1da1f2');
    });

    $('.googlePlus, .googlePlus > i').hover(function(){
        $('.googlePlus > i').css('color', '#e53935');
    });

    $('.googlePlus').mouseout(function(){
        $('.googlePlus > i').css('color', '#ddd');
    });

    $('.googlePlus > i').mouseout(function(){
        $('.googlePlus > i').css('color', '#e53935');
    });

    /* Show button - End */

});

function loadData(file, colorForSex, marker){

    var region = $('select[name="region"] option:selected').val();

    getFile(file);

    var data = google.visualization.arrayToDataTable(processedData);

    var options = {
        region: region,
        backgroundColor: 'none',
        chartArea: { width: '100%', height: '100%' },
        colorAxis: {colors: ['#ddd', colorForSex]},
        datalessRegionColor: 'white',
        displayMode: marker,
        legend: {
            numberFormat: '.##',
            textStyle: {
                fontName: 'Verdana',
                color: '#ff1a1a',
                fontSize: 14
            }
        }
    };

    chart.draw(data, options);
    chart.draw(data, options);
}

function getFile(fileUrl){
    $.get(fileUrl+'?q='+Math.random(), function(data) {

            processedData = $.csv.toArrays(data);

            var j = 1;

            for (var i = 1; i < processedData.length; i++) {
                for(var k = 0; k < processedData[i][j].length; k++){
                    if(processedData[i][j].charAt(k) == ','){
                        processedData[i][j]=processedData[i][j].substring(0,k)+processedData[i][j].substring(k+1,processedData[i][j].length-1);
                    }
                }
                processedData[i][j] = parseFloat(processedData[i][j]);
            }

    }, 'text');

    return processedData;
}

And here is my HTML code

<!DOCTYPE html>

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Nunito+Sans:900|Roboto:400,700"/>
    <link rel="stylesheet" href="style.css"/>
    <link rel="stylesheet" href="font-awesome-4.7.0/css/font-awesome.min.css"/>
    <title>Facts About Migration | Home</title>

    <link rel="apple-touch-icon" sizes="57x57" href="images/favIco/apple-icon-57x57.png">
    <link rel="apple-touch-icon" sizes="60x60" href="images/favIco/apple-icon-60x60.png">
    <link rel="apple-touch-icon" sizes="72x72" href="images/favIco/apple-icon-72x72.png">
    <link rel="apple-touch-icon" sizes="76x76" href="images/favIco/apple-icon-76x76.png">
    <link rel="apple-touch-icon" sizes="114x114" href="images/favIco/apple-icon-114x114.png">
    <link rel="apple-touch-icon" sizes="120x120" href="images/favIco/apple-icon-120x120.png">
    <link rel="apple-touch-icon" sizes="144x144" href="images/favIco/apple-icon-144x144.png">
    <link rel="apple-touch-icon" sizes="152x152" href="images/favIco/apple-icon-152x152.png">
    <link rel="apple-touch-icon" sizes="180x180" href="images/favIco/apple-icon-180x180.png">
    <link rel="icon" type="image/png" sizes="192x192"  href="images/favIco/android-icon-192x192.png">
    <link rel="icon" type="image/png" sizes="32x32" href="images/favIco/favicon-32x32.png">
    <link rel="icon" type="image/png" sizes="96x96" href="images/favIco/favicon-96x96.png">
    <link rel="icon" type="image/png" sizes="16x16" href="images/favIco/favicon-16x16.png">
    <link rel="manifest" href="images/favIco/manifest.json">
    <meta name="msapplication-TileColor" content="#ffffff">
    <meta name="msapplication-TileImage" content="images/favIco/ms-icon-144x144.png">
    <meta name="theme-color" content="#ffffff">

HOME

ABOUT US

SPONSORS

CONTACT US

            <form name="categories" id="categories">
                <select name="region">
                    <option value="world" selected>Show All</option>
                    <option value="CH">Switzerland</option>
                </select>
                <select name="sex">
                    <option value="all" selected>Sex (Both)</option>
                    <option value="male">Male</option>
                    <option value="female">Female</option>
                </select>
                <select name="age">
                    <option value="all" selected>Age (All)</option>
                    <option value="0-14">0 - 14</option>
                    <option value="15-19">15 - 19</option>
                    <option value="20-39">20 - 39</option>
                    <option value="40-64">40 - 64</option>
                    <option value="65-79">65 - 79</option>
                    <option value="80+">80+</option>
                </select>
                <select name="permOrNot">
                    <option value="all">Permanent and Non permanent
Foreign residents</option>
                    <option value="perm">Permanent foreign resident population</option>
                    <option value="not">Non permanent
Foreign residents </option>
                </select>
                <select name="permSelect">
                    <option value="all">All Permanent foreign resident population</option>
                    <option value="short">Short-term residents (L)</option>
                    <option value="residents">Residents (B)</option>
                    <option value="settled">Settled (C)</option>
                </select>
                <input type="button" name="categoriesButton" id="showButton" value="SHOW ON MAP"/>
            </form>

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec eget ipsum ut urna convallis elementum. Etiam a fringilla felis. Pellentesque iaculis eu turpis et placerat. Maecenas posuere rutrum turpis, non cursus justo. Vivamus vestibulum tincidunt felis et elementum. Duis dapibus interdum leo quis euismod. Nulla ullamcorper elementum felis et malesuada. Integer pharetra sem vel fermentum gravida. Ut facilisis placerat pellentesque.

Vestibulum maximus arcu non est luctus, sit amet pharetra lorem consectetur. Duis vitae risus ac metus sagittis gravida. Aenean vulputate magna ac leo feugiat ornare. Sed laoreet nulla vel nibh blandit, sed mollis elit placerat. Ut vel diam finibus, lacinia lectus id, iaculis nisi. Sed hendrerit dui risus, a dictum purus varius a. Curabitur congue, mi eget ullamcorper bibendum, odio nisi egestas nunc, venenatis rutrum magna ipsum ac purus.

Copyright © 2017. All rights reserved.

Home

About Us

Sponsors

Contact Us


问:
GPU-enabled CNTK 2.0 for Python appears to hang with 100% CPU thread workload in Anaconda 3 4.4.0, Windows 10 Pro 64bit
Is there a known issue that prevents the GPU-enabled version of CNTK 2.0 from running in Anaconda 3 4.4.0 64bit, Windows 10 Pro 64bit?

I have installed Anaconda 4.4.0, created an environment with Python 3.6.1 and installed CNTK using the precompiled CNTK GPU image for Python 3.6, according to the instructions found under "First time CNTK installation", here:

https://learn.microsoft.com/en-us/cognitive-toolkit/Setup-Windows-Python

The quick installation test works fine:

```<code>python -c "import cntk; print(cntk.__version__)"
</code>```

However, when I invoke a CNTK function, for example:

```<code>import cntk
cntk.minus([1, 2, 3], [4, 5, 6]).eval()
</code>```

one thread of the CPU takes 100% workload and the program doesn't produce any output. It freezes until I press "<"CTRL>+"<"BREAK>, at which point it is terminated and the respective CPU thread workload falls back to 0%.

Similarly, in the following example, the program hangs when it executes the last line:

```<code>import numpy as np
x = cntk.input_variable(2)
y = cntk.input_variable(2)
x0 = np.asarray([[2., 1.]], dtype=np.float32)
y0 = np.asarray([[4., 6.]], dtype=np.float32)
cntk.squared_error(x, y).eval({x:x0, y:y0})
</code>```

The GPU load is 0% at all times, while attempting to run the examples.

When I replace the GPU-enabled version of CNTK with the CPU-only version, in the same anaconda environment, the examples work as expected.

答: The problem was resolved by deactivating SLI from the NVIDIA Control Panel.</p>

Body:
Is there a known issue that prevents the GPU-enabled version of CNTK 2.0 from running in Anaconda 3 4.4.0 64bit, Windows 10 Pro 64bit?

I have installed Anaconda 4.4.0, created an environment with Python 3.6.1 and installed CNTK using the precompiled CNTK GPU image for Python 3.6, according to the instructions found under "First time CNTK installation", here:

https://learn.microsoft.com/en-us/cognitive-toolkit/Setup-Windows-Python

The quick installation test works fine:

python -c "import cntk; print(cntk.__version__)"

However, when I invoke a CNTK function, for example:

import cntk
cntk.minus([1, 2, 3], [4, 5, 6]).eval()

one thread of the CPU takes 100% workload and the program doesn't produce any output. It freezes until I press "<"CTRL>+"<"BREAK>, at which point it is terminated and the respective CPU thread workload falls back to 0%.

Similarly, in the following example, the program hangs when it executes the last line:

import numpy as np
x = cntk.input_variable(2)
y = cntk.input_variable(2)
x0 = np.asarray([[2., 1.]], dtype=np.float32)
y0 = np.asarray([[4., 6.]], dtype=np.float32)
cntk.squared_error(x, y).eval({x:x0, y:y0})

The GPU load is 0% at all times, while attempting to run the examples.

When I replace the GPU-enabled version of CNTK with the CPU-only version, in the same anaconda environment, the examples work as expected.


问:
Angular - Re-Populate form inputs from service
I have a basic angular component that allows some one to edit the details of a user once they go to their profile and click on "edit".

Component:

```<code>export class EditUserComponent implements OnInit {

    // Define our vars
    user: Users[];
    editUserForm: FormGroup;
    message: {};
    displayMessage = false;
    userID: number;
    errorMessage: any = '';

    constructor(
        private fb: FormBuilder,
        private _userService: UserService,
        private activatedRoute: ActivatedRoute
    ) {
    }

    ngOnInit(): void {

        // Get the userID from the activated route
        this.activatedRoute.params.subscribe((params: Params) => {
            this.userID = params['id'];
        });

        // Call our service and pass the UserID
        this._userService.getUser(this.userID)
            .then(res => {
                this.user = res;
                this.createForm();
            });

    }

    // Generate the form
    createForm() {
        this.editUserForm = this.fb.group({
            QID: ['', Validators.required],
            favoriteColor: [''],
            favoriteNumber: [''],
            favoriteActor: ['']
        });
    }

}
</code>```

Service:

```<code>// Fetch a single user
    getUser(userID: number) {
        return this._http.post(this.baseUrl + '/fetchUser', { "userID": userID }, { "headers": this.headers })
            .toPromise()
            .then(res => res.json())
            .catch(err => { this.handleError(err); });
    }
</code>```

Interface:

```<code>export interface Users {
    RecordID?: number;
    QID: string;
    favoriteColor?: string;
    favoriteNumber?: number;
    favoriteActor?: string;
}
</code>```

I am trying to pass the values to my formGroup but I am having trouble figuring out how to access the values.

I assumed I could do something like this where I could access the user model and select a property from it but that is throwing an undefined error.

Would I pass the values here in the form group or bind them to the elements directly somehow? I am receiving the data back from the service just fine, just not sure how to get each of the values back to their respective fields.

```<code>createForm() {
    this.editUserForm = this.fb.group({
        QID: [this.user.QID, Validators.required],
        favoriteColor: [''],
        favoriteNumber: [''],
        favoriteActor: ['']
    });
}
</code>```

答:
If I understand correctly ... this is what my code looks like:

```<code>onProductRetrieved(product: IProduct): void {
    if (this.productForm) {
        this.productForm.reset();
    }
    this.product = product;

    // Update the data on the form
    this.productForm.patchValue({
        productName: this.product.productName,
        productCode: this.product.productCode,
        starRating: this.product.starRating,
        description: this.product.description
    });
    this.productForm.setControl('tags', this.fb.array(this.product.tags || []));
}
</code>```

I'm using patchValue for the values and setControl for the array.

OR

Since you are creating the form after retrieving the data, you could do something like this:

```<code>createForm() {
    this.editUserForm = this.fb.group({
        QID: [this.user.QID, Validators.required],
        favoriteColor: [this.user.favoriteColor],
        favoriteNumber: [this.user.favoriteNumber],
        favoriteActor: [this.user.favoriteActor]
    });
}
</code>```

AND just to be complete ... each input element needs a formControlName property like this:

```<code>                    <input class="form-control"
                            id="productNameId"
                            type="text"
                            placeholder="Name (required)"
                            formControlName="productName" />
                    <span class="help-block" *ngIf="displayMessage.productName">
                            {{displayMessage.productName}}
                    </span>
                </div>
</code>```

You can find a complete working example here: https://github.com/DeborahK/Angular2-ReactiveForms

Body:
I have a basic angular component that allows some one to edit the details of a user once they go to their profile and click on "edit".

Component:

export class EditUserComponent implements OnInit {

    // Define our vars
    user: Users[];
    editUserForm: FormGroup;
    message: {};
    displayMessage = false;
    userID: number;
    errorMessage: any = '';

    constructor(
        private fb: FormBuilder,
        private _userService: UserService,
        private activatedRoute: ActivatedRoute
    ) {
    }

    ngOnInit(): void {

        // Get the userID from the activated route
        this.activatedRoute.params.subscribe((params: Params) => {
            this.userID = params['id'];
        });

        // Call our service and pass the UserID
        this._userService.getUser(this.userID)
            .then(res => {
                this.user = res;
                this.createForm();
            });

    }

    // Generate the form
    createForm() {
        this.editUserForm = this.fb.group({
            QID: ['', Validators.required],
            favoriteColor: [''],
            favoriteNumber: [''],
            favoriteActor: ['']
        });
    }

}

Service:

// Fetch a single user
    getUser(userID: number) {
        return this._http.post(this.baseUrl + '/fetchUser', { "userID": userID }, { "headers": this.headers })
            .toPromise()
            .then(res => res.json())
            .catch(err => { this.handleError(err); });
    }

Interface:

export interface Users {
    RecordID?: number;
    QID: string;
    favoriteColor?: string;
    favoriteNumber?: number;
    favoriteActor?: string;
}

I am trying to pass the values to my formGroup but I am having trouble figuring out how to access the values.

I assumed I could do something like this where I could access the user model and select a property from it but that is throwing an undefined error.

Would I pass the values here in the form group or bind them to the elements directly somehow? I am receiving the data back from the service just fine, just not sure how to get each of the values back to their respective fields.

createForm() {
    this.editUserForm = this.fb.group({
        QID: [this.user.QID, Validators.required],
        favoriteColor: [''],
        favoriteNumber: [''],
        favoriteActor: ['']
    });
}

Body:
If I understand correctly ... this is what my code looks like:

onProductRetrieved(product: IProduct): void {
    if (this.productForm) {
        this.productForm.reset();
    }
    this.product = product;

    // Update the data on the form
    this.productForm.patchValue({
        productName: this.product.productName,
        productCode: this.product.productCode,
        starRating: this.product.starRating,
        description: this.product.description
    });
    this.productForm.setControl('tags', this.fb.array(this.product.tags || []));
}

I'm using patchValue for the values and setControl for the array.

OR

Since you are creating the form after retrieving the data, you could do something like this:

createForm() {
    this.editUserForm = this.fb.group({
        QID: [this.user.QID, Validators.required],
        favoriteColor: [this.user.favoriteColor],
        favoriteNumber: [this.user.favoriteNumber],
        favoriteActor: [this.user.favoriteActor]
    });
}

AND just to be complete ... each input element needs a formControlName property like this:

                    <input class="form-control"
                            id="productNameId"
                            type="text"
                            placeholder="Name (required)"
                            formControlName="productName" />
                    <span class="help-block" *ngIf="displayMessage.productName">
                            {{displayMessage.productName}}
                    </span>
                </div>

You can find a complete working example here: https://github.com/DeborahK/Angular2-ReactiveForms


问:
Ember - JSON import - not displaying template content
I am working with the Ember CLI.

I have a JSON in this format:

public/assets/data.json

```<code>{
  "important": [
    {
      "name": "first",
      "value": 10
    },
    {
      "name": "second",
      "value": 10
    },
    ...
  ],
  "unimportant1": {
    ...
  },
  "unimportant2": {
    ...
  }
  ...
}
</code>```

I want to import "important" for use in a model.
I have attempted the following:

app/routes/important.js

```<code>import Ember from 'ember';

export default Ember.Route.extend({
  model() {
    return Ember.$.getJSON("/assets/data.json").important;
  }
});
</code>```

The console log does not display any errors.

I want to display the items in "important".
I have attempted the following:

app/templates/important.hbs

```<code>{{#each model as |important|}}
  <div>
    {{important.name}}{{important.value}}
  </div>
{{/each}}
</code>```

However, nothing is displayed. How can I get them to display?

I noticed that the items display as expected if I copy and paste the array into the return statement:

app/routes/important.js

```<code>import Ember from 'ember';

export default Ember.Route.extend({
  model() {
    return [
      {
        "name": "first",
        "value": 10
      },
      {
        "name": "second",
        "value": 10
      },
      ...
    ];
  }
});
</code>```

Any help is much appreciated.

答:
Ember.$.getJSON("/assets/data.json"); returns a promise, but Ember.$.getJSON("/assets/data.json").important; does not return a promise. It is just an undefined.

In your model hook, just return the promise:

```<code>model() {
  return Ember.$.getJSON("/assets/data.json");
}
</code>```

Then in your template, use it like:

```<code>{{#each model.important as |important|}}
  <div>
    {{important.name}}{{important.value}}
  </div>
{{/each}}
</code>```

Body:
I am working with the Ember CLI.

I have a JSON in this format:

public/assets/data.json

{
  "important": [
    {
      "name": "first",
      "value": 10
    },
    {
      "name": "second",
      "value": 10
    },
    ...
  ],
  "unimportant1": {
    ...
  },
  "unimportant2": {
    ...
  }
  ...
}

I want to import "important" for use in a model.
I have attempted the following:

app/routes/important.js

import Ember from 'ember';

export default Ember.Route.extend({
  model() {
    return Ember.$.getJSON("/assets/data.json").important;
  }
});

The console log does not display any errors.

I want to display the items in "important".
I have attempted the following:

app/templates/important.hbs

{{#each model as |important|}}

    {{important.name}}{{important.value}}

{{/each}}

However, nothing is displayed. How can I get them to display?

I noticed that the items display as expected if I copy and paste the array into the return statement:

app/routes/important.js

import Ember from 'ember';

export default Ember.Route.extend({
  model() {
    return [
      {
        "name": "first",
        "value": 10
      },
      {
        "name": "second",
        "value": 10
      },
      ...
    ];
  }
});

Any help is much appreciated.

Body:
Ember.$.getJSON("/assets/data.json"); returns a promise, but Ember.$.getJSON("/assets/data.json").important; does not return a promise. It is just an undefined.

In your model hook, just return the promise:

model() {
  return Ember.$.getJSON("/assets/data.json");
}

Then in your template, use it like:

{{#each model.important as |important|}}
  <div>
    {{important.name}}{{important.value}}
  </div>
{{/each}}


问:
Block users in online Android app
I'm developing a mobile online Android game. Some of users violate game rules and I need to block them and restrict using some functions in the app.
What parameters I should to retrieve to identify users devices and then add into DB as blocked? What methods do you use to implement this functionality in your projects?

Update.
Now I already use IP address and ANDROID_ID, but users can change these parameters easily

Update 2.
I already use my own users system for identifying users. User need to create account using email. But the problem is bad users make new accounts and keep violating game rules. So the purpose is to block these users devices to prevent them even to create new account using that blocked device.

答: Imei perhaps. Good enough for me lol</p>

Title: Block users in online Android app

Body: Imei perhaps. Good enough for me lol


问:
Comparing file contents in F#
I wrote a quick and dirty function to compare file contents (BTW, I have already tested that they are of equal size):

```<code>let eqFiles f1 f2 =
  let bytes1 = Seq.ofArray (File.ReadAllBytes f1)
  let bytes2 = Seq.ofArray (File.ReadAllBytes f2)
  let res = Seq.compareWith (fun x y -> (int x) - (int y)) bytes1 bytes2
  res = 0
</code>```

I'm not happy with reading the whole contents into an array. I'd rather have a lazy sequence of bytes, but I can't find the right API in F#.

答: you must stream the files, just read them block by bloc, maybe File and Stream(and it's descendants like StreamReader and so )  libraries in .Net could address your need.

Title: Comparing file contents in F#

Body:
I wrote a quick and dirty function to compare file contents (BTW, I have already tested that they are of equal size):

let eqFiles f1 f2 =
  let bytes1 = Seq.ofArray (File.ReadAllBytes f1)
  let bytes2 = Seq.ofArray (File.ReadAllBytes f2)
  let res = Seq.compareWith (fun x y -> (int x) - (int y)) bytes1 bytes2
  res = 0

I'm not happy with reading the whole contents into an array. I'd rather have a lazy sequence of bytes, but I can't find the right API in F#.


问:
PDO execute in a if statment
I'm not sure if i'm doing this right.

This is the problem:

```<code>if ($result->execute() && $result2->execute()){}
</code>```

Is this something that can be done or not?

My goal is to do something inside IF only if both queries works.

I couldn't find nothing online about that.

答:
You can certainly do this. PDO's execute() statement returns true on success and false on failure. I would change the style somewhat so it's easier to read, but there's no reason you can't do this.

$success1 = $result->execute();
$success2 = $result2->execute();

if ( $success1 and $success2 ) {
    // Do stuff here on failure
}
else {
    // Do stuff on failure here
}
```

Title: PDO execute in a if statment

Body:
I'm not sure if i'm doing this right.

This is the problem:

if ($result->execute() && $result2->execute()){}

Is this something that can be done or not?

My goal is to do something inside IF only if both queries works.

I couldn't find nothing online about that.


问:
Different starting directory per window?
I daily use tmux (2.5) on my laptop to work, and my tmux sessions have a starting directory which is the working directory I started the tmux session from. Every pane/window I open start with this starting directory as working directory.

I can change this starting directory, and this change would apply to the whole session.

But if I want to work on a different project with several panes, I could start a new window, but every pane I would open in it would start with the session's starting directory : I would have to cd to the new location for each pane which isn't practical.

If I need to work on several project/directories simultaneously, I can start a new terminal session, then cd to the relevant directory/project and start a new tmux session. That's not complicated.

But if I want to do the same thing on a server through ssh, I'd need to either :

open a new ssh session.

either embed my remote tmux sessions in an other tmux session.

Neither sounds practical to me, I'd prefer a single tmux session on the remote machine.

I think it would be more convenient to being able to start new window with its own starting directory location that would apply to any new pane opened in it. Is there a way to achieve this?

Edit :

I already tried the -c parameter of tmux new-window command.

But it doesn't assign its starting directory to the window created this way, it only applies this custom starting directory to the first pane created.

Any new pane opened in this window then uses the session's starting directory as default working dir (and not the path passed to tmux new-window).

答:
This question is very similar to: https://unix.stackexchange.com/questions/12032/create-new-window-with-current-directory-in-tmux

It depends on your tmux version but the -c parameter does do the trick but it does not remember the setting. There used to be a default-path setting but that has been removed in version 1.9 unfortunately.

For newer versions you will need to pass along the -c in all cases (you can use an alias if you manually execute that command) or if you use key bindings you need to rebind the split/new window keys.

```<code>bind '"' split-window -c "#{pane_current_path}"
bind % split-window -h -c "#{pane_current_path}"
bind c new-window -c "#{pane_current_path}"
</code>```

To use a custom path instead of the current pane path, execute this command:

```<code>tmux setenv custom_path /home/whatever/some/path
</code>```

Put this in your config:

```<code>bind '"' split-window -c "#{custom_path}"
bind % split-window -h -c "#{custom_path}"
bind c new-window -c "#{custom_path}"
</code>```

Body:
This question is very similar to: https://unix.stackexchange.com/questions/12032/create-new-window-with-current-directory-in-tmux

It depends on your tmux version but the -c parameter does do the trick but it does not remember the setting. There used to be a default-path setting but that has been removed in version 1.9 unfortunately.

For newer versions you will need to pass along the -c in all cases (you can use an alias if you manually execute that command) or if you use key bindings you need to rebind the split/new window keys.

bind '"' split-window -c "#{pane_current_path}"
bind % split-window -h -c "#{pane_current_path}"
bind c new-window -c "#{pane_current_path}"

To use a custom path instead of the current pane path, execute this command:

tmux setenv custom_path /home/whatever/some/path

Put this in your config:

bind '"' split-window -c "#{custom_path}"
bind % split-window -h -c "#{custom_path}"
bind c new-window -c "#{custom_path}"


问:
Using mapply() For Column Row Comparison
I am working with two different large data set and trying to make use of mapply() to get iterative functions working.

The goal is to take each data point column wise from Data_1, and compare it against both the data points in column of Data_2. So, Data_1[1,1] will be compared against Data_2[1,1] and Data_2[2,1] only. To be more clear, data1 column in Data_1 will only be compared against dataA elements in Data_2, thus no cross column comparison.

Data_1: NxM

```<code>  data1       data2       data3      data4
-0.710003   -0.714271   -0.709946   -0.713645
-0.710458   -0.715011   -0.710117   -0.714157
-0.71071    -0.714048   -0.710235   -0.713515
-0.710255   -0.713991   -0.709722   -0.713972
</code>```

Data_2: PxQ

```<code>  dataA       dataB       dataC      dataD
-0.71097    -0.714059   -0.70928    -0.714059
-0.710343   -0.714576   -0.709338   -0.713644
</code>```

I had earlier written a for() while() loop based algorithm, but the run time was too much as the original data is . Then, I moved to apply() based logic, but still had loops within function I was calling, so that didn't speed up the code. Based on my earlier question, I am figuring out better way to do this with mapply().

The part I am not able to visualize is the column to row comparison and how mapply() will navigate over it recursively. How can I use mapply() or lapply() to get this done efficiently?

Any suggestions will be helpful, thanks.

答:
That's one solution based on data.table, but if you are using data.frame or matrix, it should be easy to adapt. To reach what you want you must use one lapply over another lapply. The higher one iterates over the columns, which calls the other to iterate over the rows.

```<code>library(data.table)

# it gets all elements of column 'j' to do diff computation
get_column_diff <- function(dt_1, dt_2, j){

        get_point_diff <- function(i){
                # it should return a vector with all differences
                # in comparison of the point (i,j)
                unlist(dt_1[i, ..j]) - unlist(dt_2[, ..j])
        }

        i_rows <- 1:nrow(dt_1)
        lapply(X=i_rows, FUN=get_point_diff)

}

j_cols <- 1:ncol(Data_1)
lapply(FUN=get_column_diff, dt_1=Data_1, dt_2=Data_2, X=j_cols)
</code>```

The function returns a list of list, each element of the list is the column result and its element is a list with the row result.

About the speed gain, i can't say how fast it will be without benchmark comparison, but probably it will be faster the any loop.

Body:
I am working with two different large data set and trying to make use of mapply() to get iterative functions working.

The goal is to take each data point column wise from Data_1, and compare it against both the data points in column of Data_2. So, Data_1[1,1] will be compared against Data_2[1,1] and Data_2[2,1] only. To be more clear, data1 column in Data_1 will only be compared against dataA elements in Data_2, thus no cross column comparison.

Data_1: NxM

  data1       data2       data3      data4
-0.710003   -0.714271   -0.709946   -0.713645
-0.710458   -0.715011   -0.710117   -0.714157
-0.71071    -0.714048   -0.710235   -0.713515
-0.710255   -0.713991   -0.709722   -0.713972

Data_2: PxQ

  dataA       dataB       dataC      dataD
-0.71097    -0.714059   -0.70928    -0.714059
-0.710343   -0.714576   -0.709338   -0.713644

I had earlier written a for() while() loop based algorithm, but the run time was too much as the original data is . Then, I moved to apply() based logic, but still had loops within function I was calling, so that didn't speed up the code. Based on my earlier question, I am figuring out better way to do this with mapply().

The part I am not able to visualize is the column to row comparison and how mapply() will navigate over it recursively. How can I use mapply() or lapply() to get this done efficiently?

Any suggestions will be helpful, thanks.

Body:
That's one solution based on data.table, but if you are using data.frame or matrix, it should be easy to adapt. To reach what you want you must use one lapply over another lapply. The higher one iterates over the columns, which calls the other to iterate over the rows.

library(data.table)

# it gets all elements of column 'j' to do diff computation
get_column_diff <- function(dt_1, dt_2, j){

        get_point_diff <- function(i){
                # it should return a vector with all differences
                # in comparison of the point (i,j)
                unlist(dt_1[i, ..j]) - unlist(dt_2[, ..j])
        }

        i_rows <- 1:nrow(dt_1)
        lapply(X=i_rows, FUN=get_point_diff)

}

j_cols <- 1:ncol(Data_1)
lapply(FUN=get_column_diff, dt_1=Data_1, dt_2=Data_2, X=j_cols)

The function returns a list of list, each element of the list is the column result and its element is a list with the row result.

About the speed gain, i can't say how fast it will be without benchmark comparison, but probably it will be faster the any loop.