答:
You need to position the div .side-bar explicitly at the top of its parent  using top: 0;. (Note this di is already positioned absolute)

```<code>.side-bar{
  top: 0;
  }
</code>```

Snippet below

@import url(http://fonts.googleapis.com/css?family=Lato);
.container {
  width: 800px;
  overflow: hidden;
  display: inline-block;
  margin-top: 0px;
}

.side-bar {
  background: #74AFAD;
  position: absolute;
  height: 100%;
  width: 200px;
  color: #fff;
  transition: margin-left 0.5s;
}

.side-bar ul {
  list-style: none;
  padding: 0px;
}

.side-bar ul li.menu-head {
  font-family: 'Lato', sans-serif;
  padding: 20px;
}

.side-bar ul li.menu-head a {
  color: #fff;
  text-decoration: none;
  height: 50px;
}

.side-bar ul .menu-head a {
  color: #fff;
  text-decoration: none;
  height: 50px;
  margin: 0;
}

.side-bar ul .menu li a {
  color: #fff;
  text-decoration: none;
  display: inline-table;
  width: 100%;
  padding-left: 20px;
  padding-right: 20px;
  padding-top: 10px;
  padding-bottom: 10px;
}

.side-bar ul .menu li a:hover {
  border-left: 3px solid #ECECEA;
  padding-left: 17px;
}

.side-bar ul .menu li a.active {
  padding-left: 17px;
  background: #D9853B;
  border-left: 3px solid #ECECEA;
}

.side-bar ul .menu li a.active:before {
  content: "";
  position: absolute;
  width: 0;
  height: 0;
  border-top: 20px solid transparent;
  border-bottom: 20px solid transparent;
  border-left: 7px solid #D9853B;
  margin-top: -10px;
  margin-left: 180px;
}

.content {
  padding-left: 200px;
  transition: padding-left 0.5s;
}

.active>.side-bar {
  margin-left: -150px;
  transition: margin-left 0.5s;
}

.active>.content {
  padding-left: 50px;
  transition: padding-left 0.5s;
}

#logout_sidebar {
  position: absolute;
  display: inline-block;
  bottom: 0;
  width: 100%;
}

@media screen and (max-width: 768px) {
  .row-offcanvas {
    position: relative;
    -webkit-transition: all 0.25s ease-out;
    -moz-transition: all 0.25s ease-out;
    transition: all 0.25s ease-out;
    width: calc(100% + 220px);
  }
  .row-offcanvas-left {
    left: -220px;
  }
  .row-offcanvas-left.active {
    left: 0;
  }
  .sidebar-offcanvas {
    position: absolute;
    top: 0;
  }
}

#sidebar {
  width: inherit;
  min-width: 220px;
  max-width: 220px;
  background-color: #f5f5f5;
  float: left;
  height: 100%;
  position: relative;
  overflow-y: auto;
  overflow-x: hidden;
}

#main {
  height: 100%;
  overflow: auto;
}

.side-bar {
  top: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <link rel="stylesheet" href="bootstrap-3.3.7-dist/css/bootstrap.min.css">
  <script src="bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
  <script type="text/javascript" src="js/main.js"></script>
  <link rel="stylesheet" type="text/css" href="css/navbar.css">

  <title> Bagus Gamestore Admin Dashboard</title>
</head>

<body>
  <div class="container">
    <div class="row">
      <div class="wrapper">
        <div class="side-bar">
          <ul>
            <li class="menu-head">
              ADMIN PANEL <span class="glyphicon glyphicon-align-justify pull-right"></span>
            </li>
            <div class="menu">
              <li>
                Dashboard <span class="glyphicon glyphicon-dashboard pull-right"></span>
              </li>
              <li>
                User List<span class="glyphicon glyphicon-user pull-right"></span>
              </li>
              <li>
                Add New Product<span class="glyphicon glyphicon-plus pull-right"></span>
              </li>
              <li>
                Go to Website <span class="glyphicon glyphicon-globe pull-right"></span>
              </li>
            </div>

            <div class="menu ">
              <li id="logout_sidebar">
                Logout<span class="glyphicon glyphicon-log-out pull-right"></span>
              </li>
            </div>
          </ul>
        </div>
        <div class="content">
          <!-- show user list -->
          <!-- end of show user list-->

        </div>
      </div>
    </div>
  </div>
</body>

</html></code>```

Title: How to remove white gap between navbar and header?

Body:
You need to position the div .side-bar explicitly at the top of its parent  using top: 0;. (Note this di is already positioned absolute)

.side-bar{
  top: 0;
  }

Snippet below

@import url(http://fonts.googleapis.com/css?family=Lato);
.container {
  width: 800px;
  overflow: hidden;
  display: inline-block;
  margin-top: 0px;
}

.side-bar {
  background: #74AFAD;
  position: absolute;
  height: 100%;
  width: 200px;
  color: #fff;
  transition: margin-left 0.5s;
}

.side-bar ul {
  list-style: none;
  padding: 0px;
}

.side-bar ul li.menu-head {
  font-family: 'Lato', sans-serif;
  padding: 20px;
}

.side-bar ul li.menu-head a {
  color: #fff;
  text-decoration: none;
  height: 50px;
}

.side-bar ul .menu-head a {
  color: #fff;
  text-decoration: none;
  height: 50px;
  margin: 0;
}

.side-bar ul .menu li a {
  color: #fff;
  text-decoration: none;
  display: inline-table;
  width: 100%;
  padding-left: 20px;
  padding-right: 20px;
  padding-top: 10px;
  padding-bottom: 10px;
}

.side-bar ul .menu li a:hover {
  border-left: 3px solid #ECECEA;
  padding-left: 17px;
}

.side-bar ul .menu li a.active {
  padding-left: 17px;
  background: #D9853B;
  border-left: 3px solid #ECECEA;
}

.side-bar ul .menu li a.active:before {
  content: "";
  position: absolute;
  width: 0;
  height: 0;
  border-top: 20px solid transparent;
  border-bottom: 20px solid transparent;
  border-left: 7px solid #D9853B;
  margin-top: -10px;
  margin-left: 180px;
}

.content {
  padding-left: 200px;
  transition: padding-left 0.5s;
}

.active>.side-bar {
  margin-left: -150px;
  transition: margin-left 0.5s;
}

.active>.content {
  padding-left: 50px;
  transition: padding-left 0.5s;
}

#logout_sidebar {
  position: absolute;
  display: inline-block;
  bottom: 0;
  width: 100%;
}

@media screen and (max-width: 768px) {
  .row-offcanvas {
    position: relative;
    -webkit-transition: all 0.25s ease-out;
    -moz-transition: all 0.25s ease-out;
    transition: all 0.25s ease-out;
    width: calc(100% + 220px);
  }
  .row-offcanvas-left {
    left: -220px;
  }
  .row-offcanvas-left.active {
    left: 0;
  }
  .sidebar-offcanvas {
    position: absolute;
    top: 0;
  }
}

#sidebar {
  width: inherit;
  min-width: 220px;
  max-width: 220px;
  background-color: #f5f5f5;
  float: left;
  height: 100%;
  position: relative;
  overflow-y: auto;
  overflow-x: hidden;
}

#main {
  height: 100%;
  overflow: auto;
}

.side-bar {
  top: 0;
}

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <link rel="stylesheet" href="bootstrap-3.3.7-dist/css/bootstrap.min.css">
  <script src="bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
  <script type="text/javascript" src="js/main.js"></script>
  <link rel="stylesheet" type="text/css" href="css/navbar.css">

  <title> Bagus Gamestore Admin Dashboard</title>
</head>

<body>
  <div class="container">
    <div class="row">
      <div class="wrapper">
        <div class="side-bar">
          <ul>
            <li class="menu-head">
              ADMIN PANEL <a href="#" class="push_menu"><span class="glyphicon glyphicon-align-justify pull-right"></span></a>
            </li>
            <div class="menu">
              <li>
                <a href="#" class="active">Dashboard <span class="glyphicon glyphicon-dashboard pull-right"></span></a>
              </li>
              <li>
                <a href="#">User List<span class="glyphicon glyphicon-user pull-right"></span></a>
              </li>
              <li>
                <a href="#">Add New Product<span class="glyphicon glyphicon-plus pull-right"></span></a>
              </li>
              <li>
                <a href="welcome.php">Go to Website <span class="glyphicon glyphicon-globe pull-right"></span></a>
              </li>
            </div>

            <div class="menu ">
              <li id="logout_sidebar">
                <a href="logout.php">Logout<span class="glyphicon glyphicon-log-out pull-right"></span></a>
              </li>
            </div>
          </ul>
        </div>
        <div class="content">
          <!-- show user list -->
          <!-- end of show user list-->

        </div>
      </div>
    </div>
  </div>
</body>

</html>


来源: stackexchange

问:
Should DAO objects be Classes or Structs?
I wanted to know from a performance point of view, should DAOs be classes or structs?

Taking into consideration that a lot of them might be created and they might be long lived objects.

What are your views and suggestions around the Data Layer design and using structs as DAOs

答:
THey should be objects.

You should only build structs if you are building a value type. such as: example: id.

Other than that, you should use object for Data access.

ContentLicense: CC BY-SA 2.5


问:
Can I access the registration tokens of all users registered in my Firebase notifications?
Sometimes I want to send a message through Firebase notifications to one unique user, then I want access the token from that user, so I like to know what is the best practice for get that token at any time?

On initial startup of my app, the FCM SDK generates a registration token for the client app instance.
I can get that token, but if I save that token in Firebase realtime database, I think other people can access that data because it is "set persistent mode on" to access offline data.

My questions is:
Is it possible to get tokens of all users without save that in a database?
Can I get these tokens direct from Firebase Authentication? If not, what is the best practice for access these tokens?

答:
I think other people can access that data because it is "set persistent mode on" to access offline data.

Simply save the registration token details to a secure node. Making sure that only you (or even including the user itself) to be the only ones that can access it. Read more on Understand Firebase Realtime Database Rules.

I can get that token, but if I save that token in Firebase realtime database, I think other people can access that data because it is "set persistent mode on" to access offline data.

Users won't be able to get the data they're not allowed to/wasn't designed to have on their device if you choose to restrict them.

Is it possible to get tokens of all users without save that in a database?

There is no API to get all the registration tokens related to your app. As mentioned in the documentation (emphasis mine):

After you've obtained the token, you can send it to your app server and store it using your preferred method. See the Instance ID API reference for full detail on the API.

It's the developer's (you) responsibility to send and store the registration token to a secure location.

Can I get these tokens direct from Firebase Authentication?

I'm not entirely sure what you mean by this. FCM Registration tokens are different from auth tokens. So, no.

If not, what is the best practice for access these tokens?

So long as you store the tokens in a secure location and make sure that you're always using the most recent/valid token, it should be good.

ContentLicense: CC BY-SA 3.0


问:
Get Sum of Exchange Mailbox Statistics
I'm trying to get the sum of the TotalItemSize for an Exchange database using the command

Get-MailboxStatistics -Database MBX07 | Measure-Object -Sum TotalItemSize

The command works perfectly fine in the Windows PowerShell ISE but if I run it in an Exchange EMS (both are on my local machine) I get errors for every mailbox in the database that say

Measure-Object : Input object "8.518 MB (8,932,049 bytes)" is not
  numeric.

The output in the ISE where the command works looks like

```<code>Count    : 174
Average  :
Sum      : 203481256406
Maximum  :
Minimum  :
Property : TotalItemSize
</code>```

It's an Exchange 2010 SP1 server running on Windows Server 2008 R2 and I'm running Windows 8.1 64bit

Any help is greatly appreciated

答:
Slightly more PowerShell native way, instead of calling a .NET method with ::

Get-Mailbox -Database "DB1" | Get-MailboxStatistics | ForEach-Object { $_.TotalItemSize.Value.ToGb() } | Measure-Object -sum

Title: Get Sum of Exchange Mailbox Statistics

Body:
I'm trying to get the sum of the TotalItemSize for an Exchange database using the command

Get-MailboxStatistics -Database MBX07 | Measure-Object -Sum TotalItemSize

The command works perfectly fine in the Windows PowerShell ISE but if I run it in an Exchange EMS (both are on my local machine) I get errors for every mailbox in the database that say

Measure-Object : Input object "8.518 MB (8,932,049 bytes)" is not
  numeric.

The output in the ISE where the command works looks like

Count    : 174
Average  :
Sum      : 203481256406
Maximum  :
Minimum  :
Property : TotalItemSize

It's an Exchange 2010 SP1 server running on Windows Server 2008 R2 and I'm running Windows 8.1 64bit

Any help is greatly appreciated


问:
Domain Driven Design question
I would like to ask for a reccomended solution for this:

 We have a list of Competitions.

 Each competition has defined fee that a participatior has to pay

We have Participators

I have to know has a Participator that is on a Competition paid the fee or not. I am thinking about 2 solutions and the thing is it has to be the most appropriate solution in Domain Driven Design.
First is to create a Dictionary in Competition instead of a List, the dictionary would have be of type <Participator, bool>.
The secont is perhaps create a different class that has 2 fields, a participator and feePaid. And in Competiton I would have a list of object of that new class.

Thank you

答:
sounds like a typical many to many relationship. i would model it with an Entry association class as follows:</p>

```<code>class Participator {
}
class Competition {
    Currency fee
}
class Entry {
    Competition competition
    Participator participator
    Boolean feePaid
}
</code>```

OwnerDisplayName: gljivar

Title: Domain Driven Design question

LastEditorDisplayName: tvanfosson

Body:
sounds like a typical many to many relationship. i would model it with an Entry association class as follows:

class Participator {
}
class Competition {
    Currency fee
}
class Entry {
    Competition competition
    Participator participator
    Boolean feePaid
}

OwnerDisplayName: Ray Tayek


问:
Build nested JSON in Javascript
I would like to replicate this example data set into nested JSON using JavaScript or Angularjs or any javascript library.

Data:

```<code>PrimaryId,FirstName,LastName,City,CarName,DogName
100,John,Smith,NewYork,Toyota,Spike
100,John,Smith,NewYork,BMW,Spike
100,John,Smith,NewYork,Toyota,Rusty
100,John,Smith,NewYork,BMW,Rusty
101,Ben,Swan,Sydney,Volkswagen,Buddy
101,Ben,Swan,Sydney,Ford,Buddy
101,Ben,Swan,Sydney,Audi,Buddy
101,Ben,Swan,Sydney,Volkswagen,Max
101,Ben,Swan,Sydney,Ford,Max
101,Ben,Swan,Sydney,Audi,Max
102,Julia,Brown,London,Mini,Lucy
</code>```

Javascript:

```<code>var file = reader.result;
var singleRow = readerFile.split(/\r\n|\n/);
var header = singleRow[0].split(',');
var result =[];

    for ( var i=1; i < file.length; i++ ){
        var elementData = singleRow[i].split(',');
        elementData = elementData.filter(function(n){ return n != "" });
        var Obj = {};

        for ( var j=0; j < header.length; j++ ){
            Obj[header[j]] = elementData[j];
            /*
              - How can i build child object and append back to Obj before j loop
              - How can i build multiple child for same parent
            */
        }
        result.push(Obj);
    }
    console.log(" Print the JSON Object : " + JSON.stringify(result));
</code>```

Desired Output:

```<code>{
    "data": [
        {
            "City": "NewYork",
            "FirstName": "John",
            "PrimaryId": 100,
            "LastName": "Smith",
            "CarName": [
                "Toyota",
                "BMW"
            ],
            "DogName": [
                "Spike",
                "Rusty"
            ]
        },
        {
            "City": "Sydney",
            "FirstName": "Ben",
            "PrimaryId": 101,
            "LastName": "Swan",
            "CarName": [
                "Volkswagen",
                "Ford",
                "Audi"
            ],
            "DogName": [
                "Buddy",
                "Max"
            ]
        },
        {
            "City": "London",
            "FirstName": "Julia",
            "PrimaryId": 102,
            "LastName": "Brown",
            "CarName": [
                "Mini"
            ],
            "DogName": [
                "Lucy"
            ]
        }
    ]
}
</code>```

If Firstname, Lastname and City has same values then CarName and DogName values should be child object under the same parent

答:
First of all, since you already know the property names, there's no point in parsing the first row.

I would do something like this:

```<code>let results = {};
for (let i = 1; i < file.length; i++) {
  let entry = getEntry(results, file[i][0]);
  entry.DogName.push(file[i][DOGNAME_INDEX]);
  entry.CarName.push(file[i][CARNAME_INDEX]);
  entry.LastName = file[i][LASTNAME_INDEX];
  ...
}

// and now to convert this into an array
let array = Object.keys(results).map(key => results[key]);

// retrieves or creates an entry for a given primary key
function getEntry(results, id) {
  return results[id] || (results[id] = {});
}
</code>```

You could also get fancier and dynamically determine what the column indexes are, but the way I have it just keeps things simple.

Title: Build nested JSON in Javascript

Body:
I would like to replicate this example data set into nested JSON using JavaScript or Angularjs or any javascript library.

Data:

PrimaryId,FirstName,LastName,City,CarName,DogName
100,John,Smith,NewYork,Toyota,Spike
100,John,Smith,NewYork,BMW,Spike
100,John,Smith,NewYork,Toyota,Rusty
100,John,Smith,NewYork,BMW,Rusty
101,Ben,Swan,Sydney,Volkswagen,Buddy
101,Ben,Swan,Sydney,Ford,Buddy
101,Ben,Swan,Sydney,Audi,Buddy
101,Ben,Swan,Sydney,Volkswagen,Max
101,Ben,Swan,Sydney,Ford,Max
101,Ben,Swan,Sydney,Audi,Max
102,Julia,Brown,London,Mini,Lucy

Javascript:

var file = reader.result;
var singleRow = readerFile.split(/\r\n|\n/);
var header = singleRow[0].split(',');
var result =[];

    for ( var i=1; i < file.length; i++ ){
        var elementData = singleRow[i].split(',');
        elementData = elementData.filter(function(n){ return n != "" });
        var Obj = {};

        for ( var j=0; j < header.length; j++ ){
            Obj[header[j]] = elementData[j];
            /*
              - How can i build child object and append back to Obj before j loop
              - How can i build multiple child for same parent
            */
        }
        result.push(Obj);
    }
    console.log(" Print the JSON Object : " + JSON.stringify(result));

Desired Output:

{
    "data": [
        {
            "City": "NewYork",
            "FirstName": "John",
            "PrimaryId": 100,
            "LastName": "Smith",
            "CarName": [
                "Toyota",
                "BMW"
            ],
            "DogName": [
                "Spike",
                "Rusty"
            ]
        },
        {
            "City": "Sydney",
            "FirstName": "Ben",
            "PrimaryId": 101,
            "LastName": "Swan",
            "CarName": [
                "Volkswagen",
                "Ford",
                "Audi"
            ],
            "DogName": [
                "Buddy",
                "Max"
            ]
        },
        {
            "City": "London",
            "FirstName": "Julia",
            "PrimaryId": 102,
            "LastName": "Brown",
            "CarName": [
                "Mini"
            ],
            "DogName": [
                "Lucy"
            ]
        }
    ]
}

If Firstname, Lastname and City has same values then CarName and DogName values should be child object under the same parent

Body:
First of all, since you already know the property names, there's no point in parsing the first row.

I would do something like this:

let results = {};
for (let i = 1; i < file.length; i++) {
  let entry = getEntry(results, file[i][0]);
  entry.DogName.push(file[i][DOGNAME_INDEX]);
  entry.CarName.push(file[i][CARNAME_INDEX]);
  entry.LastName = file[i][LASTNAME_INDEX];
  ...
}

// and now to convert this into an array
let array = Object.keys(results).map(key => results[key]);

// retrieves or creates an entry for a given primary key
function getEntry(results, id) {
  return results[id] || (results[id] = {});
}

You could also get fancier and dynamically determine what the column indexes are, but the way I have it just keeps things simple.


问:
Third parameter of np.r_? (numpy)
I'm looking over the docs and I still can't figure out how the third parameter operates.

```<code> np.r_['0,2,0', [1,2,3], [4,5,6]]
</code>```

output:

```<code>array([[1],
       [2],
       [3],
       [4],
       [5],
</code>```

2)

```<code>np.r_['1,2,0', [1,2,3], [4,5,6]]
</code>```

output:

```<code>array([[1, 4],
       [2, 5],
       [3, 6]])
</code>```

The first parameter is the axis, second is the number of dimensions and third according to the docs means " which axis should contain the start of the arrays which are less than the specified number of dimensions"

Here are the docs:

https://docs.scipy.org/doc/numpy/reference/generated/numpy.r_.html

Thank you.

答:
Maybe a simple example can clear things up:

```<code>b=np.arange(3)
np.r_['0,2,0', b, b]
# array([[0],
#        [1],
#        [2],
#        [0],
#        [1],
#        [2]])
np.r_['0,2,1', b, b]
# array([[0, 1, 2],
#        [0, 1, 2]])
</code>```

We are concatenating b a 1d array with itself. The second number specifies that it should be made 2d before it gets stacked on itself as specified by the first number. Now there are two ways to make a shape (3,) array 2d: either make it (3, 1) (first example) or make it (1, 3) (second example). The third number specifies where the first original dimension (i.e. 3) goes in the 2d array.

Title: Third parameter of np.r_? (numpy)

Body:
I'm looking over the docs and I still can't figure out how the third parameter operates.

 np.r_['0,2,0', [1,2,3], [4,5,6]]

output:

array([[1],
       [2],
       [3],
       [4],
       [5],

2)

np.r_['1,2,0', [1,2,3], [4,5,6]]

output:

array([[1, 4],
       [2, 5],
       [3, 6]])

The first parameter is the axis, second is the number of dimensions and third according to the docs means " which axis should contain the start of the arrays which are less than the specified number of dimensions"

Here are the docs:

https://docs.scipy.org/doc/numpy/reference/generated/numpy.r_.html

Thank you.

Body:
Maybe a simple example can clear things up:

b=np.arange(3)
np.r_['0,2,0', b, b]
# array([[0],
#        [1],
#        [2],
#        [0],
#        [1],
#        [2]])
np.r_['0,2,1', b, b]
# array([[0, 1, 2],
#        [0, 1, 2]])

We are concatenating b a 1d array with itself. The second number specifies that it should be made 2d before it gets stacked on itself as specified by the first number. Now there are two ways to make a shape (3,) array 2d: either make it (3, 1) (first example) or make it (1, 3) (second example). The third number specifies where the first original dimension (i.e. 3) goes in the 2d array.


问:
DataTables get field headers based on input json object
I'm trying to create a DataTables object from a json object (following this example).  I can assume the input is an array of objects, each with the same set of keys.

I want to create a table that gets its column headers dynamically from the first row of the input.

See my js function below

```<code> function populateDataTable(json_obj) {
/*extract fields from ajax return*/
var columns_obj = [];
for (var key in json_obj[0]) {
  columns_obj.push({
    'data': key
  })
}
console.log(columns_obj);

/*draw html table container*/
var html_table = '<table id="example" class="display" width="100%" cellspacing="0"><thead><tr>';
for (var i = 0; i < columns_obj.length; i++) {
  html_table += '<th>' + columns_obj[i]['data'] + '</th>';
}
html_table += '<tr></thead></table>';
console.log(html_table);
$('#query_output').html(html_table);
console.log('columns_obj:', columns_obj.length, 'ajax data length:', Object.keys(json_obj[0]).length);
console.log($('#query_output th').length);
alert('pause');
$('#query_output table').DataTable({
  data: json_obj,
  columns: columns_obj
});
</code>```

}

In my fiddle here, contrary to my expectation the data is assigned entirely to a single field header 'name'.  Be warned that running this messes with the sandboxing of the fiddle.

JS Fiddle

答:
I let data tables do a little more work than you and came up with this:

http://jsbin.com/zeminu/edit?html,js,console,output

```<code>    $(function () {

        /* user  run query click event*/
        $('#run_query').click(function () {
            populateDataTable(sample_ajax);
        });

        function populateDataTable(json_obj) {
            console.log(json_obj)
            /*extract fields from ajax return*/
            var keys = Object.keys(json_obj[0]);
            var columns_obj = [];
            $.each(keys, function (i, it) {
                columns_obj[i] = { data: it, title: it };
            });

            /*draw html table container*/
            var html_table = '<table id="example" class="display" width="100%" cellspacing="0"><thead></thead><tbody></tbody></table>';

            $('#query_output').html(html_table);

            $('#query_output table').DataTable({
                data: json_obj,
                columns: columns_obj
            });
        }
    });
</code>```

Body:
I'm trying to create a DataTables object from a json object (following this example).  I can assume the input is an array of objects, each with the same set of keys.

I want to create a table that gets its column headers dynamically from the first row of the input.

See my js function below

 function populateDataTable(json_obj) {
/*extract fields from ajax return*/
var columns_obj = [];
for (var key in json_obj[0]) {
  columns_obj.push({
    'data': key
  })
}
console.log(columns_obj);

/*draw html table container*/
var html_table = '

';
for (var i = 0; i < columns_obj.length; i++) {
  html_table += '' + columns_obj[i]['data'] + '	';
}
html_table += '

';
console.log(html_table);
$('#query_output').html(html_table);
console.log('columns_obj:', columns_obj.length, 'ajax data length:', Object.keys(json_obj[0]).length);
console.log($('#query_output th').length);
alert('pause');
$('#query_output table').DataTable({
  data: json_obj,
  columns: columns_obj
});

}

In my fiddle here, contrary to my expectation the data is assigned entirely to a single field header 'name'.  Be warned that running this messes with the sandboxing of the fiddle.

JS Fiddle

Body:
I let data tables do a little more work than you and came up with this:

http://jsbin.com/zeminu/edit?html,js,console,output

    $(function () {

        /* user  run query click event*/
        $('#run_query').click(function () {
            populateDataTable(sample_ajax);
        });

        function populateDataTable(json_obj) {
            console.log(json_obj)
            /*extract fields from ajax return*/
            var keys = Object.keys(json_obj[0]);
            var columns_obj = [];
            $.each(keys, function (i, it) {
                columns_obj[i] = { data: it, title: it };
            });

            /*draw html table container*/
            var html_table = '<table id="example" class="display" width="100%" cellspacing="0"><thead></thead><tbody></tbody></table>';

            $('#query_output').html(html_table);

            $('#query_output table').DataTable({
                data: json_obj,
                columns: columns_obj
            });
        }
    });


问:
Get the result from the Query
I write this code :

```<code>Var Q : TFDQuery;
begin
Q := TFDQuery.Create(Self);
Q.Connection := FDConnection1;
Q.Params.CreateParam(ftString,'N',ptOutput);// Try also ptResult
Q.Params.CreateParam(ftInteger,'ID',ptInput);
Q.SQL.Text := 'SELECT NOM FROM EMPLOYEE WHERE ID_EMP = :ID';
Q.Params.ParamByName('ID').Value := 1;
Q.Active := True;
ShowMessage( VarToStr(Q.Params.ParamByName('N').Value) );
</code>```

The result should be the name of the employer.

I get an error :

'N' parameter not found

How can I get the result from the Query using the parameter?

If I can't , what is the the function of :

ptOutput

ptResult

答:
There is no need to manually create parameters. Data access components are smart enough to parse the SQL string and populate the parameters collection by themselves

Also to get the result you must read the query's fields. When you call Open on a Query component, the fields collection will be populated with the fields that you specified in the SELECT [fields] SQL statement

As a side note, I advice that you use the type-safe version to get the value from a TField or TParameter object: See more here

```<code>var
  q : TFDQuery;
begin
  q := TFDQuery.Create(Self);
  q.Connection := FDConnection1;
  q.SQL.Text := 'SELECT NOM FROM EMPLOYEE WHERE ID_EMP = :ID';
  q.ParamByName('ID').AsInteger := 1;
  q.Open;
  ShowMessage(q.FieldByName('Nom').AsString);
end;
</code>```

Title: Get the result from the Query

Body:
I write this code :

Var Q : TFDQuery;
begin
Q := TFDQuery.Create(Self);
Q.Connection := FDConnection1;
Q.Params.CreateParam(ftString,'N',ptOutput);// Try also ptResult
Q.Params.CreateParam(ftInteger,'ID',ptInput);
Q.SQL.Text := 'SELECT NOM FROM EMPLOYEE WHERE ID_EMP = :ID';
Q.Params.ParamByName('ID').Value := 1;
Q.Active := True;
ShowMessage( VarToStr(Q.Params.ParamByName('N').Value) );

The result should be the name of the employer.

I get an error :

'N' parameter not found

How can I get the result from the Query using the parameter?

If I can't , what is the the function of :

ptOutput

ptResult

Body:
There is no need to manually create parameters. Data access components are smart enough to parse the SQL string and populate the parameters collection by themselves

Also to get the result you must read the query's fields. When you call Open on a Query component, the fields collection will be populated with the fields that you specified in the SELECT [fields] SQL statement

As a side note, I advice that you use the type-safe version to get the value from a TField or TParameter object: See more here

var
  q : TFDQuery;
begin
  q := TFDQuery.Create(Self);
  q.Connection := FDConnection1;
  q.SQL.Text := 'SELECT NOM FROM EMPLOYEE WHERE ID_EMP = :ID';
  q.ParamByName('ID').AsInteger := 1;
  q.Open;
  ShowMessage(q.FieldByName('Nom').AsString);
end;


问:
need PHP to save data sent as a GET to a file web send
I need to send unit ID from Arduino's to web using the form:

```<code>      http://somdomain.com/path/phpscript.php?ID=5
</code>```

the arduino code is a slam dunk but i need help with the PHP script to accept the server side data and to save the ID number only to a text file named id_file.txt for later parsing.

```<code>    there are 20 units and i need 1 ID number/line
</code>```

I'm lost to even the structure of the file.

Please Help if possible.

答:
Make Arduino Invoke a page like

```<code>http://somdomain.com/path/phpscript.php?ID=5
</code>```

Then the phpscript.php will look like this

```<code>    <?php
    //first line just checks to see if ID is set and if so it'll run the script. This stops the script from running if ID isn't set and someone just randomly comes to the webpage
    if (isset($_GET['ID'])) {

    $id = $_GET['ID'] . "\n"; //I added \n to denote a new line so when you write to this file it'll just append the ID's there
    $myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
    fwrite($myfile, $id); //the second parameter is whatever you want to write to that file
    fclose($myfile);
    }
</code>```

If you wanted to write a new line to the same file that should work

Body:
I need to send unit ID from Arduino's to web using the form:

      http://somdomain.com/path/phpscript.php?ID=5

the arduino code is a slam dunk but i need help with the PHP script to accept the server side data and to save the ID number only to a text file named id_file.txt for later parsing.

    there are 20 units and i need 1 ID number/line

I'm lost to even the structure of the file.

Please Help if possible.

Body:
Make Arduino Invoke a page like

http://somdomain.com/path/phpscript.php?ID=5

Then the phpscript.php will look like this

    <?php
    //first line just checks to see if ID is set and if so it'll run the script. This stops the script from running if ID isn't set and someone just randomly comes to the webpage
    if (isset($_GET['ID'])) {

    $id = $_GET['ID'] . "\n"; //I added \n to denote a new line so when you write to this file it'll just append the ID's there
    $myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
    fwrite($myfile, $id); //the second parameter is whatever you want to write to that file
    fclose($myfile);
    }

If you wanted to write a new line to the same file that should work


问:
Git rename from index.lock to index failed
Using the GitHub Windows client I did a sync to pull remote changes to my local machine, but before finishing the sync, I ran out of disk space and the sync failed.  Now I seem to have a bunch of local changes that are actually changes that were being pulled from origin.  I tried to run git pull but got:

```<code>C:\Users\Tom\SourceLog [master +4 ~26 -0 !]> git pull
Updating b3a86e1..5afd74f
error: Your local changes to the following files would be overwritten by merge:
        SourceLog.Interface/IChangedFile.cs
        SourceLog.Interface/ILogEntry.cs
        ...
Please, commit your changes or stash them before you can merge.
error: The following untracked working tree files would be overwritten by merge:
        Lib/MSBuildExtensionPack/4.0.6.0/Ionic.Zip.dll
        Lib/MSBuildExtensionPack/4.0.6.0/MSBuild.ExtensionPack.dll
        ...
Aborting
</code>```

So now I'm trying to discard the local changes but I'm getting:

```<code>C:\Users\Tom\SourceLog [master +4 ~26 -0 !]> git checkout -- .
Rename from '.git/index.lock' to '.git/index' failed. Should I try again? (y/n) y
Rename from '.git/index.lock' to '.git/index' failed. Should I try again? (y/n) n
fatal: unable to write new index file
</code>```

How can I clean this up?  (I didn't have any local changes before starting the sync.)

Update

Can't seem to reset head..

```<code>C:\Users\Tom\SourceLog [master +4 ~0 -0 !]> git reset head
Rename from '.git/index.lock' to '.git/index' failed. Should I try again? (y/n) y
Rename from '.git/index.lock' to '.git/index' failed. Should I try again? (y/n) n
error: Could not write new index file.
fatal: Could not reset index file to revision 'head'.
</code>```

答:
In my case, this was caused by using the same Git repo from both admin and non-admin command prompts. When last git pull was from admin cmd, the index was created by it, and then non-admin cmd had insufficient permissions to modify it.

My solution was re-creating the index (while keeping the worktree intact):

```<code>del .git\index
del .git\index.lock
git reset --mixed head
</code>```

Body:
Using the GitHub Windows client I did a sync to pull remote changes to my local machine, but before finishing the sync, I ran out of disk space and the sync failed.  Now I seem to have a bunch of local changes that are actually changes that were being pulled from origin.  I tried to run git pull but got:

C:\Users\Tom\SourceLog [master +4 ~26 -0 !]> git pull
Updating b3a86e1..5afd74f
error: Your local changes to the following files would be overwritten by merge:
        SourceLog.Interface/IChangedFile.cs
        SourceLog.Interface/ILogEntry.cs
        ...
Please, commit your changes or stash them before you can merge.
error: The following untracked working tree files would be overwritten by merge:
        Lib/MSBuildExtensionPack/4.0.6.0/Ionic.Zip.dll
        Lib/MSBuildExtensionPack/4.0.6.0/MSBuild.ExtensionPack.dll
        ...
Aborting

So now I'm trying to discard the local changes but I'm getting:

C:\Users\Tom\SourceLog [master +4 ~26 -0 !]> git checkout -- .
Rename from '.git/index.lock' to '.git/index' failed. Should I try again? (y/n) y
Rename from '.git/index.lock' to '.git/index' failed. Should I try again? (y/n) n
fatal: unable to write new index file

How can I clean this up?  (I didn't have any local changes before starting the sync.)

Update

Can't seem to reset head..

C:\Users\Tom\SourceLog [master +4 ~0 -0 !]> git reset head
Rename from '.git/index.lock' to '.git/index' failed. Should I try again? (y/n) y
Rename from '.git/index.lock' to '.git/index' failed. Should I try again? (y/n) n
error: Could not write new index file.
fatal: Could not reset index file to revision 'head'.

Body:
In my case, this was caused by using the same Git repo from both admin and non-admin command prompts. When last git pull was from admin cmd, the index was created by it, and then non-admin cmd had insufficient permissions to modify it.

My solution was re-creating the index (while keeping the worktree intact):

del .git\index
del .git\index.lock
git reset --mixed head

ContentLicense: CC BY-SA 4.0


问:
Heroku Postgres Ruby Puma Workers & Threads
For a pure Rack app running on a Heroku hobby dyno with a Heroku Postgres hobby dev add-on, how do you know how many workers & threads to configure Puma to have?</p>

答:
Based on this article it seems like you'd be safe running 2-4 processes within a single Heroku web dyno depending on your memory usage. For threads, I'd stick to the default (5) depending on the needs of your app.

I'd recommend tuning your app to use a particular config then keeping an eye on the Heroku logs for a few days to see if you get too many R14 errors. At that point, you know you've exhausted the dyno and should scale it back.


问:
html a click event use jquery
hi every I writed a line like this:

```<code><a href="#">delete</a>
</code>```

I want do some in js function when click this,so I use jQuery, and like this

```<code>$('a[href='#']').click(function(){
  alert("test");
  return false;
});
</code>```

I use this to test, but it do best in Firefox, but can't work in IE, why? I could not find the error, could you help me thank you

答:
I do it follow your advices,but it also didn't work in IE,so I changed the way,I use the span for href ,like this
test
and change the css for span,to made it had the style of href
Aslo think you very much</p>

Title: html a click event use jquery

Body:
hi every I writed a line like this:

delete

I want do some in js function when click this,so I use jQuery, and like this

$('a[href='#']').click(function(){
  alert("test");
  return false;
});

I use this to test, but it do best in Firefox, but can't work in IE, why? I could not find the error, could you help me thank you


问:
Pass MySQL row data to bootstrap modal
Ok what I have is a MySQL Database and I am using PHP to output it to my browser in an HTML Table. Each row has an edit button, and I have been able to pass one mysql value (lead_id) to the modal, but cannot figure out how to get the rest of the data and be able to CRUD inside the modal. I have read a lot of different articles and forums about this and they all appear to use some form of .ajax in the jQuery. I have tried all of these jQuery functions but have been unsuccessful. Maybe the don't work with 3.1.1? IDK.

If someone could help me out with the .ajax call and the jquery part it seems to be my biggest struggle. I also am okay with php, but I am not sure what the php file would look like for the .ajax call.

Below is my code.

```<code><?php
/* mysql connect info */
$mysqlhost = '';
$mysqlusername = '';
$mysqlpassword = '';
$mysqldb = '';
?>

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Website | Login</title>
<link href="css/bootstrap.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">

<?php
$mysqli = new mysqli($mysqlhost, $mysqlusername, $mysqlpassword, $mysqldb);

if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$sql="SELECT * FROM leads";
$result=mysqli_query($mysqli,$sql);

// Associative array
$row=mysqli_fetch_assoc($result);
?>

<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container-fluid">
<div class="navbar-header">
  <h1>
    <a class="navbar-brand" href="#">
    <span class="glyphicon glyphicon-th-list" aria-hidden="true">
    </a>
  </h1>
 </div>
 </div>
 </nav>

 <header id="header">
 <div class="container-fluid">
 <div class="row">
 <div class="col-md-12">
 </div>
 </div>
 </div>
 </header>

 <!-- Beginning of Sections -->
 <section id="main">
 <div class="container-fluid">
 <div class="row">
 <div class="col-md-12">
 <div class="container">

 <table class="table table-striped">
 <thead>
  <tr>
    <!--<th>Lead Number</th>-->
    <th>First Name</th>
    <th>Last Name</th>
    <th>Moving Date</th>
    <th>eMail</th>
    <th>Phone</th>
    <th>From</th>
    <th>To</th>
    <th>Moving Size</th>
    <!--<th>IP Address</th>-->
    <!--<th>Source</th>-->
    <th>Submission Time</th>
    <th>Actions</th>
   </tr>
  </thead>
  <tbody>

 <?php
 while($row=mysqli_fetch_assoc($result))
 {
 echo "<tr>";
 /*echo "<td>" . $row["lead_id"] ."<td>";*/
 echo "<td>" . $row["customer_first_name"] ."</td>";
 echo "<td>" . $row["customer_last_name"] ."</td>";
 echo "<td>" . $row["moving_date"] ."</td>";
 echo "<td>" . $row["customer_email"] ."</td>";
 echo "<td>" . $row["customer_phone"] ."</td>";
 echo "<td>" . $row["customer_from_zip"] ."</td>";
 echo "<td>" . $row["customer_to_zip"] ."</td>";
 echo "<td>" . $row["customer_moving_size"] ."</td>";
 /*echo "<td>" . $row["customer_ip_address"] ."<td>";*/
 /*echo "<td>" . $row["lead_handle"] ."</td>";*/
 echo "<td>" . $row["sent_date"] ."</td>";
 echo "<td> <button type=\"button\" class=\"btn btn-primary btn-sm\" data-toggle=\"modal\" data-target=\"#myModal\" data-id=\"". $row["lead_id"] ."\" id=\"". $row["lead_id"] ."\">Edit</button></td>";
 echo "</tr>";
 }
 echo "</tbody>";
 echo "</table>";

 ?>

</div>
</div>
</div>
</div>

</section>

</div>

  <!-- Bootstrap core JavaScript
  ================================================== -->
  <!-- Placed at the end of the document so the pages load faster -->
  <!-- this is google jquery library-->

  <script src="js/jquery-3.1.1.js"></script>
  <script src="js/bootstrap.js"></script>
  <script src="js/my.js"></script>
  <!-- This is the functionality of the login screen -->

  <!-- at one point the drop down was not working because we did not include the bootstrap.js which much come after the initial include to the jquery library-->

<!-- MODAL BEGIND -->

<div class="modal fade" id="myModal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
  <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-  label="Close"><span aria-hidden="true">×</span></button>
    <h4 class="modal-title">Modal title</h4>
  </div>
  <div class="modal-body" id="thebody">
    <p>One fine body…</p>
  </div>
  <div class="modal-footer">
    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
    <button type="button" class="btn btn-primary">Save changes</button>
  </div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
</code>```

This is where I feel my problem is:

```<code> $('#myModal').on('show.bs.modal', function (event) {
  var button = $(event.relatedTarget);
  var id = button.data('id');
  var modal = $(this)
  $.ajax({
      type: "POST",
      url: "selecta.php",
      data: {id:id},
      success: function(data){
        $('.modal-body').html();
        $('#myModal').modal("show");// this triggers y
  modal.find('.modal-title').text('Lead Number ' + id)
  modal.find('.modal-body input').val(id)

})
})
})

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

This is the result I get when the jQuery $.ajax function is run
For some reason the lead number does not pass to the modal

Now when I comment out the jQuery, the modal does load with the lead number like this picture shows.
enter image description here

```<code> $('#myModal').on('show.bs.modal', function (event) {
  var button = $(event.relatedTarget);
  var id = button.data('id');
  var modal = $(this);
  /*$.ajax({
      type: "POST",
      url: "selecta.php",
      data: {id:id},
      success: function(data){
        $('.modal-body').html();
        $('#myModal').modal("show");// this triggers y*/
  modal.find('.modal-title').text('Lead Number ' + id)
  modal.find('.modal-body input').val(id)

})
</code>```

答:
I cannot see any issue except that you have missed ";" at end of    </p>

```<code>var modal = $(this)
modal.find('.modal-title').text('Lead Number ' + id)
  modal.find('.modal-body input').val(id)
</code>```

<p>...and some closing brackets. Are you getting any error? You can share screenshots or results.</p>

Title: Pass MySQL row data to bootstrap modal

Body:
Ok what I have is a MySQL Database and I am using PHP to output it to my browser in an HTML Table. Each row has an edit button, and I have been able to pass one mysql value (lead_id) to the modal, but cannot figure out how to get the rest of the data and be able to CRUD inside the modal. I have read a lot of different articles and forums about this and they all appear to use some form of .ajax in the jQuery. I have tried all of these jQuery functions but have been unsuccessful. Maybe the don't work with 3.1.1? IDK.

If someone could help me out with the .ajax call and the jquery part it seems to be my biggest struggle. I also am okay with php, but I am not sure what the php file would look like for the .ajax call.

Below is my code.

<?php
/* mysql connect info */
$mysqlhost = '';
$mysqlusername = '';
$mysqlpassword = '';
$mysqldb = '';
?>

<!DOCTYPE html>

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Website | Login</title>
<link href="css/bootstrap.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">

<?php
$mysqli = new mysqli($mysqlhost, $mysqlusername, $mysqlpassword, $mysqldb);

if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$sql="SELECT * FROM leads";
$result=mysqli_query($mysqli,$sql);

// Associative array
$row=mysqli_fetch_assoc($result);
?>

    First Name
    Last Name
    Moving Date
    eMail
    Phone
    From
    To
    Moving Size

    Submission Time
    Actions

 <?php
 while($row=mysqli_fetch_assoc($result))
 {
 echo "
";
 /*echo "" . $row["lead_id"] ."";*/
 echo "" . $row["customer_first_name"] ."	";
 echo "" . $row["customer_last_name"] ."	";
 echo "" . $row["moving_date"] ."	";
 echo "" . $row["customer_email"] ."	";
 echo "" . $row["customer_phone"] ."	";
 echo "" . $row["customer_from_zip"] ."	";
 echo "" . $row["customer_to_zip"] ."	";
 echo "" . $row["customer_moving_size"] ."	";
 /*echo "" . $row["customer_ip_address"] ."";*/
 /*echo "" . $row["lead_handle"] ."	";*/
 echo "" . $row["sent_date"] ."	";
 echo " <button type=\"button\" class=\"btn btn-primary btn-sm\" data-toggle=\"modal\" data-target=\"#myModal\" data-id=\"". $row["lead_id"] ."\" id=\"". $row["lead_id"] ."\">Edit</button>	";
 echo "
";
 }
 echo "
";
 echo "
";

 ?>

    <button type="button" class="close" data-dismiss="modal" aria-  label="Close">×</button>

Modal title

One fine body…

    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
    <button type="button" class="btn btn-primary">Save changes</button>

This is where I feel my problem is:

 $('#myModal').on('show.bs.modal', function (event) {
  var button = $(event.relatedTarget);
  var id = button.data('id');
  var modal = $(this)
  $.ajax({
      type: "POST",
      url: "selecta.php",
      data: {id:id},
      success: function(data){
        $('.modal-body').html();
        $('#myModal').modal("show");// this triggers y
  modal.find('.modal-title').text('Lead Number ' + id)
  modal.find('.modal-body input').val(id)

})
})
})

</script>

This is the result I get when the jQuery $.ajax function is run
For some reason the lead number does not pass to the modal

Now when I comment out the jQuery, the modal does load with the lead number like this picture shows.
enter image description here

 $('#myModal').on('show.bs.modal', function (event) {
  var button = $(event.relatedTarget);
  var id = button.data('id');
  var modal = $(this);
  /*$.ajax({
      type: "POST",
      url: "selecta.php",
      data: {id:id},
      success: function(data){
        $('.modal-body').html();
        $('#myModal').modal("show");// this triggers y*/
  modal.find('.modal-title').text('Lead Number ' + id)
  modal.find('.modal-body input').val(id)

})

Body:
I cannot see any issue except that you have missed ";" at end of

var modal = $(this)
modal.find('.modal-title').text('Lead Number ' + id)
  modal.find('.modal-body input').val(id)

...and some closing brackets. Are you getting any error? You can share screenshots or results.


问:
How to fix RED kibana status
Here is the cluster status</p>

```<code>Status Breakdown
ID  Status
ui settings     Elasticsearch plugin is red
plugin:kibana@5.2.2     Ready
plugin:elasticsearch@5.2.2  This version of Kibana requires Elasticsearch v5.2.2 on all nodes. I found the following incompatible nodes in your cluster: v5.1.1 @ 127.0.0.1:9200 (127.0.0.1)
plugin:console@5.2.2    Ready
plugin:timelion@5.2.2   Ready *emphasized text*
</code>```

答:
Install or update elasticsearch.

RedHat/Centos :
try yum update then yum upgrade

Debian/Ubuntu :
try apt-get remove elasticsearch and apt-get install elasticsearch

Reference :

https://www.elastic.co/guide/en/kibana/current/install.html

https://www.elastic.co/guide/en/elasticsearch/reference/current/rolling-upgrades.html

Title: How to fix RED kibana status

Body:
Here is the cluster status

Status Breakdown
ID  Status
ui settings     Elasticsearch plugin is red
plugin:kibana@5.2.2     Ready
plugin:elasticsearch@5.2.2  This version of Kibana requires Elasticsearch v5.2.2 on all nodes. I found the following incompatible nodes in your cluster: v5.1.1 @ 127.0.0.1:9200 (127.0.0.1)
plugin:console@5.2.2    Ready
plugin:timelion@5.2.2   Ready *emphasized text*


答:
You can use the following code to write to a file.

```<code>$filename='myfilename.txt';
if(isset($_GET['ID'])){
   $id= $_GET['ID'];
   if(is_numeric($id)){
      if(file_put_contents($filename,$id,FILE_APPEND)!== FALSE){
          echo "id successfully saved";
      }else{
          echo "there is a error saving your id";
      }
   }
}
</code>```

later  you can read from the file..

```<code> $filearray = file($filename,FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
 foreach($filearray as $id){
  echo $id;// this print the id's
 }
</code>```

Title: need PHP to save data sent as a GET to a file web send

Body:
You can use the following code to write to a file.

$filename='myfilename.txt';
if(isset($_GET['ID'])){
   $id= $_GET['ID'];
   if(is_numeric($id)){
      if(file_put_contents($filename,$id,FILE_APPEND)!== FALSE){
          echo "id successfully saved";
      }else{
          echo "there is a error saving your id";
      }
   }
}

later  you can read from the file..

 $filearray = file($filename,FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
 foreach($filearray as $id){
  echo $id;// this print the id's
 }


问:
Node.js encode ISO8859-1 to UTF-8
I have an application that allows users to persist strings to a database and those strings may contain emojis. The problem I have is an emoji such as  will get stored in MySQL as ðŸ˜Š

When I retrieve this string using a PHP MySQL client and render it in a web browser, it renders fine probably because the Content-Type is set to UTF-8. When I try to read the string in node.js, I get back what I think is the ISO8859-1 encoding a literal ðŸ˜Š. The charset on the table is set to latin1 and that's where I'm getting ISO8859-1 from.

What's the right way to encode the string in node.js so that I can see the emoji and not the encoding set by MySQL when I console.log the string?

答:
I have found a super dirty way to convert it back:

    const isoToUtfTable = {
      'ð': 0xf0,
      'Ÿ': 0x9f,
      '˜': 0x98,
      'Š': 0x8a
    };

    function convertISO8859ToUtf8(s) {
      const buf = new Uint8Array([...s].map(c => isoToUtfTable[c]));
      return String.fromCharCode(...buf)
    }

    function decode_utf8(s) {
      return decodeURIComponent(escape(s));
    }

    console.log(decode_utf8(convertISO8859ToUtf8('ðŸ˜Š')))```

Now you simply need to complete the isoToUtfTable table (it's small, see https://en.wikipedia.org/wiki/ISO/IEC_8859-1).

Title: Node.js encode ISO8859-1 to UTF-8

Body:
I have found a super dirty way to convert it back:

    const isoToUtfTable = {
      'ð': 0xf0,
      'Ÿ': 0x9f,
      '˜': 0x98,
      'Š': 0x8a
    };

    function convertISO8859ToUtf8(s) {
      const buf = new Uint8Array([...s].map(c => isoToUtfTable[c]));
      return String.fromCharCode(...buf)
    }

    function decode_utf8(s) {
      return decodeURIComponent(escape(s));
    }

    console.log(decode_utf8(convertISO8859ToUtf8('ðŸ˜Š')))

Now you simply need to complete the isoToUtfTable table (it's small, see https://en.wikipedia.org/wiki/ISO/IEC_8859-1).


问:
Generate unique sequence number across threads
I need to generate a unique sequence number from multiple threads.  I created the simple class below and it seems to work, but I'm not certain if I can rely on the sequence number being unique.

In addition, I need to be able to have the number go back to 0 if it exceeds 999999.  I don't expect it to roll over for a very long time as the method will likely be called less than 100 times per day.  I know that the system will be shut down periodically for maintenance before it has a chance to reach 999999.

The GetSequenceNumber method will be called from an xslt transformation in a BizTalk map and the method could be called more than once at the same time (within the same BizTalk host instance).

On my dev system, it seems to work correctly and generates different values even if BizTalk is calling the method more than once at the same time.  The dev system only has a single BizTalk host instance running.

On the production system, however, there are two servers.  Am I right in thinking that this method cannot guarantee uniqueness across servers since they are running in different App Domains?

I can't use a guid because the sequence number is limited to 16 characters.

```<code>public class HelperMethods
{
    private static int sequenceNumber = 0;

    public string GetSequenceNumber()
    {
        string result = null;

        int seqNo = Interlocked.Increment(ref sequenceNumber);

        result = string.Format("{0:MMddHHmmss}{1:000000}", DateTime.Now, seqNo);

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

I thought that I might be able to use the servers computer name and prepend some arbitrary character so that even if the sequence number generated on one server was the same as the other, it would still be different, but I'm not sure how unique it would be.  Something like this:

```<code>    string seqNumber = (MachineName == "Blah" ? "A" : "B") + GetSequenceNumber();
</code>```

Does anyone have any suggestions as to how I can create a unique sequence number?  It doesn't have to be perfectly unique, I just need collisions to be very unlikely.  Also, how can I reset the number back to 0 if it reaches 1000000 in a thread safe way?

答:
You'll have several problems here.

BizTalk Pipelines and Orchestrations run in separate AppDomains, and the Orchestration AppDomain gets torn down sometimes between hydrations of your orchestration.  Even if, for right now, this map only ever runs in an orchestration xor a pipeline, at some point someone may put it on another one (or on another host instance), and your solution goes boom.  And forget about it when you start running anything in a multi-server environment.

The bottom line on BizTalk maps is that they shouldn't typically be indeterminate in any way that uses external resources.  If you just want to generate a GUID (which is indeterminate), that's ok.  If you want to generate a sequence across multiple mappings, that's not a good idea.  You'll have to rely on some external system, (it really should be external even to the BizTalk appdomain you're running in to really work properly - such as a singleton WCF service or using a SQL Server SEQUENCE) and that's generally a bad idea in a map (especially a map that's going to execute in parallel on multiple systems).

So what can you do?

Pick a different way of identifying your debatched messages.  Perhaps a Batch ID and an individual ID - and perhaps both GUID (or at least something derived from a GUID that's still good-enough for uniqueness).

Sequence your messages before batching or on the way out, through an Ordered Delivery port or a singleton orchestration (effectively a singleton queue).  This has some obvious disadvantages, but you can get a little creative with it - map your entire batch first to sequence it, then debatch; or rework your debatch process to construct a sequence in the message as it debatches; or throw everything into a SQL (2012+) table with a SEQUENCE that loops around per your requirement and pull it back out with your sequence.

Rethink your requirement.  What's the end system requesting this?  Why are you thinking you need to do it in a map?

Body:
I need to generate a unique sequence number from multiple threads.  I created the simple class below and it seems to work, but I'm not certain if I can rely on the sequence number being unique.

In addition, I need to be able to have the number go back to 0 if it exceeds 999999.  I don't expect it to roll over for a very long time as the method will likely be called less than 100 times per day.  I know that the system will be shut down periodically for maintenance before it has a chance to reach 999999.

The GetSequenceNumber method will be called from an xslt transformation in a BizTalk map and the method could be called more than once at the same time (within the same BizTalk host instance).

On my dev system, it seems to work correctly and generates different values even if BizTalk is calling the method more than once at the same time.  The dev system only has a single BizTalk host instance running.

On the production system, however, there are two servers.  Am I right in thinking that this method cannot guarantee uniqueness across servers since they are running in different App Domains?

I can't use a guid because the sequence number is limited to 16 characters.

public class HelperMethods
{
    private static int sequenceNumber = 0;

    public string GetSequenceNumber()
    {
        string result = null;

        int seqNo = Interlocked.Increment(ref sequenceNumber);

        result = string.Format("{0:MMddHHmmss}{1:000000}", DateTime.Now, seqNo);

        return result;
    }
}

I thought that I might be able to use the servers computer name and prepend some arbitrary character so that even if the sequence number generated on one server was the same as the other, it would still be different, but I'm not sure how unique it would be.  Something like this:

    string seqNumber = (MachineName == "Blah" ? "A" : "B") + GetSequenceNumber();

Does anyone have any suggestions as to how I can create a unique sequence number?  It doesn't have to be perfectly unique, I just need collisions to be very unlikely.  Also, how can I reset the number back to 0 if it reaches 1000000 in a thread safe way?


问:
Configuration.resolve has an unknown property 'root'
I get the following error :

Invalid configuration object. Webpack has been initialised using a
  configuration object that does not match the API schema.
   - configuration.resolve has an unknown property 'root'. These properties are valid:    object { alias?, aliasFields?,
  cachePredicate?, descriptionFiles?, enforceExtension?,
  enforceModuleExtension?, extensions?, fileSystem?, mainFields?,
  mainFiles?, moduleExtensions?, modules?, plugins?, resolver?,
  symlinks?, unsafeCache?, useSyncFileSystemCalls? }

I use webpack 2.3.2.

My webpack.config.js looks like this :

```<code>module.exports= {
  entry:'./public/app.jsx',
  output: {
    path: __dirname,
    filename:'./public/bundle.js'
  },
  resolve: {
    root: __dirname,
    alias:{
      Mod1: 'public/components/mod1.jsx',
      Mod2:'public/components/mod2.jsx',
      Mod3: 'public/components/mod3.jsx'
    },
    extensions: ['*','.js','.jsx']
  },
  module :{
    loaders:[{
      loader :'babel-loader',
      query :{
        presets:['react','es2015','es2017']
      },
      test:/\.jsx?$/,
      exclude:/(node_modules|bower_components)/
    }]
  }
};
</code>```

答:
Have you tried removing LINE 8? Does it through any errors?

As you've probably guessed it is throwing an error as you are trying to set a property which isn't valid.

There is a chance that the instructions you may have followed when configuring webpack is outdated.

Give it a go without LINE 8 and let me know if the problems persist and we can fix it together.

Body:
I get the following error :

Invalid configuration object. Webpack has been initialised using a
  configuration object that does not match the API schema.
   - configuration.resolve has an unknown property 'root'. These properties are valid:    object { alias?, aliasFields?,
  cachePredicate?, descriptionFiles?, enforceExtension?,
  enforceModuleExtension?, extensions?, fileSystem?, mainFields?,
  mainFiles?, moduleExtensions?, modules?, plugins?, resolver?,
  symlinks?, unsafeCache?, useSyncFileSystemCalls? }

I use webpack 2.3.2.

My webpack.config.js looks like this :

module.exports= {
  entry:'./public/app.jsx',
  output: {
    path: __dirname,
    filename:'./public/bundle.js'
  },
  resolve: {
    root: __dirname,
    alias:{
      Mod1: 'public/components/mod1.jsx',
      Mod2:'public/components/mod2.jsx',
      Mod3: 'public/components/mod3.jsx'
    },
    extensions: ['*','.js','.jsx']
  },
  module :{
    loaders:[{
      loader :'babel-loader',
      query :{
        presets:['react','es2015','es2017']
      },
      test:/\.jsx?$/,
      exclude:/(node_modules|bower_components)/
    }]
  }
};


问:
Django template filter queryset
I'm new in django.
I has a django application where stores products categorized by 'X' and 'Y'.

views.py

```<code>...

class CartListView(ListView):

template_name = 'checkout/list.html'
context_object_name = 'product_list'

def get_queryset(self):
    return Product.objects.filter(category__slug='X') | Product.objects.filter(category__slug='Y')

def get_context_data(self, **kwargs):
    context = super(CartListView, self).get_context_data(**kwargs)
    context['minicurso'] = get_object_or_404(Category, slug='X')
    context['pacotes'] = get_object_or_404(Category, slug='Y')
    return context
...
</code>```

In my views.py I filter this products by your categories slug.

The problem is, I'm trying to render the products in category 'X' on top the page and the products in category 'Y' down with a text between them. How I can do this?

list.html

```<code>{% for category in product_list %}
    {{ category.name }}
{% endfor %}

<p>
    Any text
</p>

{% for category in product_list %}
    {{ category.name }}
{% endfor %}
</code>```

答:
First off, you should use IN operator over | when populating the filtered queryset:

```<code>def get_queryset(self):
    return Product.objects.filter(category__slug__in=["X", "Y"])
</code>```

Secondly, you can't filter queryset by any field in the template unless you write a custom template tag which does that. However, it defeats the purpose of separation of presentation code from data logic. Filtering models is data logic, and outputting HTML is presentation. Thus, you need to override get_context_data and pass each queryset into the context:

```<code>def get_context_data(self, **kwargs):
    context = super(CartListView, self).get_context_data(**kwargs)

    context['minicurso'] = get_object_or_404(Category, slug='X')
    context['pacotes'] = get_object_or_404(Category, slug='Y')

    context["x_product_list"] = self.get_queryset().filter(category=context['minicurso'])
    context["y_product_list"] = self.get_queryset().filter(category=context['pacotes'])

    return context
</code>```

Then you can use them in the template:

```<code>{% for category in x_product_list %}
  {{ category.name }}
{% endfor %}

...

{% for category in y_product_list %}
  {{ category.name }}
{% endfor %}
</code>```

Title: Django template filter queryset

Body:
I'm new in django.
I has a django application where stores products categorized by 'X' and 'Y'.

views.py

...

class CartListView(ListView):

template_name = 'checkout/list.html'
context_object_name = 'product_list'

def get_queryset(self):
    return Product.objects.filter(category__slug='X') | Product.objects.filter(category__slug='Y')

def get_context_data(self, **kwargs):
    context = super(CartListView, self).get_context_data(**kwargs)
    context['minicurso'] = get_object_or_404(Category, slug='X')
    context['pacotes'] = get_object_or_404(Category, slug='Y')
    return context
...

In my views.py I filter this products by your categories slug.

The problem is, I'm trying to render the products in category 'X' on top the page and the products in category 'Y' down with a text between them. How I can do this?

list.html

{% for category in product_list %}
    {{ category.name }}
{% endfor %}

    Any text

{% for category in product_list %}
    {{ category.name }}
{% endfor %}

Body:
First off, you should use IN operator over | when populating the filtered queryset:

def get_queryset(self):
    return Product.objects.filter(category__slug__in=["X", "Y"])

Secondly, you can't filter queryset by any field in the template unless you write a custom template tag which does that. However, it defeats the purpose of separation of presentation code from data logic. Filtering models is data logic, and outputting HTML is presentation. Thus, you need to override get_context_data and pass each queryset into the context:

def get_context_data(self, **kwargs):
    context = super(CartListView, self).get_context_data(**kwargs)

    context['minicurso'] = get_object_or_404(Category, slug='X')
    context['pacotes'] = get_object_or_404(Category, slug='Y')

    context["x_product_list"] = self.get_queryset().filter(category=context['minicurso'])
    context["y_product_list"] = self.get_queryset().filter(category=context['pacotes'])

    return context

Then you can use them in the template:

{% for category in x_product_list %}
  {{ category.name }}
{% endfor %}

...

{% for category in y_product_list %}
  {{ category.name }}
{% endfor %}


问:
Unable to cast music to Chromecast
I'm trying to establish a simple audio stream to a Chromecast device. This is just a POC for me to familiarize myself with the API. What I want to do is load up the user's library, select a song, and have it cast over. I've been following the integration guide quite closely but to no avail.

Please find the full project on Github here.

An overview of my code, AppDelegate.m:

```<code>- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
{
    GCKCastOptions *options = [GCKCastOptions.alloc initWithReceiverApplicationID:kGCKMediaDefaultReceiverApplicationID];

    [GCKCastContext setSharedInstanceWithOptions:options];
    [GCKCastContext.sharedInstance.sessionManager addListener:self];
}
</code>```

UITableViewDelegate:

```<code>- (void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath
{
MPMediaItem *mediaItem = MusicManager.sharedManager[index];
    NSString *path = [MPMediaLibrary.defaultMediaLibrary pathForAssetURL:mediaItem.assetURL];

    GCKMediaMetadata *metadata = [GCKMediaMetadata.alloc initWithMetadataType:GCKMediaMetadataTypeMusicTrack];

    [metadata setString:mediaItem.title forKey:kGCKMetadataKeyTitle];
    [metadata setString:mediaItem.artist forKey:kGCKMetadataKeyArtist];
    [metadata setString:mediaItem.albumTitle forKey:kGCKMetadataKeyAlbumTitle];

    GCKMediaInformation *mediaInfo = [GCKMediaInformation.alloc initWithContentID:path
                                                                       streamType:GCKMediaStreamTypeBuffered
                                                                      contentType:[self fileMIMEType:path]
                                                                         metadata:metadata
                                                                   streamDuration:mediaItem.playbackDuration
                                                                       customData:nil];

    [GCKCastContext.sharedInstance.sessionManager.currentCastSession.remoteMediaClient loadMedia:mediaInfo autoplay:YES];
}
</code>```

I initiate the casting session by tapping the GCKCastButton and Start Session, my TV shows the Cast logo, then when I tap on a specific song, my TV briefly shows the metadata (i.e. song title, artist name, etc.), and then reverts back to the Chromecast logo. On the device, if I remain on the screen presented by GCKCastButton, I can also see the details of the song that is supposed to be currently casting, but quickly changes to "No Media Selected" after a few seconds.

I've checked the file path, the MIME type, everything is correct and playable. I've even tried bundling a short MP3 and trying to cast that, but to no avail.

Can't help but feel like I'm missing something here, the integration guide doesn't really give much more info.

Any insight is appreciated. Thanks!

答:
It seems that I was under the wrong impression that the cast library initiates a stream from the provided file itself. But instead it required an actual URL for the Chromecast device to perform a GET operation on.

I imagine this will be solved by running a server locally on the iOS device.

Title: Unable to cast music to Chromecast

Body:
I'm trying to establish a simple audio stream to a Chromecast device. This is just a POC for me to familiarize myself with the API. What I want to do is load up the user's library, select a song, and have it cast over. I've been following the integration guide quite closely but to no avail.

Please find the full project on Github here.

An overview of my code, AppDelegate.m:

- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
{
    GCKCastOptions *options = [GCKCastOptions.alloc initWithReceiverApplicationID:kGCKMediaDefaultReceiverApplicationID];

    [GCKCastContext setSharedInstanceWithOptions:options];
    [GCKCastContext.sharedInstance.sessionManager addListener:self];
}

UITableViewDelegate:

- (void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath
{
MPMediaItem *mediaItem = MusicManager.sharedManager[index];
    NSString *path = [MPMediaLibrary.defaultMediaLibrary pathForAssetURL:mediaItem.assetURL];

    GCKMediaMetadata *metadata = [GCKMediaMetadata.alloc initWithMetadataType:GCKMediaMetadataTypeMusicTrack];

    [metadata setString:mediaItem.title forKey:kGCKMetadataKeyTitle];
    [metadata setString:mediaItem.artist forKey:kGCKMetadataKeyArtist];
    [metadata setString:mediaItem.albumTitle forKey:kGCKMetadataKeyAlbumTitle];

    GCKMediaInformation *mediaInfo = [GCKMediaInformation.alloc initWithContentID:path
                                                                       streamType:GCKMediaStreamTypeBuffered
                                                                      contentType:[self fileMIMEType:path]
                                                                         metadata:metadata
                                                                   streamDuration:mediaItem.playbackDuration
                                                                       customData:nil];

    [GCKCastContext.sharedInstance.sessionManager.currentCastSession.remoteMediaClient loadMedia:mediaInfo autoplay:YES];
}

I initiate the casting session by tapping the GCKCastButton and Start Session, my TV shows the Cast logo, then when I tap on a specific song, my TV briefly shows the metadata (i.e. song title, artist name, etc.), and then reverts back to the Chromecast logo. On the device, if I remain on the screen presented by GCKCastButton, I can also see the details of the song that is supposed to be currently casting, but quickly changes to "No Media Selected" after a few seconds.

I've checked the file path, the MIME type, everything is correct and playable. I've even tried bundling a short MP3 and trying to cast that, but to no avail.

Can't help but feel like I'm missing something here, the integration guide doesn't really give much more info.

Any insight is appreciated. Thanks!


问:
Xamarin Forms listview out of memory error
In Xamarin Forms i have the following listview:

```<code><ListView x:Name="StudentView"  RowHeight="55"  SeparatorVisibility="None" CachingStrategy="RecycleElement">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <Grid>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="55"></RowDefinition>
                    </Grid.RowDefinitions>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="*"></ColumnDefinition>
                        <ColumnDefinition Width="*"></ColumnDefinition>
                    </Grid.ColumnDefinitions>

                    <Image Source="{Binding Image}" Grid.Row="0" Grid.Column="0" Aspect="AspectFill"></Image>
                    <Image Source="{Binding Image}" Grid.Row="0" Grid.Column="1" Aspect="AspectFill"></Image>
                </Grid>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>
</code>```

In the code behind i have declared an array of 1000 items.

The problem is that if i scroll up and down the listview, everytime i see in the xamarin profile that the memory usage increase and seems that CachingStrategy="RecycleElement" not work properly (tested on real android device).

After scroll some times, the program crash with out of memory.

What's the problem? How can i resolve it?

答:
1000 Image items are a lot! I bet this is Android, I suggest to use different solutions like:

1.- Pagging strategies (Load 10, the load another 10 and so).
2.- Reduce the images sizes.
3.- Use a cacheable image like:
https://github.com/luberda-molinet/FFImageLoading
4.- Implement a View custom renderer with a Recycler view.

And then the topic gets bigger and bigger on how you can improve your ListView performance, here are some useful links:

-https://developer.xamarin.com/guides/android/deployment,_testing,_and_metrics/performance/

-https://blog.xamarin.com/creating-highly-performant-smooth-scrolling-android-listviews/

-https://blog.xamarin.com/tips-for-creating-a-smooth-and-fluid-android-ui/

-http://kent-boogaart.com/blog/jason-smith's-xamarin-forms-performance-tips

Body:
In Xamarin Forms i have the following listview:

<ListView x:Name="StudentView"  RowHeight="55"  SeparatorVisibility="None" CachingStrategy="RecycleElement">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <Grid>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="55"></RowDefinition>
                    </Grid.RowDefinitions>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="*"></ColumnDefinition>
                        <ColumnDefinition Width="*"></ColumnDefinition>
                    </Grid.ColumnDefinitions>

                    <Image Source="{Binding Image}" Grid.Row="0" Grid.Column="0" Aspect="AspectFill"></Image>
                    <Image Source="{Binding Image}" Grid.Row="0" Grid.Column="1" Aspect="AspectFill"></Image>
                </Grid>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

In the code behind i have declared an array of 1000 items.

The problem is that if i scroll up and down the listview, everytime i see in the xamarin profile that the memory usage increase and seems that CachingStrategy="RecycleElement" not work properly (tested on real android device).

After scroll some times, the program crash with out of memory.

What's the problem? How can i resolve it?


问:
Retrieving data from array of array objects
In my application i am trying to return javascript object of employee who works in all projects. My array of data is like:

```<code>   var data = [
{
    projectName: "project1", projectId: 1,
    employees: [
        {fullName: "John Doe", employeeId: 1},
        {fullName: "Jane Smith", employeeId: 2}
    ]
},

{
    projectName: "project2", projectId: 2,
    employees: [
        {fullName: "John Doe", employeeId: 1},
        {fullName: "Mary Jones", employeeId: 3},
        {fullName: "Bill Evans", employeeId: 4}
    ]
}
</code>```

];

I need to search for employeeid 1 and return both projects. How do i search it.

答:
try to use Array.filter and Array.findIndex.

UPD:
since Array.findIndex is a new feature in ES6, maybe not supported by some browsers, but it has a polyfill for those unsupported browsers to use, see documentation here）.

```<code>function doFilter(arr) {
  return arr.filter(function(item) {
    return item.employees.findIndex(function(employee) {
      return employee.employeeId === 1;
    }) > -1;
 });
}
</code>```

this code snippet will return the target project array which contains the employee with an ID of 1.

var data = [{
    projectName: "project1",
    projectId: 1,
    employees: [{
        fullName: "John Doe",
        employeeId: 1
      },
      {
        fullName: "Jane Smith",
        employeeId: 2
      }
    ]
  },
  {
    projectName: "project2",
    projectId: 2,
    employees: [{
        fullName: "John Doe",
        employeeId: 1
      },
      {
        fullName: "Mary Jones",
        employeeId: 3
      },
      {
        fullName: "Bill Evans",
        employeeId: 4
      }
    ]
  },
  {
    projectName: "project3",
    projectId: 3,
    employees: [{
      fullName: "Jane Smith",
      employeeId: 2
    }]
  }
];

function doFilter(arr) {
  return arr.filter(function(item) {
    return item.employees.findIndex(function(employee) {
      return employee.employeeId === 1;
    }) > -1;
  });
}
console.log(doFilter(data));```

Body:
In my application i am trying to return javascript object of employee who works in all projects. My array of data is like:

   var data = [
{
    projectName: "project1", projectId: 1,
    employees: [
        {fullName: "John Doe", employeeId: 1},
        {fullName: "Jane Smith", employeeId: 2}
    ]
},

{
    projectName: "project2", projectId: 2,
    employees: [
        {fullName: "John Doe", employeeId: 1},
        {fullName: "Mary Jones", employeeId: 3},
        {fullName: "Bill Evans", employeeId: 4}
    ]
}

];

I need to search for employeeid 1 and return both projects. How do i search it.

Body:
try to use Array.filter and Array.findIndex.

UPD:
since Array.findIndex is a new feature in ES6, maybe not supported by some browsers, but it has a polyfill for those unsupported browsers to use, see documentation here）.

function doFilter(arr) {
  return arr.filter(function(item) {
    return item.employees.findIndex(function(employee) {
      return employee.employeeId === 1;
    }) > -1;
 });
}

this code snippet will return the target project array which contains the employee with an ID of 1.

var data = [{
    projectName: "project1",
    projectId: 1,
    employees: [{
        fullName: "John Doe",
        employeeId: 1
      },
      {
        fullName: "Jane Smith",
        employeeId: 2
      }
    ]
  },
  {
    projectName: "project2",
    projectId: 2,
    employees: [{
        fullName: "John Doe",
        employeeId: 1
      },
      {
        fullName: "Mary Jones",
        employeeId: 3
      },
      {
        fullName: "Bill Evans",
        employeeId: 4
      }
    ]
  },
  {
    projectName: "project3",
    projectId: 3,
    employees: [{
      fullName: "Jane Smith",
      employeeId: 2
    }]
  }
];

function doFilter(arr) {
  return arr.filter(function(item) {
    return item.employees.findIndex(function(employee) {
      return employee.employeeId === 1;
    }) > -1;
  });
}
console.log(doFilter(data));


问:
Suggestions for machine learning toolset without Matlab
I am new to the field of machine learning, I am planning to use python as the programing language for implementing algorithms and Java for system architecture.

As far as I understand, machine learning is more about modeling data specific to the domain, visualize the data, and choose appropriate models & parameters. Implementing the models/algorithms is the last and relatively easy step.

Matlab seems to have everything for machine learning but it is too expensive and requires to learn a new language.

What tools other than programming language do I need in general for machine learning for enterprise projects? things like data modeling, visualization,etc

答:
After a couple of years of trial and error, I would suggest you to go directly with python, possibly with scikit-learn or tensorflow (if you want to go hardcore :).

I also tried R in the past, and while it is a very valid language it has some limitations: It is single threaded by default, and although there are solutions for that, they are non as clean as python.

Also, python seems to be THE language for machine learning, it is easy to learn, and fast (depending on the interpreter implementation of course), also there is huuuuuuge support for it, lots of tutorials, documentation and, more important, libraries are actively develop and supported.

Finally, i recommend you to consider spyder as a good IDE for data science, I also tried Rodeo, but it does not seem as mature and stable as spyder.

Hope this helps.


问:
How to use FormData in AJAX?
Is there way to make single var and function in the same time ? If it's possible, how to take the single var #id and then put it into FormData ? The following foo.php looks like:

```<code>.
.
.
<input type="hidden" id="id" name="id" value="<?php echo $_GET['id']; ?>" />
<div id="dock" class="dock">Drag & Drop Photos Here</div>
.
.
.
<script type="text/javascript" src="script/tuto-dd-upload-image.js"></script>
</code>```

tuto-dd-upload-image.js has included:

```<code>$(document).ready(function() {

    // Add eventhandlers for dragover and prevent the default actions for this event
    $('#dock').on('dragover', function(e) {
        $(this).attr('class', 'dock_hover'); // If drag over the window, we change the class of the #dock div by "dock_hover"
        e.preventDefault();
        e.stopPropagation();
    });

    // Add eventhandlers for dragenter and prevent the default actions for this event
    $('#dock').on('dragenter', function(e) {
        e.preventDefault();
        e.stopPropagation();
    });

    $('#dock').on('dragleave', function(e) {
        $(this).attr('class', 'dock'); // If drag OUT the window, we change the class of the #dock div by "dock" (the original one)
    });

    // When drop the images
    $('#dock').on('drop', function(e){ // drop-handler event
        if (e.originalEvent.dataTransfer) {
            $('.progress-bar').attr('style', 'width: 0%').attr('aria-valuenow', '0').text('0%'); // Bootstrap progress bar at 0%
            if (e.originalEvent.dataTransfer.files.length) { // Check if we have files
                e.preventDefault();
                e.stopPropagation();
                // Launch the upload function
                upload(e.originalEvent.dataTransfer.files); // Access the dropped files with e.originalEvent.dataTransfer.files
            }
        }
    });

    function upload(files){ // upload function
        var fd = new FormData(); // Create a FormData object
        for (var i = 0; i < files.length; i++) { // Loop all files
            fd.append('file_' + i, files[i]); // Create an append() method, one for each file dropped
        }
        fd.append('nbr_files', i); // The last append is the number of files
        fd.$('#id').val();
        $.ajax({ // JQuery Ajax
            type: 'POST',
            url: 'ajax/tuto-dd-upload-image.php', // URL to the PHP file which will insert new value in the database
            data: fd, // We send the data string
            processData: false,
            contentType: false,
            success: function(data) {
                $('#result').html(data); // Display images thumbnail as result
                $('#dock').attr('class', 'dock'); // #dock div with the "dock" class
                $('.progress-bar').attr('style', 'width: 100%').attr('aria-valuenow', '100').text('100%'); // Progress bar at 100% when finish
            },
            xhrFields: { //
                onprogress: function (e) {
                    if (e.lengthComputable) {
                        var pourc = e.loaded / e.total * 100;
                        $('.progress-bar').attr('style', 'width: ' + pourc + '%').attr('aria-valuenow', pourc).text(pourc + '%');
                    }
                }
            },
        });
    }

});
</code>```

After those both php and js, the data will be sent to tuto-dd-upload-image.php and here's following tuto-dd-upload-image.php code:

```<code>.
.
.
$imgType = $_FILES["file_".$i]["type"];
$imgSize = $_FILES["file_".$i]["size"];
$id = $_POST['id'];
echo $imgType;
echo $imgSize;
echo $id;
.
.
.
</code>```

Unfortunately, at the same time $imgType and imgSize are appeared whereas $id are not appeared. How to tucking #id into FormData ? I think there's something way but limitation of my brain and skill as for jquery and ajax. Thank you.

答:
You must append it your form data

change

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

to

```<code>fd.append('id', $('#id').val());
</code>```

Title: How to use FormData in AJAX?

Body:
Is there way to make single var and function in the same time ? If it's possible, how to take the single var #id and then put it into FormData ? The following foo.php looks like:

.
.
.
<input type="hidden" id="id" name="id" value="<?php echo $_GET['id']; ?>" />

Drag & Drop Photos Here

.
.
.

tuto-dd-upload-image.js has included:

$(document).ready(function() {

    // Add eventhandlers for dragover and prevent the default actions for this event
    $('#dock').on('dragover', function(e) {
        $(this).attr('class', 'dock_hover'); // If drag over the window, we change the class of the #dock div by "dock_hover"
        e.preventDefault();
        e.stopPropagation();
    });

    // Add eventhandlers for dragenter and prevent the default actions for this event
    $('#dock').on('dragenter', function(e) {
        e.preventDefault();
        e.stopPropagation();
    });

    $('#dock').on('dragleave', function(e) {
        $(this).attr('class', 'dock'); // If drag OUT the window, we change the class of the #dock div by "dock" (the original one)
    });

    // When drop the images
    $('#dock').on('drop', function(e){ // drop-handler event
        if (e.originalEvent.dataTransfer) {
            $('.progress-bar').attr('style', 'width: 0%').attr('aria-valuenow', '0').text('0%'); // Bootstrap progress bar at 0%
            if (e.originalEvent.dataTransfer.files.length) { // Check if we have files
                e.preventDefault();
                e.stopPropagation();
                // Launch the upload function
                upload(e.originalEvent.dataTransfer.files); // Access the dropped files with e.originalEvent.dataTransfer.files
            }
        }
    });

    function upload(files){ // upload function
        var fd = new FormData(); // Create a FormData object
        for (var i = 0; i < files.length; i++) { // Loop all files
            fd.append('file_' + i, files[i]); // Create an append() method, one for each file dropped
        }
        fd.append('nbr_files', i); // The last append is the number of files
        fd.$('#id').val();
        $.ajax({ // JQuery Ajax
            type: 'POST',
            url: 'ajax/tuto-dd-upload-image.php', // URL to the PHP file which will insert new value in the database
            data: fd, // We send the data string
            processData: false,
            contentType: false,
            success: function(data) {
                $('#result').html(data); // Display images thumbnail as result
                $('#dock').attr('class', 'dock'); // #dock div with the "dock" class
                $('.progress-bar').attr('style', 'width: 100%').attr('aria-valuenow', '100').text('100%'); // Progress bar at 100% when finish
            },
            xhrFields: { //
                onprogress: function (e) {
                    if (e.lengthComputable) {
                        var pourc = e.loaded / e.total * 100;
                        $('.progress-bar').attr('style', 'width: ' + pourc + '%').attr('aria-valuenow', pourc).text(pourc + '%');
                    }
                }
            },
        });
    }

});

After those both php and js, the data will be sent to tuto-dd-upload-image.php and here's following tuto-dd-upload-image.php code:

.
.
.
$imgType = $_FILES["file_".$i]["type"];
$imgSize = $_FILES["file_".$i]["size"];
$id = $_POST['id'];
echo $imgType;
echo $imgSize;
echo $id;
.
.
.

Unfortunately, at the same time $imgType and imgSize are appeared whereas $id are not appeared. How to tucking #id into FormData ? I think there's something way but limitation of my brain and skill as for jquery and ajax. Thank you.

Body:
You must append it your form data

change

fd.$('#id').val();

to

fd.append('id', $('#id').val());


问:
Build nested JSON in Javascript
I would like to replicate this example data set into nested JSON using JavaScript or Angularjs or any javascript library.

Data:

```<code>PrimaryId,FirstName,LastName,City,CarName,DogName
100,John,Smith,NewYork,Toyota,Spike
100,John,Smith,NewYork,BMW,Spike
100,John,Smith,NewYork,Toyota,Rusty
100,John,Smith,NewYork,BMW,Rusty
101,Ben,Swan,Sydney,Volkswagen,Buddy
101,Ben,Swan,Sydney,Ford,Buddy
101,Ben,Swan,Sydney,Audi,Buddy
101,Ben,Swan,Sydney,Volkswagen,Max
101,Ben,Swan,Sydney,Ford,Max
101,Ben,Swan,Sydney,Audi,Max
102,Julia,Brown,London,Mini,Lucy
</code>```

Javascript:

```<code>var file = reader.result;
var singleRow = readerFile.split(/\r\n|\n/);
var header = singleRow[0].split(',');
var result =[];

    for ( var i=1; i < file.length; i++ ){
        var elementData = singleRow[i].split(',');
        elementData = elementData.filter(function(n){ return n != "" });
        var Obj = {};

        for ( var j=0; j < header.length; j++ ){
            Obj[header[j]] = elementData[j];
            /*
              - How can i build child object and append back to Obj before j loop
              - How can i build multiple child for same parent
            */
        }
        result.push(Obj);
    }
    console.log(" Print the JSON Object : " + JSON.stringify(result));
</code>```

Desired Output:

```<code>{
    "data": [
        {
            "City": "NewYork",
            "FirstName": "John",
            "PrimaryId": 100,
            "LastName": "Smith",
            "CarName": [
                "Toyota",
                "BMW"
            ],
            "DogName": [
                "Spike",
                "Rusty"
            ]
        },
        {
            "City": "Sydney",
            "FirstName": "Ben",
            "PrimaryId": 101,
            "LastName": "Swan",
            "CarName": [
                "Volkswagen",
                "Ford",
                "Audi"
            ],
            "DogName": [
                "Buddy",
                "Max"
            ]
        },
        {
            "City": "London",
            "FirstName": "Julia",
            "PrimaryId": 102,
            "LastName": "Brown",
            "CarName": [
                "Mini"
            ],
            "DogName": [
                "Lucy"
            ]
        }
    ]
}
</code>```

If Firstname, Lastname and City has same values then CarName and DogName values should be child object under the same parent

答:
I reformatted your initial code a little bit, but it doesn't change the initial logic. One key observation is that even if the FirstName, LastName and City are the same, that may not be a unique person, hence you should use the PrimaryId instead, to determine uniqueness.

Look at the post-processing section for the new code:

```<code>const data = `PrimaryId,FirstName,LastName,City,CarName,DogName
100,John,Smith,NewYork,Toyota,Spike
100,John,Smith,NewYork,BMW,Spike
100,John,Smith,NewYork,Toyota,Rusty
100,John,Smith,NewYork,BMW,Rusty
101,Ben,Swan,Sydney,Volkswagen,Buddy
101,Ben,Swan,Sydney,Ford,Buddy
101,Ben,Swan,Sydney,Audi,Buddy
101,Ben,Swan,Sydney,Volkswagen,Max
101,Ben,Swan,Sydney,Ford,Max
101,Ben,Swan,Sydney,Audi,Max
102,Julia,Brown,London,Mini,Lucy`;

var singleRow = data.split(/\r\n|\n/);
var header = singleRow[0].split(',');
var result =[];

for (var i = 1; i < singleRow.length; i++) {
  var elementData = singleRow[i].split(',');
  elementData = elementData.filter(function(n) { return n != '' });
  var Obj = {};
  for ( var j=0; j < header.length; j++ ){
    Obj[header[j]] = elementData[j];
  }
  result.push(Obj);
}

console.log(JSON.stringify(result, null, 2));

// Post-processing code starts here
const people = {};

// Create a map of unique people first
result.forEach(function (object) {
  if (!people[object.PrimaryId]) {
    people[object.PrimaryId] = {
      City: object.City,
      FirstName: object.FirstName,
      PrimaryId: object.PrimaryId,
      LastName: object.LastName,
      CarName: [],
      DogName: [],
    };
  }
  // As you iterate through your results, if this person already exists
  // add to their array of car and dogs.
  people[object.PrimaryId].CarName.push(object.CarName);
  people[object.PrimaryId].DogName.push(object.DogName);
});

// Convert back into an array
const peopleList = [];
Object.keys(people).forEach(function (primaryId) {
  peopleList.push(people[primaryId]);
})

console.log(peopleList);
</code>```

Title: Build nested JSON in Javascript

Body:
I would like to replicate this example data set into nested JSON using JavaScript or Angularjs or any javascript library.

Data:

PrimaryId,FirstName,LastName,City,CarName,DogName
100,John,Smith,NewYork,Toyota,Spike
100,John,Smith,NewYork,BMW,Spike
100,John,Smith,NewYork,Toyota,Rusty
100,John,Smith,NewYork,BMW,Rusty
101,Ben,Swan,Sydney,Volkswagen,Buddy
101,Ben,Swan,Sydney,Ford,Buddy
101,Ben,Swan,Sydney,Audi,Buddy
101,Ben,Swan,Sydney,Volkswagen,Max
101,Ben,Swan,Sydney,Ford,Max
101,Ben,Swan,Sydney,Audi,Max
102,Julia,Brown,London,Mini,Lucy

Javascript:

var file = reader.result;
var singleRow = readerFile.split(/\r\n|\n/);
var header = singleRow[0].split(',');
var result =[];

    for ( var i=1; i < file.length; i++ ){
        var elementData = singleRow[i].split(',');
        elementData = elementData.filter(function(n){ return n != "" });
        var Obj = {};

        for ( var j=0; j < header.length; j++ ){
            Obj[header[j]] = elementData[j];
            /*
              - How can i build child object and append back to Obj before j loop
              - How can i build multiple child for same parent
            */
        }
        result.push(Obj);
    }
    console.log(" Print the JSON Object : " + JSON.stringify(result));

Desired Output:

{
    "data": [
        {
            "City": "NewYork",
            "FirstName": "John",
            "PrimaryId": 100,
            "LastName": "Smith",
            "CarName": [
                "Toyota",
                "BMW"
            ],
            "DogName": [
                "Spike",
                "Rusty"
            ]
        },
        {
            "City": "Sydney",
            "FirstName": "Ben",
            "PrimaryId": 101,
            "LastName": "Swan",
            "CarName": [
                "Volkswagen",
                "Ford",
                "Audi"
            ],
            "DogName": [
                "Buddy",
                "Max"
            ]
        },
        {
            "City": "London",
            "FirstName": "Julia",
            "PrimaryId": 102,
            "LastName": "Brown",
            "CarName": [
                "Mini"
            ],
            "DogName": [
                "Lucy"
            ]
        }
    ]
}

If Firstname, Lastname and City has same values then CarName and DogName values should be child object under the same parent

Body:
I reformatted your initial code a little bit, but it doesn't change the initial logic. One key observation is that even if the FirstName, LastName and City are the same, that may not be a unique person, hence you should use the PrimaryId instead, to determine uniqueness.

Look at the post-processing section for the new code:

const data = `PrimaryId,FirstName,LastName,City,CarName,DogName
100,John,Smith,NewYork,Toyota,Spike
100,John,Smith,NewYork,BMW,Spike
100,John,Smith,NewYork,Toyota,Rusty
100,John,Smith,NewYork,BMW,Rusty
101,Ben,Swan,Sydney,Volkswagen,Buddy
101,Ben,Swan,Sydney,Ford,Buddy
101,Ben,Swan,Sydney,Audi,Buddy
101,Ben,Swan,Sydney,Volkswagen,Max
101,Ben,Swan,Sydney,Ford,Max
101,Ben,Swan,Sydney,Audi,Max
102,Julia,Brown,London,Mini,Lucy`;

var singleRow = data.split(/\r\n|\n/);
var header = singleRow[0].split(',');
var result =[];

for (var i = 1; i < singleRow.length; i++) {
  var elementData = singleRow[i].split(',');
  elementData = elementData.filter(function(n) { return n != '' });
  var Obj = {};
  for ( var j=0; j < header.length; j++ ){
    Obj[header[j]] = elementData[j];
  }
  result.push(Obj);
}

console.log(JSON.stringify(result, null, 2));

// Post-processing code starts here
const people = {};

// Create a map of unique people first
result.forEach(function (object) {
  if (!people[object.PrimaryId]) {
    people[object.PrimaryId] = {
      City: object.City,
      FirstName: object.FirstName,
      PrimaryId: object.PrimaryId,
      LastName: object.LastName,
      CarName: [],
      DogName: [],
    };
  }
  // As you iterate through your results, if this person already exists
  // add to their array of car and dogs.
  people[object.PrimaryId].CarName.push(object.CarName);
  people[object.PrimaryId].DogName.push(object.DogName);
});

// Convert back into an array
const peopleList = [];
Object.keys(people).forEach(function (primaryId) {
  peopleList.push(people[primaryId]);
})

console.log(peopleList);