问:
Ziparchive for multiple files into memory stream
I have studied the answers to similar questions, but have not seen one where multiple files are gathered into an ziparchive for transmission to download. The following gives no errors but does not return a recognizable zip file.</p>

```<code>public async Task<HttpResponseMessage> SendAZipOfFiles()
{
      var memoryStream = new MemoryStream();
      var response = new HttpResponseMessage(HttpStatusCode.OK);

      List<string> filepaths = await GetSomeFiles();
      using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
      {
          foreach (string filepath in filepaths)
          {
               string filename = Path.GetFileName(filepath);
               using (StreamReader reader = new StreamReader(filepath))
               using (StreamWriter writer = new StreamWriter(archive.CreateEntry(filename).Open()))
               {
                    writer.Write(reader.ReadToEnd());
               }
          }
      }
      memoryStream.Position = 0;
      response.Content = new StreamContent(memoryStream);
      response.Content.Headers.ContentLength = memoryStream.Length;
      response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
      {
          FileName = "TheFile.zip")
      };
      response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
     return response;
}
</code>```

答:
It turned out my problem was on the typescript side.

I did change the code, replacing:

```<code>string filename = Path.GetFileName(filepath);
using (StreamReader reader = new StreamReader(filepath))
using (StreamWriter writer = new
StreamWriter(archive.CreateEntry(filename).Open()))
{
    writer.Write(reader.ReadToEnd());
}
</code>```

with the simpler:

```<code>archive.CreateEntryFromFile(filepath, Path.GetFileName(filepath));
</code>```

Body:
I have studied the answers to similar questions, but have not seen one where multiple files are gathered into an ziparchive for transmission to download. The following gives no errors but does not return a recognizable zip file.

public async Task<HttpResponseMessage> SendAZipOfFiles()
{
      var memoryStream = new MemoryStream();
      var response = new HttpResponseMessage(HttpStatusCode.OK);

      List<string> filepaths = await GetSomeFiles();
      using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
      {
          foreach (string filepath in filepaths)
          {
               string filename = Path.GetFileName(filepath);
               using (StreamReader reader = new StreamReader(filepath))
               using (StreamWriter writer = new StreamWriter(archive.CreateEntry(filename).Open()))
               {
                    writer.Write(reader.ReadToEnd());
               }
          }
      }
      memoryStream.Position = 0;
      response.Content = new StreamContent(memoryStream);
      response.Content.Headers.ContentLength = memoryStream.Length;
      response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
      {
          FileName = "TheFile.zip")
      };
      response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
     return response;
}

Body:
It turned out my problem was on the typescript side.

I did change the code, replacing:

string filename = Path.GetFileName(filepath);
using (StreamReader reader = new StreamReader(filepath))
using (StreamWriter writer = new
StreamWriter(archive.CreateEntry(filename).Open()))
{
    writer.Write(reader.ReadToEnd());
}

with the simpler:

archive.CreateEntryFromFile(filepath, Path.GetFileName(filepath));


来源: stackexchange

问:
Dojo EnhancedGrid editable problem
I'm having problem with making my dojo EnhancedGrid editable.
Currently, I can double click the grid cells and I can change the value, but the moment I press enter again or try to leave the cells (i.e. to save the new value to the grid), I received the "assertion failed in ItemFileWriteStore" error in my firebug.

Below is my source code:

```<code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
    <head>
    <style type="text/css">
        body, html { font-family:helvetica,arial,sans-serif; font-size:90%; }
    </style>
    <link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/dojo/1.5/dijit/themes/claro/claro.css" />
    <style type="text/css">
        @import "http://ajax.googleapis.com/ajax/libs/dojo/1.5/dojox/grid/resources/Grid.css";
        @import "http://ajax.googleapis.com/ajax/libs/dojo/1.5/dojox/grid/resources/claroGrid.css";
        .dojoxGrid table { margin: 0; }
    </style>
    <script src="http://ajax.googleapis.com/ajax/libs/dojo/1.5/dojo/dojo.xd.js" djConfig="parseOnLoad: true">
    </script>

    <script type="text/javascript">
        dojo.require("dojox.grid.EnhancedGrid");
        dojo.require("dojo.data.ItemFileWriteStore");
        dojo.require("dojox.grid.cells._base");

        dojo.addOnLoad(function() {

            var layoutabc =
            [[
                {
                    field: "title",
                    name: "TitleofMovie",
                    width: "300px",
                    editable: true
                },
                {
                    field: "year",
                    name: "Year",
                    width: "200px",
                    editable: true
                },
                {
                    field: "producer",
                    name: "Producer",
                    width: "auto",
                    editable: true,
                    type: dojox.grid.cells.Cell
                }
            ]];

            var mystore = new dojo.data.ItemFileWriteStore({
                url: "movies.json"
            });

            // create a new grid:
            var grid = new dojox.grid.EnhancedGrid(
                {
                    query: {},
                    store: mystore,
                    structure: layoutabc
                },
                document.createElement("div")
            );
            dojo.byId("gridDiv").appendChild(grid.domNode);

            grid.startup();
        });
    </script>
</head>

<body class="claro">
    <div id="gridDiv" style="width: 800px; height: 400px;">
    </div>
</body>
</code>```

And this is the content of my movies.json (the content of data is weird, I know):

```<code>{
    items:
    [
        {
            title: "Africa",
            year: "continent",
            producer: "Katia Lund"
        },
        {
            title: "Kenya",
            year: "country",
            producer: "Christine Jeffs"
        },
        {
            title: "Mombasa",
            year: "city",
            producer: "Ridley Scott"
        }
    ]
}
</code>```

答:
I think the problem is that your store does not contain any identifier so when the grid tries to write to the store, it does not have any way to know which entry it should write to.

I would start by editing the response for movies.json, perhaps like this:

```<code>{
    identifier:"id",
    items:
    [
        {
            id:1
            title: "Africa",
            year: "continent",
            producer: "Katia Lund"
        },
        {
            id:2
            title: "Kenya",
            year: "country",
            producer: "Christine Jeffs"
        },
        {
            id:3
            title: "Mombasa",
            year: "city",
            producer: "Ridley Scott"
        }
    ]
}
</code>```

Note that you don't have to include the id field in the layout list, it will be accessible to the grid anyway. Also, as identifier implies, it must be a unique value for each item in the store, otherwise it will fail to initialize.

ContentLicense: CC BY-SA 2.5

Title: Dojo EnhancedGrid editable problem

Body:
I'm having problem with making my dojo EnhancedGrid editable.
Currently, I can double click the grid cells and I can change the value, but the moment I press enter again or try to leave the cells (i.e. to save the new value to the grid), I received the "assertion failed in ItemFileWriteStore" error in my firebug.

Below is my source code:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

    <link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/dojo/1.5/dijit/themes/claro/claro.css" />

And this is the content of my movies.json (the content of data is weird, I know):

{
    items:
    [
        {
            title: "Africa",
            year: "continent",
            producer: "Katia Lund"
        },
        {
            title: "Kenya",
            year: "country",
            producer: "Christine Jeffs"
        },
        {
            title: "Mombasa",
            year: "city",
            producer: "Ridley Scott"
        }
    ]
}

Body:
I think the problem is that your store does not contain any identifier so when the grid tries to write to the store, it does not have any way to know which entry it should write to.

I would start by editing the response for movies.json, perhaps like this:

{
    identifier:"id",
    items:
    [
        {
            id:1
            title: "Africa",
            year: "continent",
            producer: "Katia Lund"
        },
        {
            id:2
            title: "Kenya",
            year: "country",
            producer: "Christine Jeffs"
        },
        {
            id:3
            title: "Mombasa",
            year: "city",
            producer: "Ridley Scott"
        }
    ]
}

Note that you don't have to include the id field in the layout list, it will be accessible to the grid anyway. Also, as identifier implies, it must be a unique value for each item in the store, otherwise it will fail to initialize.


问:
creating tags like stackoverflow using jquery
i want to make tag like stack overflow tags but the problems are 1- when i click tab it doesn't work 2-when i click enter the effect of save client is clicked and 3- i want to send the tags as array of list

```<code><div class="row">
              <div class="form-group">
                <div class="col-md-12 col-sm-12">
                  <label>Address *</label>
                  <div class="target" contenteditable="true"></div>
                    <input type="text" id="clientAdd" name="address" value="" class="form-control required">
                </div>
              </div>
            </div>

<div class="row">
            <div class="col-md-12">
              <button type="submit" class="btn btn-3d btn-teal btn-xlg btn-block margin-top-30">
                Save Client
              </button>
            </div>
          </div>
</code>```

this is the jq code

```<code>$("#clientAdd").keypress(function (e) {
if (e.which === 9 || e.which === 32 ) {
     $(".target").append("<a href='#' class='tag'>" + this.value + "</a>");
        var stringList = [];
        stringList.push(this.value);
        this.value = "";
}
</code>```

});

this is the css code

```<code>.tag {
 color: #3E6D8E;
 background-color: #E0EAF1;
 border-bottom: 1px solid #b3cee1;
 border-right: 1px solid #b3cee1;
 padding: 3px 4px 3px 4px;
 margin: 2px 2px 2px 0;
 text-decoration: none;
 font-size: 90%;
 line-height: 2.4;
 white-space: nowrap;
 }
.tag:hover {
   background-color: #c4dae9;
   border-bottom: 1px solid #c4dae9;
   border-right: 1px solid #c4dae9;
}
</code>```

答:
Use vanilla.js it's available in all browsers, it's faster and no library required. Select your elements, add an event listener, create a new element and append that element and you are done!

var input = document.getElementById('clientAdd');
var target= document.getElementsByClassName('target')[0];
var button = document.querySelectorAll('button[type="submit"]')[0];
var stringList=[];

input.addEventListener('keypress', function(e){

if (e.which === 9 || e.which === 32 ){
let atag= document.createElement('a');
atag.setAttribute('class','tag');
atag.setAttribute('href','#');
atag.innerHTML=this.value;
stringList.push(this.value);
target.appendChild(atag);
console.log('your string has been added to the array', stringList);
}
});

button.addEventListener('click', clicked =>{
let atag= document.createElement('a');
atag.setAttribute('class','tag');
atag.setAttribute('href','#');
atag.innerHTML=input.value;
stringList.push(input.value);
target.appendChild(atag);
console.log('your string has been added to the array', stringList);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.tag {
 color: #3E6D8E;
 background-color: #E0EAF1;
 border-bottom: 1px solid #b3cee1;
 border-right: 1px solid #b3cee1;
 padding: 3px 4px 3px 4px;
 margin: 2px 2px 2px 0;
 text-decoration: none;
 font-size: 90%;
 line-height: 2.4;
 white-space: nowrap;
 }
.tag:hover {
   background-color: #c4dae9;
   border-bottom: 1px solid #c4dae9;
   border-right: 1px solid #c4dae9;
}</code>```

                  Address *

                    <input type="text" id="clientAdd" name="address" value="" class="form-control required">

              <button type="submit" class="btn btn-3d btn-teal btn-xlg btn-block margin-top-30">
                Save Client
              </button>

```

ContentLicense: CC BY-SA 3.0

Body:
i want to make tag like stack overflow tags but the problems are 1- when i click tab it doesn't work 2-when i click enter the effect of save client is clicked and 3- i want to send the tags as array of list

                  Address *

                    <input type="text" id="clientAdd" name="address" value="" class="form-control required">

              <button type="submit" class="btn btn-3d btn-teal btn-xlg btn-block margin-top-30">
                Save Client
              </button>

this is the jq code

$("#clientAdd").keypress(function (e) {
if (e.which === 9 || e.which === 32 ) {
     $(".target").append("" + this.value + "");
        var stringList = [];
        stringList.push(this.value);
        this.value = "";
}

});

this is the css code

.tag {
 color: #3E6D8E;
 background-color: #E0EAF1;
 border-bottom: 1px solid #b3cee1;
 border-right: 1px solid #b3cee1;
 padding: 3px 4px 3px 4px;
 margin: 2px 2px 2px 0;
 text-decoration: none;
 font-size: 90%;
 line-height: 2.4;
 white-space: nowrap;
 }
.tag:hover {
   background-color: #c4dae9;
   border-bottom: 1px solid #c4dae9;
   border-right: 1px solid #c4dae9;
}

Body:
Use vanilla.js it's available in all browsers, it's faster and no library required. Select your elements, add an event listener, create a new element and append that element and you are done!

var input = document.getElementById('clientAdd');
var target= document.getElementsByClassName('target')[0];
var button = document.querySelectorAll('button[type="submit"]')[0];
var stringList=[];

input.addEventListener('keypress', function(e){

if (e.which === 9 || e.which === 32 ){
let atag= document.createElement('a');
atag.setAttribute('class','tag');
atag.setAttribute('href','#');
atag.innerHTML=this.value;
stringList.push(this.value);
target.appendChild(atag);
console.log('your string has been added to the array', stringList);
}
});

button.addEventListener('click', clicked =>{
let atag= document.createElement('a');
atag.setAttribute('class','tag');
atag.setAttribute('href','#');
atag.innerHTML=input.value;
stringList.push(input.value);
target.appendChild(atag);
console.log('your string has been added to the array', stringList);
});

.tag {
 color: #3E6D8E;
 background-color: #E0EAF1;
 border-bottom: 1px solid #b3cee1;
 border-right: 1px solid #b3cee1;
 padding: 3px 4px 3px 4px;
 margin: 2px 2px 2px 0;
 text-decoration: none;
 font-size: 90%;
 line-height: 2.4;
 white-space: nowrap;
 }
.tag:hover {
   background-color: #c4dae9;
   border-bottom: 1px solid #c4dae9;
   border-right: 1px solid #c4dae9;
}

<div class="row">
              <div class="form-group">
                <div class="col-md-12 col-sm-12">
                  <label>Address *</label>
                  <div class="target" contenteditable="true"></div>
                    <input type="text" id="clientAdd" name="address" value="" class="form-control required">
                </div>
              </div>
            </div>

<div class="row">
            <div class="col-md-12">
              <button type="submit" class="btn btn-3d btn-teal btn-xlg btn-block margin-top-30">
                Save Client
              </button>
            </div>
          </div>


问:
Set EditText above listview with swiperefreshlayout
I'm trying to put EditText above listview but I don't understand why listiview is overlapping over edit text. Here is the layout source:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:padding="10dp"
   >

    <RelativeLayout
        android:id="@+id/firstlayout"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="horizontal" >

        <TextView
            android:id="@+id/textEnter"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="hello" />

        <EditText
            android:id="@+id/editTextInput"
            android:layout_below="@+id/textEnter"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" />
    </RelativeLayout>

    <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/sw_refresh"
        android:layout_width="match_parent"
        android:layout_height="fill_parent">

    <!--layout which should be refreshed should come here-->
    <ListView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="fill_parent"
        android:listSelector="@drawable/list_selector"
        android:background="@drawable/customshape"
        android:fadeScrollbars="false"
        >
        </ListView>

    </android.support.v4.widget.SwipeRefreshLayout>

</RelativeLayout>
</code>```

I had tried everything that was on my mind and in Android Studio designer there is error like Layout fidelity warning

答:
Add just this line android:layout_below="@+id/firstlayout"

```<code><android.support.v4.widget.SwipeRefreshLayout
    android:id="@+id/sw_refresh"
    android:layout_width="match_parent"
    android:layout_below="@+id/firstlayout"
    android:layout_height="fill_parent">

<ListView
    android:id="@+id/list"
    android:layout_width="match_parent"
    android:layout_height="fill_parent"
    android:listSelector="@drawable/list_selector"
    android:background="@drawable/customshape"
    android:fadeScrollbars="false" >
</ListView>
</android.support.v4.widget.SwipeRefreshLayout>
</code>```

Body:
I'm trying to put EditText above listview but I don't understand why listiview is overlapping over edit text. Here is the layout source:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:padding="10dp"
   >

    <RelativeLayout
        android:id="@+id/firstlayout"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="horizontal" >

        <TextView
            android:id="@+id/textEnter"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="hello" />

        <EditText
            android:id="@+id/editTextInput"
            android:layout_below="@+id/textEnter"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" />
    </RelativeLayout>

    <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/sw_refresh"
        android:layout_width="match_parent"
        android:layout_height="fill_parent">

    <ListView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="fill_parent"
        android:listSelector="@drawable/list_selector"
        android:background="@drawable/customshape"
        android:fadeScrollbars="false"
        >
        </ListView>

    </android.support.v4.widget.SwipeRefreshLayout>

</RelativeLayout>

I had tried everything that was on my mind and in Android Studio designer there is error like Layout fidelity warning

Body:
Add just this line android:layout_below="@+id/firstlayout"

<android.support.v4.widget.SwipeRefreshLayout
    android:id="@+id/sw_refresh"
    android:layout_width="match_parent"
    android:layout_below="@+id/firstlayout"
    android:layout_height="fill_parent">

<ListView
    android:id="@+id/list"
    android:layout_width="match_parent"
    android:layout_height="fill_parent"
    android:listSelector="@drawable/list_selector"
    android:background="@drawable/customshape"
    android:fadeScrollbars="false" >
</ListView>
</android.support.v4.widget.SwipeRefreshLayout>


问:
How can I drop the first level from a multi level column by chaining?
How can I drop the first level from a multi level column?

For a data frame:

```<code>tmp.head(1000).groupby(['user_id', 'aisle_id']).agg({'aisle_id': ['count']})
</code>```

giving

```<code>                 aisle_id
                    count
user_id aisle_id
382     38              1
        84              2
        115             1
3107    43              1
3321    37              1
        69              2
</code>```

I want to drop the aisle_id in my columns. How can I do this by chaining commands without having to start another statement?

答:
You can quickly access the first level of the columns multiindex with the dot operator.  Similar to how you'd access columns with a single level index.

just add .aisle_id at the end.  Or equivalently ['aisle_id']

```<code>tmp.head(1000).groupby(['user_id', 'aisle_id']).agg({'aisle_id': ['count']}) \
    .aisle_id

                  count
user_id aisle_id
381     38            1
382     84            2
        115           1
3107    43            1
3321    37            1
        69            2
</code>```

Response to Comment

@displayname these are equivalent df.aisle_id and df.xs('aisle_id').  What I mean to point out is that it will access all columns whose first level is aisle_id.  If you were to aggregate the way you had, this will work identically to what ScottBoston has suggested.  The difference is that if you wanted to store the results of an aggregation into a variable that was over more that just one column, then those results are preserved and you can access just aisle_id with df.aisle_id.  The advantage of ScottBoston's solution is that when more that one column is available, we limit the calculation to just over aisle_id.

Body:
How can I drop the first level from a multi level column?

For a data frame:

tmp.head(1000).groupby(['user_id', 'aisle_id']).agg({'aisle_id': ['count']})

giving

                 aisle_id
                    count
user_id aisle_id
382     38              1
        84              2
        115             1
3107    43              1
3321    37              1
        69              2

I want to drop the aisle_id in my columns. How can I do this by chaining commands without having to start another statement?

Body:
You can quickly access the first level of the columns multiindex with the dot operator.  Similar to how you'd access columns with a single level index.

just add .aisle_id at the end.  Or equivalently ['aisle_id']

tmp.head(1000).groupby(['user_id', 'aisle_id']).agg({'aisle_id': ['count']}) \
    .aisle_id

                  count
user_id aisle_id
381     38            1
382     84            2
        115           1
3107    43            1
3321    37            1
        69            2

Response to Comment

@displayname these are equivalent df.aisle_id and df.xs('aisle_id').  What I mean to point out is that it will access all columns whose first level is aisle_id.  If you were to aggregate the way you had, this will work identically to what ScottBoston has suggested.  The difference is that if you wanted to store the results of an aggregation into a variable that was over more that just one column, then those results are preserved and you can access just aisle_id with df.aisle_id.  The advantage of ScottBoston's solution is that when more that one column is available, we limit the calculation to just over aisle_id.


答:
Do all of your animation with one source.  Update the source each frame with setData(). Render one layer from the source using data-driven styles. This will use your GPU to render animations.
 This will improve performance considerably by reducing the number of layers and setData() calls.

Example code of animating in GL JS with one layer and one source: https://bl.ocks.org/ryanbaumann/9b9b52e09ff86d1ce8346fb76b681427

Title: MapBox GL JS marker/icon animation slow performance

Body:
I'm using mapbox-gl-js to animate many image from one coordinates to another on the map.
It become slow frame rate when I try to add up to 15 image and above.
Doing performance profile on chrome give me the hint to method Actor.receive, which cost the most computational time.

/**
 * Util.js
 */
 var linesDataSource = {
  "type": "FeatureCollection",
  "features": [{
    "type": "Feature",
    "properties": {},
    "geometry": {
      "type": "LineString",
      "coordinates": [
        [
          151.15684390068054, -33.89568424317427
        ],
        [
          151.15808844566345, -33.89606717952166
        ],
        [
          151.15779876708984, -33.89680633086413
        ],
        [
          151.15740180015564, -33.897794824453406
        ],
        [
          151.1582601070404, -33.8980085512904
        ],
        [
          151.1609423160553, -33.89863191817193
        ],
        [
          151.16222977638245, -33.89621857248702
        ],
        [
          151.16639256477356, -33.89771467675142
        ],
        [
          151.1694610118866, -33.898916884371395
        ],
        [
          151.17089867591858, -33.896298721595166
        ],
        [
          151.17217540740964, -33.899014841282515
        ],
        [
          151.1714780330658, -33.899192944468965
        ],
        [
          151.17132782936093, -33.89878330658397
        ],
        [
          151.1719822883606, -33.8985784869035
        ],
        [
          151.17339849472046, -33.89839147720036
        ],
        [
          151.17376327514648, -33.89825789858986
        ],
        [
          151.17332339286804, -33.897269410368615
        ],
        [
          151.1732053756714, -33.89697553328233
        ],
        [
          151.17341995239258, -33.89662822269281
        ],
        [
          151.17295861244202, -33.896263099778615
        ],
        [
          151.17225050926208, -33.89589797530112
        ],
        [
          151.17136001586914, -33.89561299901295
        ],
        [
          151.17184281349182, -33.894758064434605
        ],
        [
          151.17200374603271, -33.89455323508587
        ],
        [
          151.17257237434387, -33.89148073582115
        ],
        [
          151.17042660713196, -33.89132042847356
        ],
        [
          151.17168188095093, -33.88838140703873
        ],
        [
          151.1716067790985, -33.887606557247125
        ],
        [
          151.16321682929993, -33.888274531623864
        ],
        [
          151.16029858589172, -33.88777577791726
        ],
        [
          151.1591076850891, -33.88790937294604
        ],
        [
          151.15857124328613, -33.8892809364742
        ],
        [
          151.1584746837616, -33.89006467716016
        ],
        [
          151.15894675254822, -33.89009139546571
        ],
        [
          151.15893602371216, -33.889806399775104
        ]
      ]
    }
  }]
}

var PI = Math.PI;
var TWO_PI = Math.PI * 2;

function rotation(start, end) {
  var dx = end[0] - start[0];
  var dy = end[1] - start[1];
  return -Math.atan2(dy, dx) * (180 / PI);
};

function lerp(v0, v1, t) {
  return v0 * (1 - t) + v1 * t
}

function interpolateAngle(fromAngle, toAngle, t) {
  fromAngle = fromAngle * (PI / 180);
  toAngle = toAngle * (PI / 180);

  fromAngle = (fromAngle + TWO_PI) % TWO_PI;
  toAngle = (toAngle + TWO_PI) % TWO_PI;

  var diff = Math.abs(fromAngle - toAngle);
  if (diff < PI) {
    return lerp(fromAngle, toAngle, t) * (180 / PI);
  } else {
    if (fromAngle > toAngle) {
      fromAngle = fromAngle - TWO_PI;
      return lerp(fromAngle, toAngle, t) * (180 / PI);
    } else if (toAngle > fromAngle) {
      toAngle = toAngle - TWO_PI;
      return lerp(fromAngle, toAngle, t) * (180 / PI);
    }
  }
}

/**
 * Car.js
 */
function Car(name, map, path) {
  this.name = name;
  this.map = map;
  this.path = path;
  this.speed = 90; // 30 km/h
  this.accumulatedDistance = 0;
  this.previousPos = this.path.features[0].geometry.coordinates[0];
  this.previousAngle = 0;

  this.animate = function(frameInfo) {

    this.accumulatedDistance += ((frameInfo.deltaTime / 3600) * this.speed);
    var point = turf.along(this.path.features[0], this.accumulatedDistance, 'kilometers');

    this.map.getSource(this.name).setData(point);

    var newAngle = rotation(this.previousPos, point.geometry.coordinates);
    var rotate = interpolateAngle(this.previousAngle, newAngle, 0.1);

    this.map.setLayoutProperty(this.name, 'icon-rotate', rotate);

    this.previousAngle = rotate;
    this.previousPos = point.geometry.coordinates;
  };

  this.init = function() {
    this.map.addSource(this.name, {
      "type": "geojson",
      "data": {
        "type": "FeatureCollection",
        "features": [{
          "type": "Feature",
          "geometry": {
            "type": "Point",
            "coordinates": this.previousPos
          }
        }]
      }
    });

    this.map.addLayer({
      "id": this.name,
      "type": "symbol",
      "source": this.name,
      "layout": {
        "icon-image": "car",
        "icon-size": 1,
        "icon-rotate": 0,
        "icon-rotation-alignment": "map"
      }
    });
  };
}

/**
 * MapBoxTest.js
 */
var destination = {};
var cars = [];
var style = 'mapbox://styles/mapbox/streets-v9'; //'/TestEmptyProject/mapbox-gl-styles-master/styles/basic-v8.json';
//'http://localhost:8080/styles/osm-bright.json';  // 'http://localhost:8080/styles/fiord-color-gl.json'

mapboxgl.accessToken = 'pk.eyJ1IjoiZW1wZXJvcjE0MTIiLCJhIjoiY2ozYTYxdXFlMDM3dzJyczRsa2M5ZjE3aCJ9.9zQGtkSsjOw6npohN6ba3w';
var map = new mapboxgl.Map({
  container: 'map',
  style: style,
  center: [132.133333, -23.116667],
  zoom: 3
});

// Used to increment the value of the point measurement against the linesData.
var counter = 0;
var linesData = {};

function addCar() {
  var car = new Car("Car_" + counter, map, linesData);
  car.init();
  cars.push(car);
  ++counter;
}

var previousTimeStamp = 0;
// Add a source and layer displaying a point which will be animated in a circle.
function animate(timeStamp) {
  if (timeStamp <= previousTimeStamp) {
    console.log("Wrong timeStamp, now: " + timeStamp + "\t previous: " + previousTimeStamp);
    return;
  }

  var i;
  var frameInfo = {
    "timeStamp": timeStamp,
    "previousTimeStamp": previousTimeStamp,
    "deltaTime": (timeStamp - previousTimeStamp) / 1000
  };
  previousTimeStamp = timeStamp;

  for (i = 0; i < cars.length; ++i) {
    var car = cars[i];
    car.animate(frameInfo);
  }
  requestAnimationFrame(animate);
}

map.on('load', function() {

  console.log("map load");

  map.loadImage('https://maxcdn.icons8.com/office/PNG/40/Transport/railroad_car-40.png', function(error, image) {
    if (error) throw error;
    map.addImage('car', image);
  });

  //fetch('./lines.geojson', {
  //method: 'get'
//}).then(function(response) {
 // return response.json();
//}).then(function(data) {

  linesData = linesDataSource;
  var coordinates = linesData.features[0].geometry.coordinates;

  var bounds = coordinates.reduce(function(bounds, coord) {
    return bounds.extend(coord);
  }, new mapboxgl.LngLatBounds(coordinates[0], coordinates[0]));

  map.fitBounds(bounds, {
    padding: 20,
    duration: 2000
  });

  map.addSource('lines', {
    "type": "geojson",
    "data": linesData
  });

  map.addLayer({
    "id": "route",
    "source": "lines",
    "type": "line",
    "paint": {
      "line-width": 2,
      "line-color": "#007cbf"
    }
  });
  // }).catch(function(err) {
  //console.log("error: " + err);
//});

document.getElementById('addCar').addEventListener('click', function() {
addCar();
});

});

requestAnimationFrame(animate);

 body {
   margin: 0;
   padding: 0;
 }

 #map {
   position: absolute;
   top: 0;
   bottom: 0;
   width: 100%;
 }

 .overlay {
   position: absolute;
   top: 10px;
   left: 10px;
 }

 .overlay button {
   font: 600 12px/20px 'Helvetica Neue', Arial, Helvetica, sans-serif;
   background-color: #3386c0;
   color: #fff;
   display: inline-block;
   margin: 0;
   padding: 10px 20px;
   border: none;
   cursor: pointer;
   border-radius: 3px;
 }

 .overlay button:hover {
   background-color: #4ea0da;
 }

<link href="https://api.tiles.mapbox.com/mapbox-gl-js/v0.37.0/mapbox-gl.css" rel="stylesheet"/>

    <button id='addCar'>Add Car</button>


问:
how to save or move image file to a folder contain in my php file folder
I'm building a media and I want my users to
 upload as many images as they like,But my problem
 is how to save or move this image to a folder
 called photo contain in folder called my_media,
 my_media folder contain my php files such as
 index.php and more,I can move this file to
 my_media folder once upload,But i don't want
 the file they for security purpose,please
 someone should fix my code thanks.

this my code

```<code>require_once ('connect.php');

if (isset($_POST['Submit'])) {

 $tmp_dir = "my_media/photo";
 //it will move to my_media if assign my_media only to the variable $tmp_dir
 //but don't work with  $tmp_dir = "my_media/photo"

 $tmp_name = $_FILES["image"]["tmp_name"];
 $name = $_FILES["image"]["name"];

move_uploaded_file($tmp_name,$tmp_dir . basename($name));

    //rename("my_media/photo","my_media/photo". basename($name));
$location=$name;
$fname=$_POST['first_name'];
$lname=$_POST['last_name'];

$sql = "INSERT INTO tbl_image (first_name, last_name, image_location)
VALUES ('$fname', '$lname', '$location')";
 $res = mysqli_query($con,$sql);
//with this my the image name is inserted into my database but not into the foldermy_media/photo
header("Location:imgview.php");
}
</code>```

答:
First of all, lets remove all / and replace them with PHPs DIRECTORY_SEPARATOR.

```<code> $tmp_dir = "my_media". DIRECTORY_SEPARATOR . "photo" . DIRECTORY_SEPARATOR ;
</code>```

And second, to make sure you have permissions to write to that folder, let PHP create the folder instead.

For this to work, first delete the folder you created.

```<code>if(!is_dir($tmp_dir)){
  mkdir($tmp_dir);
  move_uploaded_file($tmp_name,$tmp_dir . basename($name));
}else{
  move_uploaded_file($tmp_name,$tmp_dir . basename($name));
}
</code>```

And last but not the least, you are open to SQL injection. Use prepared statements instead. Example

Body:
I'm building a media and I want my users to
 upload as many images as they like,But my problem
 is how to save or move this image to a folder
 called photo contain in folder called my_media,
 my_media folder contain my php files such as
 index.php and more,I can move this file to
 my_media folder once upload,But i don't want
 the file they for security purpose,please
 someone should fix my code thanks.

this my code

require_once ('connect.php');

if (isset($_POST['Submit'])) {

 $tmp_dir = "my_media/photo";
 //it will move to my_media if assign my_media only to the variable $tmp_dir
 //but don't work with  $tmp_dir = "my_media/photo"

 $tmp_name = $_FILES["image"]["tmp_name"];
 $name = $_FILES["image"]["name"];

move_uploaded_file($tmp_name,$tmp_dir . basename($name));

    //rename("my_media/photo","my_media/photo". basename($name));
$location=$name;
$fname=$_POST['first_name'];
$lname=$_POST['last_name'];

$sql = "INSERT INTO tbl_image (first_name, last_name, image_location)
VALUES ('$fname', '$lname', '$location')";
 $res = mysqli_query($con,$sql);
//with this my the image name is inserted into my database but not into the foldermy_media/photo
header("Location:imgview.php");
}

Body:
First of all, lets remove all / and replace them with PHPs DIRECTORY_SEPARATOR.

 $tmp_dir = "my_media". DIRECTORY_SEPARATOR . "photo" . DIRECTORY_SEPARATOR ;

And second, to make sure you have permissions to write to that folder, let PHP create the folder instead.

For this to work, first delete the folder you created.

if(!is_dir($tmp_dir)){
  mkdir($tmp_dir);
  move_uploaded_file($tmp_name,$tmp_dir . basename($name));
}else{
  move_uploaded_file($tmp_name,$tmp_dir . basename($name));
}

And last but not the least, you are open to SQL injection. Use prepared statements instead. Example


问:
How do you put a restriction on a variable?
I am trying to make an add and remove button that has an input that has a text type and it show numbers. The add and remove button work and it will show positive numbers and negative also. I don't want it to show negative numbers. How do I make it so it can't go lower than 0? Also I do not want the input to have a number type.

Here is my code:

```<code><button onclick="add();">ADD</button>
<button onclick="remove();">REMOVE</button>
<input type="text" id="inc">

<script>
var i = 0;
    function add() {
        if(i >= 0) {
            i++;
            document.getElementById('inc').value = i;
        } else {
            i = 0;
            document.getElementById('inc').value = i;
        }

    }
        function remove() {
        i--;
        document.getElementById('inc').value = i;
    }
        </script>
</code>```

答:
in the same way where you have set a constraint in the add() function, do the same thing for the remove() function by doing the processing only if i-1 >= 0 :

```<code> function remove() {
    if(i-1 >= 0) {
        i--;
        document.getElementById('inc').value = i;
    }
  }
</code>```

Body:
I am trying to make an add and remove button that has an input that has a text type and it show numbers. The add and remove button work and it will show positive numbers and negative also. I don't want it to show negative numbers. How do I make it so it can't go lower than 0? Also I do not want the input to have a number type.

Here is my code:

<button onclick="add();">ADD</button>
<button onclick="remove();">REMOVE</button>
<input type="text" id="inc">

Body:
in the same way where you have set a constraint in the add() function, do the same thing for the remove() function by doing the processing only if i-1 >= 0 :

 function remove() {
    if(i-1 >= 0) {
        i--;
        document.getElementById('inc').value = i;
    }
  }


问:
I have a classification project where some of the columns/features have more than 90% null values. How do I handle them?
In my classification problem, some of the features(~5) among 85 features have mostly null values (>90%). How do I handle these values? Do I,

1) Ignore these columns/features altogether

2) Try and impute these values, if so how?

3) Any other method?

I am starting with random forests and I am a newbie to this method, does random forest handle null values by itself? How can I implement this? how does random forest do this? Where can I learn about this - any references would be much welcome.

Thanks in advance.

答:
Have you tried running the neural-network on your dataset even though features are missing? A neural-network does not need all features to be present.

You can simply set all missing features values to 0 for the neural network, as neural networks don't see a difference between 0 and feature is missing. Why not you ask? If you set an input value to 0, that means all the connections from that input node will have a 0 value a well: adding nothing to the hidden neurons that are connected to that input node.

But before you try, ask yourself this question: if some feature is missing so often, is it of any importance to the dataset prediction?


答:
Just change your remove function so that it doesn't decrement lower than zero

```<code>function remove() {
    i = i > 0 ? i - 1 : 0;
    document.getElementById('inc').value = i;
}
</code>```

Title: How do you put a restriction on a variable?

Body:
Just change your remove function so that it doesn't decrement lower than zero

function remove() {
    i = i > 0 ? i - 1 : 0;
    document.getElementById('inc').value = i;
}


问:
How can I retrieve values from POST request payload in Java REST service?
I would like to send a post request from AngularJS application.
I call

```<code>var data = {name: "Dave", age: 18};
$http.post(serviceAddress + 'cxf/addPerson', data};
</code>```

Java CXF side:

```<code>@POST
public Response addPerson( @Context HttpServletRequest request ) {
    String name = request.getParameter("name");
    int age = Integer.parseInt(request.getParameter("age"));
    . . .
}
</code>```

I get null for name and age and request.getParameterMap is empty as well.

How can I get this values from request payload? My Chrome developer tools says it sends name and age in request payload. So the server should retrieve it.

Body:
I would like to send a post request from AngularJS application.
I call

var data = {name: "Dave", age: 18};
$http.post(serviceAddress + 'cxf/addPerson', data};

Java CXF side:

@POST
public Response addPerson( @Context HttpServletRequest request ) {
    String name = request.getParameter("name");
    int age = Integer.parseInt(request.getParameter("age"));
    . . .
}

I get null for name and age and request.getParameterMap is empty as well.

How can I get this values from request payload? My Chrome developer tools says it sends name and age in request payload. So the server should retrieve it.

Body: IOUtils.toString(request.getReader());


问:
Laravel auth() returns false on 404's
I had an issue with Laravel when it throws a 404 exception, or any kind of exception, the auth() helper returns null in these pages, 404, 400... any exception.

As someone suggested, I moved 2 middlewares to the globalgroup

```<code> \App\Http\Middleware\EncryptCookies::class,
 \Illuminate\Session\Middleware\StartSession::class,
</code>```

however, it caused another issue, it was logging me out everytime i refresh the page, when I moved these middlewares back logged in users stay logged in.

So now, I still need a way to use auth(), in 404 pages, it makes no sense that the navbar displays Please Login on 404 pages when the use is already logged in, that's really bad Laravel.

Actually the solution above suggested by many, cause lots of issues in the code, and detecting the authenticated user, I just did some tests, it was creating a new session upon every refresh.

答:
Issue is solved at my previous related question auth() method null on Exceptions

These middlewares should be moved and not copied to the global array. I had multiple instances, on web group and global group, which was causing the issue.

So copying the middlwares in App/Http/Kernel.php from the 'web' group to the 'middlewares' group will recreate the session on every refresh. I hope, someone will find this useful.

Title: Laravel auth() returns false on 404's

Body:
I had an issue with Laravel when it throws a 404 exception, or any kind of exception, the auth() helper returns null in these pages, 404, 400... any exception.

As someone suggested, I moved 2 middlewares to the globalgroup

 \App\Http\Middleware\EncryptCookies::class,
 \Illuminate\Session\Middleware\StartSession::class,

however, it caused another issue, it was logging me out everytime i refresh the page, when I moved these middlewares back logged in users stay logged in.

So now, I still need a way to use auth(), in 404 pages, it makes no sense that the navbar displays Please Login on 404 pages when the use is already logged in, that's really bad Laravel.

Actually the solution above suggested by many, cause lots of issues in the code, and detecting the authenticated user, I just did some tests, it was creating a new session upon every refresh.


问:
inputAccessoryView disappears after presenting UIViewController
I have a UICollectionViewController with an inputAccessoryView. Everything works great until I present a UIViewController, and then the accessory view disappears.  Trying to get basic Chat application features.

I have implemented in the collection view:

```<code>override var inputAccessoryView: UIView? {
    get {
        return inputContainerView
    }
}

override var canBecomeFirstResponder: Bool {
    return true
}

override func becomeFirstResponder() -> Bool {
    return true
}
</code>```

As suggested in multiple other threads, I also call (in the collection view),

```<code>view.resignFirstResponder()
view.inputAccessoryView?.reloadInputViews()
view.becomeFirstResponder()
</code>```

after dismissing the UIViewController but to no avail.  print(view.isFirstResponder) still prints false.  I have tried almost every combination of the above three lines in numerous different places in my code.  I think I'm missing something simple.

答: The animation to present and dismiss view controller might be causing issue or You haven't maintained a global ivar for the view you have setted as input accessory view. Try creating a readonly ivar for the accessoryview so only one instance is allocated and maintained through out VC life cycle. Then ensure to set it back to the textfields before calling reloadInputViews.</p>

Body:
I have a UICollectionViewController with an inputAccessoryView. Everything works great until I present a UIViewController, and then the accessory view disappears.  Trying to get basic Chat application features.

I have implemented in the collection view:

override var inputAccessoryView: UIView? {
    get {
        return inputContainerView
    }
}

override var canBecomeFirstResponder: Bool {
    return true
}

override func becomeFirstResponder() -> Bool {
    return true
}

As suggested in multiple other threads, I also call (in the collection view),

view.resignFirstResponder()
view.inputAccessoryView?.reloadInputViews()
view.becomeFirstResponder()

after dismissing the UIViewController but to no avail.  print(view.isFirstResponder) still prints false.  I have tried almost every combination of the above three lines in numerous different places in my code.  I think I'm missing something simple.


问:
Is a sync always required when a CUDA kernel's launch parameters are dependent on a prior kernel?
I have this attached pattern in my code a lot. Basically it amounts to a first kernel for filtering a large dataset, where the selected entries returned will be very sparse, and then a second kernel for performing a much more involved computation on the much-reduced dataset.

It seems like the cudaStreamSynchronize is almost superfluous, but I can't see any way around it.

Is there an alternative pattern that avoids the synchronization between kernels?

Would CUDA dynamic parallelism help in any way?

example code:

```<code>/* Pseudocode. Won't Compile */
/* Please ignore silly mistakes/syntax and inefficiant/incorrect simplifications */

__global__ void bar( const float * dataIn, float * dataOut, unsigned int * counter_ptr )
{
   < do some computation >
   if (bConditionalComputedAboveIsTrue)
   {
      const unsigned int ind = atomicInc(counter_ptr, (unsigned int)(-1));
      dataOut[ ind ] = resultOfAboveComputation;
   }
}

int foo( float * d_datain, float* d_tempbuffer, float* d_output, cudaStream_t stream  ){
   /* Initialize a counter that will be updated by the bar kernel */
   unsigned int * counter_ptr;
   cudaMalloc( &counter_ptr, sizeof( unsigned int) ); //< Create a Counter
   cudaMemsetAsync(counter_ptr, 0, sizeof(unsigned int), stream); //<Initially Set the Counter to 0
   dim3 threadsInit(16,16,1);
   dim3 gridInit(256, 1, 1);
   /* Launch the Filtering Kernel. This will update the value in counter_ptr*/
   bar<<< gridInit, threadsInit, 0, stream >>>( d_datain, d_tempbuffer, counter_ptr );
   /* Download the count and synchronize the stream */
   unsigned int count;
   cudaMemcpyAsync(&count, counter_ptr, sizeof(unsigned int), cudaMemcpyDeviceToHost, stream);
   cudaStreamSynchronize( stream ); //< Is there any way around this synchronize?
   /* Compute the grid parameters and launch a second kernel */
   dim3 bazThreads(128,1,1);
   dim3 bazGrid( count/128 + 1, 1, 1); //< Here I use the counter modified in the prior kernel to set the grid parameters
   baz<<< bazGrid, bazThreads, 0, stream >>>( d_tempbuffer, d_output );
   /* cleanup */
   cudaFree(counter_ptr);
}
</code>```

答:
Instead of varying the number of blocks in the second kernel, you could use a fixed block count and have the blocks adapt the amount of work they do.

E.g. launch a larger number of blocks, and have them exit early if no work remains. Or launch just enough blocks to fill the device, and have each block loop over the work to to. Grid-stride loops are a good way of doing this.

There is also the option of using dynamic parallelism to move the kernel launch itself (and thus the decision on the grid size) to the device.

Body:
I have this attached pattern in my code a lot. Basically it amounts to a first kernel for filtering a large dataset, where the selected entries returned will be very sparse, and then a second kernel for performing a much more involved computation on the much-reduced dataset.

It seems like the cudaStreamSynchronize is almost superfluous, but I can't see any way around it.

Is there an alternative pattern that avoids the synchronization between kernels?

Would CUDA dynamic parallelism help in any way?

example code:

/* Pseudocode. Won't Compile */
/* Please ignore silly mistakes/syntax and inefficiant/incorrect simplifications */

__global__ void bar( const float * dataIn, float * dataOut, unsigned int * counter_ptr )
{
   < do some computation >
   if (bConditionalComputedAboveIsTrue)
   {
      const unsigned int ind = atomicInc(counter_ptr, (unsigned int)(-1));
      dataOut[ ind ] = resultOfAboveComputation;
   }
}

int foo( float * d_datain, float* d_tempbuffer, float* d_output, cudaStream_t stream  ){
   /* Initialize a counter that will be updated by the bar kernel */
   unsigned int * counter_ptr;
   cudaMalloc( &counter_ptr, sizeof( unsigned int) ); //< Create a Counter
   cudaMemsetAsync(counter_ptr, 0, sizeof(unsigned int), stream); //<Initially Set the Counter to 0
   dim3 threadsInit(16,16,1);
   dim3 gridInit(256, 1, 1);
   /* Launch the Filtering Kernel. This will update the value in counter_ptr*/
   bar<<< gridInit, threadsInit, 0, stream >>>( d_datain, d_tempbuffer, counter_ptr );
   /* Download the count and synchronize the stream */
   unsigned int count;
   cudaMemcpyAsync(&count, counter_ptr, sizeof(unsigned int), cudaMemcpyDeviceToHost, stream);
   cudaStreamSynchronize( stream ); //< Is there any way around this synchronize?
   /* Compute the grid parameters and launch a second kernel */
   dim3 bazThreads(128,1,1);
   dim3 bazGrid( count/128 + 1, 1, 1); //< Here I use the counter modified in the prior kernel to set the grid parameters
   baz<<< bazGrid, bazThreads, 0, stream >>>( d_tempbuffer, d_output );
   /* cleanup */
   cudaFree(counter_ptr);
}


问:
Why isn't localStorage saving my variables?
My game is an idle one where you click protons, neutrons, and electrons and when you have enough of some, you can build hydrogen and so forth. I kind of got my local variables to work but now I am having issues with the buying stage.

Basically hydrogen costs 1 proton and one electron, when you click on the button, it runs the function SetHydrogen(), when it does that, it is supposed to run based off of the variable HydrogenCost. I am not sure if any of this is feasible.

```<code>var protons = Number(localStorage.setItem("ProtonS", Pcount));
var neutrons = Number(localStorage.NeutronS);
var electrons = Number(localStorage.ElectronS);
var hydrogens = Number(localStorage.HydrogenS);

function SaveVariables(){
  if (localStorage.getItem("ProtonS")){
    localStorage.setItem("ProtonS", Pcount);
    protons = Number(localStorage.ProtonS);
  } else {
    localStorage.ProtonS = Number(localStorage.ProtonS);
  }
  if (localStorage.NeutronS){
    localStorage.NeutronS = neutrons;
    neutrons = Number(localStorage.NeutronS);
  } else {
    neutrons = Number(localStorage.NeutronS);
  }
  if (localStorage.ElectronS){
    localStorage.ElectronS = electrons;
    electrons = Number(localStorage.ElectronS);
  } else {
    electrons = Number(localStorage.ElectronS);
  }
  if (localStorage.HydrogenS){
    localStorage.HydrogenS = document.getElementByID("HydrogenTotal").innerHTML;
    hydrogens = Number(localStorage.HydrogenS);
  } else {
    hydrogens = 0;
  }
}

function LoadVariables(){
  buying = 0;
  CanUBuy = false;
  protons = Number(localStorage.ProtonS);
  neutrons = Number(localStorage.NeutronS);
  electrons = Number(localStorage.ElectronS);
  hydrogens = Number(localStorage.HydrogenS);
}

function update(){
    protonTap.onmousedown = function() {protons = protons + 1};
    neutronTap.onmousedown = function() {neutrons = neutrons + 1};
    electronTap.onmousedown = function() {electrons = electrons + 1};

};
function draw(){
    ProtonsTotal.value = protons.toFixed(0);
    NeutronsTotal.value = neutrons.toFixed(0);
    ElectronsTotal.value = electrons.toFixed(0);
    console.log(hydrogens);
    console.log(CanUBuy);
    console.log(Pcount);
};
var mainloop = function() {update(), draw(), SaveVariables()};
var buying = 0;

function SetHydrogen(){
  buying = 1;
  HydrogenCost.buy;
  if (CanUBuy = true){
    HydrogenTotal.value ++;
    buying = 0;
    CanUBuy = false;
  } else {
    buying = 0;
  }
}

function reset(){
  CanUBuy = false;
  protons = 0;
  neutrons = 0;
  electrons = 0;
  hydrogens = 0;
  buying = 0;
}

setInterval(mainloop, 16);

var CanUBuy = false;
var HydrogenCost = new buy(1,0,1);

function buy(ProtonCost, NeutronCost, ElectronCost){
  if (buying = 1){
    this.pCost = ProtonCost;
    this.nCost = NeutronCost;
    this.eCost = ElectronCost;

    if (protons >= ProtonCost && neutrons >= NeutronCost && electrons >= ElectronCost) {
      CanUBuy = true;
      protons = protons - this.pCost;
      neutrons = neutrons - this.nCost;
      electrons = electrons - this.eCost;
    } else{
      CanUBuy = false;
      alert("You don't have enough money");
    }
  } else if (buying = 0) {
    buying = 0;
  }
}

if(!localStorage.getItem('start')){
    localStorage.setItem('start', Date.now());
 }
  var start = parseInt(localStorage.getItem('start'));
  setInterval(function(){
     ffs.value = ~~((Date.now() - start)/1e3);

  }, 1e3);
</code>```

答:
At first, i think you should rethink your overall structure. You could shorten your code and make it reusable through OOP:

```<code>function stored(name,startvalue){
  this.name=name;
  this.value=+localStorage.getItem(name) || startvalue || 0;
}
stored.prototype={
    change:function(by){
      this.value+=by;
      localStorage.setItem(this.name,this.value);
    },
    set:function(to){
      this.value=to;
      localStorage.setItem(this.name,this.value);
    },
   valueOf:function(){ return this.value;},
};
</code>```

So you can do:

```<code>var neutrons=new stored("neutrons");
alert(+neutrons);//0, 5 on reload
neutrons.set(5);
alert(+neutrons);//5
</code>```

Note the + to convert the stored object to its value.

A hydrogen function could look like this:

```<code>var protons=new stored("protons",10);
var electrons=new stored("electrons",10);
var hydrogens=new stored("hydrogens");
hydrogens.buy=function(){
 if(+protons && +neutrons){
   protons.change(-1);
   neutrons.change(-1);
   this.change(1);
 }else{
   alert("impossible. Sorry :(");
 }
}

hydrogens.buy();//test
</code>```

http://jsbin.com/pozinotida/1/edit?js

Body:
My game is an idle one where you click protons, neutrons, and electrons and when you have enough of some, you can build hydrogen and so forth. I kind of got my local variables to work but now I am having issues with the buying stage.

Basically hydrogen costs 1 proton and one electron, when you click on the button, it runs the function SetHydrogen(), when it does that, it is supposed to run based off of the variable HydrogenCost. I am not sure if any of this is feasible.

var protons = Number(localStorage.setItem("ProtonS", Pcount));
var neutrons = Number(localStorage.NeutronS);
var electrons = Number(localStorage.ElectronS);
var hydrogens = Number(localStorage.HydrogenS);

function SaveVariables(){
  if (localStorage.getItem("ProtonS")){
    localStorage.setItem("ProtonS", Pcount);
    protons = Number(localStorage.ProtonS);
  } else {
    localStorage.ProtonS = Number(localStorage.ProtonS);
  }
  if (localStorage.NeutronS){
    localStorage.NeutronS = neutrons;
    neutrons = Number(localStorage.NeutronS);
  } else {
    neutrons = Number(localStorage.NeutronS);
  }
  if (localStorage.ElectronS){
    localStorage.ElectronS = electrons;
    electrons = Number(localStorage.ElectronS);
  } else {
    electrons = Number(localStorage.ElectronS);
  }
  if (localStorage.HydrogenS){
    localStorage.HydrogenS = document.getElementByID("HydrogenTotal").innerHTML;
    hydrogens = Number(localStorage.HydrogenS);
  } else {
    hydrogens = 0;
  }
}

function LoadVariables(){
  buying = 0;
  CanUBuy = false;
  protons = Number(localStorage.ProtonS);
  neutrons = Number(localStorage.NeutronS);
  electrons = Number(localStorage.ElectronS);
  hydrogens = Number(localStorage.HydrogenS);
}

function update(){
    protonTap.onmousedown = function() {protons = protons + 1};
    neutronTap.onmousedown = function() {neutrons = neutrons + 1};
    electronTap.onmousedown = function() {electrons = electrons + 1};

};
function draw(){
    ProtonsTotal.value = protons.toFixed(0);
    NeutronsTotal.value = neutrons.toFixed(0);
    ElectronsTotal.value = electrons.toFixed(0);
    console.log(hydrogens);
    console.log(CanUBuy);
    console.log(Pcount);
};
var mainloop = function() {update(), draw(), SaveVariables()};
var buying = 0;

function SetHydrogen(){
  buying = 1;
  HydrogenCost.buy;
  if (CanUBuy = true){
    HydrogenTotal.value ++;
    buying = 0;
    CanUBuy = false;
  } else {
    buying = 0;
  }
}

function reset(){
  CanUBuy = false;
  protons = 0;
  neutrons = 0;
  electrons = 0;
  hydrogens = 0;
  buying = 0;
}

setInterval(mainloop, 16);

var CanUBuy = false;
var HydrogenCost = new buy(1,0,1);

function buy(ProtonCost, NeutronCost, ElectronCost){
  if (buying = 1){
    this.pCost = ProtonCost;
    this.nCost = NeutronCost;
    this.eCost = ElectronCost;

    if (protons >= ProtonCost && neutrons >= NeutronCost && electrons >= ElectronCost) {
      CanUBuy = true;
      protons = protons - this.pCost;
      neutrons = neutrons - this.nCost;
      electrons = electrons - this.eCost;
    } else{
      CanUBuy = false;
      alert("You don't have enough money");
    }
  } else if (buying = 0) {
    buying = 0;
  }
}

if(!localStorage.getItem('start')){
    localStorage.setItem('start', Date.now());
 }
  var start = parseInt(localStorage.getItem('start'));
  setInterval(function(){
     ffs.value = ~~((Date.now() - start)/1e3);

  }, 1e3);

Body:
At first, i think you should rethink your overall structure. You could shorten your code and make it reusable through OOP:

function stored(name,startvalue){
  this.name=name;
  this.value=+localStorage.getItem(name) || startvalue || 0;
}
stored.prototype={
    change:function(by){
      this.value+=by;
      localStorage.setItem(this.name,this.value);
    },
    set:function(to){
      this.value=to;
      localStorage.setItem(this.name,this.value);
    },
   valueOf:function(){ return this.value;},
};

So you can do:

var neutrons=new stored("neutrons");
alert(+neutrons);//0, 5 on reload
neutrons.set(5);
alert(+neutrons);//5

Note the + to convert the stored object to its value.

A hydrogen function could look like this:

var protons=new stored("protons",10);
var electrons=new stored("electrons",10);
var hydrogens=new stored("hydrogens");
hydrogens.buy=function(){
 if(+protons && +neutrons){
   protons.change(-1);
   neutrons.change(-1);
   this.change(1);
 }else{
   alert("impossible. Sorry :(");
 }
}

hydrogens.buy();//test

http://jsbin.com/pozinotida/1/edit?js


问:
ssh run script in background and get its pid

Hi

I need to get the pid of the script run through ssh.
```

ssh some.host './script &' #get the pid of it

```

Some code I was trying so far:
```

ssh some.host './script & ; echo $!'

```
```

nohup ssh some.host '( ./script  & ); echo $! > thePID'; ssh some.host 'cat thePID'

```

Any sugestion?

答:
As far as I remember, it should be this -

```<code>./script & echo $!
</code>```

without

```<code>;
</code>```

Body:
Hi

I need to get the pid of the script run through ssh.

ssh some.host './script &' #get the pid of it

Some code I was trying so far:

ssh some.host './script & ; echo $!'

nohup ssh some.host '( ./script  & ); echo $! > thePID'; ssh some.host 'cat thePID'

Any sugestion?

Body:
As far as I remember, it should be this -

./script & echo $!

without

;


问:
Array number that are multiples of 3
I need to get all number that multiples of 3.
Can someone help me to write it?  Here is what I have so far:</p>

```<code>int[] myList = { 1, 2, 3, 4, 5, 6, 7, 8, 9, };

public class Main {
public static void main(String[] args) {
    int[] myList = { 1, 2, 3, 4, 5, 6, 7, 8, 9, };
    int share = myList[0];
    for (int i / 3; i / myList.length;) {

        }
    }
    System.out.println(i / 3 );

}

}
</code>```

答:
Okay What I think you want to do is have an array with a set of numbers, then you want your program take those numbers and save them into an array. Then print that array after the loop is done.

Remember that with these kinds of problems you have the known size of the array, but you don't know how many answers you are going to get. So I recommend that you use List<>. Their sizes are not set and they can grow depending on how many answers you are getting back.

Side Note : Make sure that you use the correct imports

```<code>import java.util.ArrayList;
import java.util.List;

public static void main(String[] args) {

    int [] listOfNumbers = {1,2,3,4,5,6,7,8,9}; // The list of numbers that you have
    List<Integer> divisableBy3 = new ArrayList<Integer>();
    //The loop go through the array list and check the numbers.

    for (int i = 1; i < listOfNumbers.length; i++) { // You already know that 0 is not divisable by 3.
        int temp = listOfNumbers[i];

        if (temp %3 == 0) { //Checking that you number is divisible by 3
            divisableBy3.add(temp);
        }
    }

    //For each loop to print out the require information.
    for (int num : divisableBy3) {
        System.out.println("Number divisable by 3 : "+num);
    }
}
</code>```

Remember that checking to see what a number is divisible by you don't use the "/" symbol but you use the modulus operator "%".

```<code>       temp %3 == 0
</code>```

Title: Array number that are multiples of 3

Body:
I need to get all number that multiples of 3.
Can someone help me to write it?  Here is what I have so far:

int[] myList = { 1, 2, 3, 4, 5, 6, 7, 8, 9, };

public class Main {
public static void main(String[] args) {
    int[] myList = { 1, 2, 3, 4, 5, 6, 7, 8, 9, };
    int share = myList[0];
    for (int i / 3; i / myList.length;) {

        }
    }
    System.out.println(i / 3 );

}

}

Body:
Okay What I think you want to do is have an array with a set of numbers, then you want your program take those numbers and save them into an array. Then print that array after the loop is done.

Remember that with these kinds of problems you have the known size of the array, but you don't know how many answers you are going to get. So I recommend that you use List<>. Their sizes are not set and they can grow depending on how many answers you are getting back.

Side Note : Make sure that you use the correct imports

import java.util.ArrayList;
import java.util.List;

public static void main(String[] args) {

    int [] listOfNumbers = {1,2,3,4,5,6,7,8,9}; // The list of numbers that you have
    List<Integer> divisableBy3 = new ArrayList<Integer>();
    //The loop go through the array list and check the numbers.

    for (int i = 1; i < listOfNumbers.length; i++) { // You already know that 0 is not divisable by 3.
        int temp = listOfNumbers[i];

        if (temp %3 == 0) { //Checking that you number is divisible by 3
            divisableBy3.add(temp);
        }
    }

    //For each loop to print out the require information.
    for (int num : divisableBy3) {
        System.out.println("Number divisable by 3 : "+num);
    }
}

Remember that checking to see what a number is divisible by you don't use the "/" symbol but you use the modulus operator "%".

       temp %3 == 0


问:
Why did Asp.net MVC team choose "../../Content/Site.css" rather than "~/Content/Site.css" in Site.Master page?
```<code><link href="../../Content/Site.css" rel="stylesheet" type="text/css" />
</code>```

The above code shows an external css inclusion tag declared in  Site.Master template.

My question: why did the Asp.net MVC team choose that way rather than using "~/Content/Site.css" ?

Is it the best practice? I am sorry, I am a newbie and still learning to improve my skill.

EDIT 1: I want to make it clearer that "~/" must be passed in to url-resolving method first. Thus, I can rewrite my question as follows:

Why did the team choose "../.." rather than "~/" resolved by url resolver?

答: ~ is a asp.net thing and doesn't make sense in pure html. In webforms that is handled by turning the tag into a server control, that can translate ~ into a absolute path, while you in MVC would have to call some method yourself. Some method being Server.MapPath for instance

Body:
<link href="../../Content/Site.css" rel="stylesheet" type="text/css" />

The above code shows an external css inclusion tag declared in  Site.Master template.

My question: why did the Asp.net MVC team choose that way rather than using "~/Content/Site.css" ?

Is it the best practice? I am sorry, I am a newbie and still learning to improve my skill.

EDIT 1: I want to make it clearer that "~/" must be passed in to url-resolving method first. Thus, I can rewrite my question as follows:

Why did the team choose "../.." rather than "~/" resolved by url resolver?


问:
Python pandas - read_csv Dataframe is dropping values from columns
first off I know the below sample is off in indentation and if someone can point me in the right direction for posting DataFrames correctly I'd be very grateful.

Now, I have a dataframe as below:

Ticker_x Date Close_x Ticker_y Close_y Lead_Lag Ticker 15M_Trend Bollinger_1SD Bollinger_2SD Bollinger_and_Trend_1SD Bollinger_and_Trend_2SD
ES M7 6/2/2017 3:29 2433.75 VX M7-CF 11.6 N
ES M7 6/2/2017 4:29 2434.75 VX M7-CF 11.6 Short
ES M7 6/2/2017 5:29 2435 VX M7-CF 11.55 N
ES M7 6/2/2017 6:29 2434.25 VX M7-CF 11.57 N
ES M7 6/2/2017 7:29 2430.25 VX M7-CF 11.7 Short
ES M7 6/2/2017 8:29 2430.75 VX M7-CF 11.58 Short
ES M7 6/2/2017 9:29 2433.25 VX M7-CF 11.63 Short
ES M7 6/2/2017 10:29 2436.75 VX M7-CF 11.61 Short
ES M7 6/2/2017 11:29 2436.75 VX M7-CF 11.57 Short
ES M7 6/2/2017 12:29 2435.75 VX M7-CF 11.67 Short
ES M7 6/2/2017 13:29 2437.75 VX M7-CF 11.64 Short
ES M7 6/2/2017 14:29 2437.75 VX M7-CF 11.63 Short       ```
</div>
</div>
</p>

<p>I'm creating this dataframe from read_csv function of another file, and only including columns outlined below. Note that I'm picking up the most recent file from a folder with 'glob':</p>

```filenameA = max(glob.iglob(r"C:\Users\cost9\OneDrive\Documents\PYTHON\Daily Tasks\Pairs Trading\VX_ES\CSV\15M\Lead_Lag\*.csv"))

AggregatedA = pd.read_csv(filenameA, usecols=['Ticker_x', 'Date', 'Close_x', 'Ticker_y', 'Close_y', 'Lead_Lag', 'Ticker', '15M_Trend', 'Bollinger_1SD', 'Bollinger_2SD', 'Bollinger_and_Trend_1SD', 'Bollinger_and_Trend_2SD'])
p2 = r"C:\Users\cost9\OneDrive\Documents\PYTHON\Daily Tasks\Individual Trading\VX\CSV\Aggregated\VX_ES_15M\blah2.csv"
AggregatedA.to_csv(path_or_buf = p2)
```

<p>So that new file 'blah2' is the csv file shown above. You'll note that like 7 or 8 columns on the far right are blank. These should not be blank. They are not blank in the original file I picked up from 'filenameA'. </p>

<p>I.e. they have a bunch of values for 'Ticker', '15M_Trend' and the other columns. For some reason pandas aren't picking up those values and I'm not sure why. Help is much appreciated!</p>

<p>edit: here's the original lines of the dataframe:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>Ticker_x Date Open_x High_x Low_x Close_x Volume_x Open Interest_x Ticker_y Open_y High_y Low_y Close_y Volume_y Open Interest_y ES_returns VX_returns Beta Pairs_Spread zscore Pairs_Spread_Mean Pairs_Spread_sdev ES_percent_change ES_difference VX_percent_change ES_CC VX_CC pairs_spread pairs_zscore ES_Inverse_price ES__Inverse_percent_change Inverse_ES_CC Inverse_pairs_spread Inverse_pairs_zscore Lead_Lag Ticker Open High Low Close Volume Open Interest Index_Num Rolling_OLS_Coefficient 15M_Long Upper_Sdev_Value Lower_Sdev_Value Intercept Middle Sdev Lower_Sdev_value 15M_Trend Rolling_mean Rolling_std Upper_Band Lower_Band Upper_Band_2 Lower_Band_2 Bollinger_1SD Bollinger_2SD Bollinger_and_Trend_1SD Bollinger_and_Trend_2SD Trend_and_LL
ES M7 6/2/2017 3:29 2433.25 2433.75 2433 2433.75 3419 0 VX M7-CF 11.55 11.6 11.53 11.6 253 0 0 0.001727116 -6.946994692     0 0 0.001727116 -0.27013895 -0.27013895 2514.335138 2.733208694 2138.25 0 0.270990395 2218.835138 -1.144384967 N VX M7-CF 11.55 11.6 11.53 11.6 253 0 1868 -0.006269114  27.09349175  23.18140592 23.10868419 3.984807553 19.12387664 Short 11.7912 0.1573199 11.9485199 11.6338801 12.1058398 11.4765602 Long N N N N
ES M7 6/2/2017 4:29 2435 2435.5 2434.75 2434.75 2847 0 VX M7-CF 11.59 11.6 11.55 11.6 118 0 0.000410889 0 -6.94464418     0.000410889 1 0 -0.434541317 -0.434541317 2515.307872 2.759879939 2137.25 -0.000467672 0.43443517 2217.807872 -1.197621083 Short VX M7-CF 11.59 11.6 11.55 11.6 118 0 1869 -0.006344733  27.26010073  23.31610124 23.24250234 4.017598384 19.22490396 Short 11.7868 0.159558575 11.94635857 11.62724143 12.10591715 11.46768285 Long N N N Short
ES M7 6/2/2017 5:29 2436.25 2436.5 2435 2435 5979 0 VX M7-CF 11.55 11.6 11.5 11.55 716 0 0.00010268 -0.004310345 -6.945304375     0.00010268 0.25 -0.004310345 -0.364155097 -0.364155097 2515.218266 2.75742302 2137 -0.000116973 0.364203518 2217.218266 -1.228176348 N VX M7-CF 11.55 11.6 11.5 11.55 716 0 1870 -0.006422122  27.43061644  23.45376171 23.37958619 4.051030244 19.32855595 Short 11.7814 0.162944964 11.94434496 11.61845504 12.10728993 11.45551007 Long N N N N
ES M7 6/2/2017 6:29 2434.5 2435 2433.75 2434.25 11821 0 VX M7-CF 11.5 11.65 11.5 11.57 1919 0 -0.000308008 0.001731602 -6.943255051     -0.000308008 -0.75 0.001731602 -0.391364705 -0.391364705 2514.583461 2.74001741 2137.75 0.000350959 0.391371805 2218.083461 -1.183339232 N VX M7-CF 11.5 11.65 11.5 11.57 1919 0 1871 -0.006492588  27.58935246  23.57945638 23.50433714 4.08501532 19.41932182 Short 11.7764 0.165551151 11.94195115 11.61084885 12.1075023 11.4452977 Long N N N N
ES M7 6/2/2017 7:29 2431.25 2431.75 2430 2430.25 16785 0 VX M7-CF 11.6 11.75 11.58 11.7 3737 0 -0.001643217 0.011235955 -6.941089619     -0.001643217 -4 0.011235955 -0.795190709 -0.795190709 2511.460749 2.654396241 2141.75 0.001871126 0.79514286 2222.960749 -0.930583022 Short VX M7-CF 11.6 11.75 11.58 11.7 3737 0 1872 -0.006552806  27.73075716  23.68800858 23.61134075 4.119416411 19.49192434 Short 11.776 0.165714286 11.94171429 11.61028571 12.10742857 11.44457143 N N N N Short
ES M7 6/2/2017 8:29 2430.25 2431 2429 2430.75 37511 0 VX M7-CF 11.7 11.8 11.53 11.58 15635 0 0.00020574 -0.01025641 -6.944443722     0.00020574 0.5 -0.01025641 -0.801967629 -0.801967629 2511.166658 2.646332626 2141.25 -0.000233454 0.801808413 2221.666658 -0.997646802 Short VX M7-CF 11.7 11.8 11.53 11.58 15635 0 1873 -0.006629471  27.90272657  23.82506069 23.74829141 4.154435156 19.59385626 Short 11.773 0.167907287 11.94090729 11.60509271 12.10881457 11.43718543 Long N N N Short
ES M7 6/2/2017 9:29 2432.25 2433.75 2432.25 2433.25 26047 0 VX M7-CF 11.55 11.7 11.55 11.63 7148 0 0.001028489 0.004317789 -6.902663206     0.001028489 2.5 0.004317789 -0.50559849 -0.50559849 2513.527973 2.711077152 2138.75 -0.001167542 0.506119457 2219.027973 -1.134391675 Short VX M7-CF 11.55 11.7 11.55 11.63 7148 0 1874 -0.006703266  28.06957526  23.95751485 23.87955587 4.190019391 19.68953648 Short 11.7706 0.169096157 11.93969616 11.60150384 12.10879231 11.43240769 N N N N Short
ES M7 6/2/2017 10:29 2435.75 2437 2435.5 2436.75 31594 0 VX M7-CF 11.65 11.65 11.55 11.61 5090 0 0.001438405 -0.00171969 -6.862573345     0.001438405 3.5 -0.00171969 -0.494655304 -0.494655304 2516.424477 2.790495933 2135.25 -0.00163647 0.495088995 2214.924477 -1.347047627 Short VX M7-CF 11.65 11.65 11.55 11.61 5090 0 1875 -0.006773515  28.23118528  24.08370058 24.00506007 4.226125209 19.77893486 Short 11.7608 0.163729992 11.92452999 11.59707001 12.08825998 11.43334002 N N N N Short
ES M7 6/2/2017 11:29 2436 2437 2435.5 2436.75 25538 0 VX M7-CF 11.65 11.65 11.55 11.57 2278 0 0 -0.003445306 -6.86522263     0 0 -0.003445306 -0.46654779 -0.46654779 2516.180626 2.783809828 2135.25 0 0.466999626 2214.680626 -1.359684729 Short VX M7-CF 11.65 11.65 11.55 11.57 2278 0 1876 -0.00683482  28.37745101  24.19388406 24.11480519 4.262645818 19.85215938 Short 11.7512 0.160466666 11.91166667 11.59073333 12.07213333 11.43026667 Long N N N Short
ES M7 6/2/2017 12:29 2437.75 2438.75 2435.5 2435.75 37037 0 VX M7-CF 11.58 11.69 11.55 11.67 4309 0 -0.000410383 0.008643042 -6.890566028     -0.000410383 -1 0.008643042 -0.503091577 -0.503091577 2516.162906 2.783323958 2136.25 0.000468329 0.503595438 2216.662906 -1.25695683 Short VX M7-CF 11.58 11.69 11.55 11.67 4309 0 1877 -0.006883805  28.50205329  24.28297379 24.20263978 4.299413516 19.90322626 Short 11.7436 0.154929345 11.89852935 11.58867065 12.05345869 11.43374131 N N N N Short
ES M7 6/2/2017 13:29 2437.75 2438.5 2437 2437.75 26228 0 VX M7-CF 11.68 11.7 11.55 11.64 8570 0 0.000821102 -0.002570694 -6.88244494     0.000821102 2 -0.002570694 -0.520801285 -0.520801285 2517.861659 2.82990182 2134.25 -0.00093622 0.521308056 2214.361659 -1.376214577 Short VX M7-CF 11.68 11.7 11.55 11.64 8570 0 1878 -0.006929786  28.62236572  24.3666349 24.2859722 4.336393523 19.94957867 Short 11.734 0.145728291 11.87972829 11.58827171 12.02545658 11.44254342 N N N N Short
ES M7 6/2/2017 14:29 2437.75 2437.75 2437.75 2437.75 1 0 VX M7-CF 11.6 11.7 11.55 11.63 28177 0 0 -0.000859107 -6.904693941     0 0 -0.000859107 -0.516701901 -0.516701901 2518.051591 2.835109521 2134.25 0 0.517232222 2214.551591 -1.36637174 Short VX M7-CF 11.6 11.7 11.55 11.63 28177 0 1879 -0.006969382  28.73142917  24.4389793 24.35792539 4.37350378 19.98442161 Short 11.724 0.13474087 11.85874087 11.58925913 11.99348174 11.45451826 N N N N Short</code>```

EDIT: Here's the new code, based on the below suggestion:

```<code>AggregatedA = pd.read_csv(max(glob.iglob(r"C:\Users\cost9\OneDrive\Documents\PYTHON\Daily Tasks\Pairs Trading\VX_ES\CSV\15M\Lead_Lag\*.csv")), usecols=['Ticker_x', 'Date', 'Close_x', 'Ticker_y', 'Close_y', 'Lead_Lag', 'Ticker', '15M_Trend', 'Bollinger_1SD', 'Bollinger_2SD', 'Bollinger_and_Trend_1SD', 'Bollinger_and_Trend_2SD'], delimiter='\t')

AggregatedA.to_csv(r"C:\Users\cost9\OneDrive\Documents\PYTHON\Daily Tasks\Individual Trading\VX\CSV\Aggregated\VX_ES_15M\blah2.csv")
</code>```

Which gives the error:

```<code>ValueError: Usecols do not match names.
</code>```

edit: I also tried using delimiter=',' rather than delimiter='\t', which got rid of the error. However, the right columns remain blank.

答:
Assuming that the input is as given, it is surprising that pandas parses the dataframe at all, as the delimiter should be given explicitly. Doing that, the code works as it should. If in.txt contains the lines, you provided, then running

```<code>In [26]: AggregatedA = pd.read_csv('in.txt', usecols=['Ticker_x', 'Date', 'Close_x', 'Ticker_y', 'Close_y', 'Lead_Lag', 'Ticker', '15M_Trend', 'Bollinger_1SD', 'Bollinger_2SD', 'Bollinger_and_Trend_1SD', 'Bollinger_and_Trend_2SD'], delimiter='\t')

In [25]: AggregatedA.to_csv('out.txt')
</code>```

will give an out.txt with the following contents:

```<code>$ cat out.txt
,Ticker_x,Date,Close_x,Ticker_y,Close_y,Lead_Lag,Ticker,15M_Trend,Bollinger_1SD,Bollinger_2SD,Bollinger_and_Trend_1SD,Bollinger_and_Trend_2SD
0,ES M7,6/2/2017 3:29,2433.75,VX M7-CF,11.6,N,VX M7-CF,Short,Long,N,N,N
1,ES M7,6/2/2017 4:29,2434.75,VX M7-CF,11.6,Short,VX M7-CF,Short,Long,N,N,N
2,ES M7,6/2/2017 5:29,2435.0,VX M7-CF,11.55,N,VX M7-CF,Short,Long,N,N,N
3,ES M7,6/2/2017 6:29,2434.25,VX M7-CF,11.57,N,VX M7-CF,Short,Long,N,N,N
4,ES M7,6/2/2017 7:29,2430.25,VX M7-CF,11.7,Short,VX M7-CF,Short,N,N,N,N
5,ES M7,6/2/2017 8:29,2430.75,VX M7-CF,11.58,Short,VX M7-CF,Short,Long,N,N,N
6,ES M7,6/2/2017 9:29,2433.25,VX M7-CF,11.63,Short,VX M7-CF,Short,N,N,N,N
7,ES M7,6/2/2017 10:29,2436.75,VX M7-CF,11.61,Short,VX M7-CF,Short,N,N,N,N
8,ES M7,6/2/2017 11:29,2436.75,VX M7-CF,11.57,Short,VX M7-CF,Short,Long,N,N,N
9,ES M7,6/2/2017 12:29,2435.75,VX M7-CF,11.67,Short,VX M7-CF,Short,N,N,N,N
10,ES M7,6/2/2017 13:29,2437.75,VX M7-CF,11.64,Short,VX M7-CF,Short,N,N,N,N
11,ES M7,6/2/2017 14:29,2437.75,VX M7-CF,11.63,Short,VX M7-CF,Short,N,N,N,N
</code>```

Body:
first off I know the below sample is off in indentation and if someone can point me in the right direction for posting DataFrames correctly I'd be very grateful.

Now, I have a dataframe as below:

Ticker_x Date Close_x Ticker_y Close_y Lead_Lag Ticker 15M_Trend Bollinger_1SD Bollinger_2SD Bollinger_and_Trend_1SD Bollinger_and_Trend_2SD
ES M7 6/2/2017 3:29 2433.75 VX M7-CF 11.6 N
ES M7 6/2/2017 4:29 2434.75 VX M7-CF 11.6 Short
ES M7 6/2/2017 5:29 2435 VX M7-CF 11.55 N
ES M7 6/2/2017 6:29 2434.25 VX M7-CF 11.57 N
ES M7 6/2/2017 7:29 2430.25 VX M7-CF 11.7 Short
ES M7 6/2/2017 8:29 2430.75 VX M7-CF 11.58 Short
ES M7 6/2/2017 9:29 2433.25 VX M7-CF 11.63 Short
ES M7 6/2/2017 10:29 2436.75 VX M7-CF 11.61 Short
ES M7 6/2/2017 11:29 2436.75 VX M7-CF 11.57 Short
ES M7 6/2/2017 12:29 2435.75 VX M7-CF 11.67 Short
ES M7 6/2/2017 13:29 2437.75 VX M7-CF 11.64 Short
ES M7 6/2/2017 14:29 2437.75 VX M7-CF 11.63 Short

I'm creating this dataframe from read_csv function of another file, and only including columns outlined below. Note that I'm picking up the most recent file from a folder with 'glob':

filenameA = max(glob.iglob(r"C:\Users\cost9\OneDrive\Documents\PYTHON\Daily Tasks\Pairs Trading\VX_ES\CSV\15M\Lead_Lag\*.csv"))

AggregatedA = pd.read_csv(filenameA, usecols=['Ticker_x', 'Date', 'Close_x', 'Ticker_y', 'Close_y', 'Lead_Lag', 'Ticker', '15M_Trend', 'Bollinger_1SD', 'Bollinger_2SD', 'Bollinger_and_Trend_1SD', 'Bollinger_and_Trend_2SD'])
p2 = r"C:\Users\cost9\OneDrive\Documents\PYTHON\Daily Tasks\Individual Trading\VX\CSV\Aggregated\VX_ES_15M\blah2.csv"
AggregatedA.to_csv(path_or_buf = p2)

So that new file 'blah2' is the csv file shown above. You'll note that like 7 or 8 columns on the far right are blank. These should not be blank. They are not blank in the original file I picked up from 'filenameA'.

I.e. they have a bunch of values for 'Ticker', '15M_Trend' and the other columns. For some reason pandas aren't picking up those values and I'm not sure why. Help is much appreciated!

edit: here's the original lines of the dataframe:

Ticker_x Date Open_x High_x Low_x Close_x Volume_x Open Interest_x Ticker_y Open_y High_y Low_y Close_y Volume_y Open Interest_y ES_returns VX_returns Beta Pairs_Spread zscore Pairs_Spread_Mean Pairs_Spread_sdev ES_percent_change ES_difference VX_percent_change ES_CC VX_CC pairs_spread pairs_zscore ES_Inverse_price ES__Inverse_percent_change Inverse_ES_CC Inverse_pairs_spread Inverse_pairs_zscore Lead_Lag Ticker Open High Low Close Volume Open Interest Index_Num Rolling_OLS_Coefficient 15M_Long Upper_Sdev_Value Lower_Sdev_Value Intercept Middle Sdev Lower_Sdev_value 15M_Trend Rolling_mean Rolling_std Upper_Band Lower_Band Upper_Band_2 Lower_Band_2 Bollinger_1SD Bollinger_2SD Bollinger_and_Trend_1SD Bollinger_and_Trend_2SD Trend_and_LL
ES M7 6/2/2017 3:29 2433.25 2433.75 2433 2433.75 3419 0 VX M7-CF 11.55 11.6 11.53 11.6 253 0 0 0.001727116 -6.946994692     0 0 0.001727116 -0.27013895 -0.27013895 2514.335138 2.733208694 2138.25 0 0.270990395 2218.835138 -1.144384967 N VX M7-CF 11.55 11.6 11.53 11.6 253 0 1868 -0.006269114  27.09349175  23.18140592 23.10868419 3.984807553 19.12387664 Short 11.7912 0.1573199 11.9485199 11.6338801 12.1058398 11.4765602 Long N N N N
ES M7 6/2/2017 4:29 2435 2435.5 2434.75 2434.75 2847 0 VX M7-CF 11.59 11.6 11.55 11.6 118 0 0.000410889 0 -6.94464418     0.000410889 1 0 -0.434541317 -0.434541317 2515.307872 2.759879939 2137.25 -0.000467672 0.43443517 2217.807872 -1.197621083 Short VX M7-CF 11.59 11.6 11.55 11.6 118 0 1869 -0.006344733  27.26010073  23.31610124 23.24250234 4.017598384 19.22490396 Short 11.7868 0.159558575 11.94635857 11.62724143 12.10591715 11.46768285 Long N N N Short
ES M7 6/2/2017 5:29 2436.25 2436.5 2435 2435 5979 0 VX M7-CF 11.55 11.6 11.5 11.55 716 0 0.00010268 -0.004310345 -6.945304375     0.00010268 0.25 -0.004310345 -0.364155097 -0.364155097 2515.218266 2.75742302 2137 -0.000116973 0.364203518 2217.218266 -1.228176348 N VX M7-CF 11.55 11.6 11.5 11.55 716 0 1870 -0.006422122  27.43061644  23.45376171 23.37958619 4.051030244 19.32855595 Short 11.7814 0.162944964 11.94434496 11.61845504 12.10728993 11.45551007 Long N N N N
ES M7 6/2/2017 6:29 2434.5 2435 2433.75 2434.25 11821 0 VX M7-CF 11.5 11.65 11.5 11.57 1919 0 -0.000308008 0.001731602 -6.943255051     -0.000308008 -0.75 0.001731602 -0.391364705 -0.391364705 2514.583461 2.74001741 2137.75 0.000350959 0.391371805 2218.083461 -1.183339232 N VX M7-CF 11.5 11.65 11.5 11.57 1919 0 1871 -0.006492588  27.58935246  23.57945638 23.50433714 4.08501532 19.41932182 Short 11.7764 0.165551151 11.94195115 11.61084885 12.1075023 11.4452977 Long N N N N
ES M7 6/2/2017 7:29 2431.25 2431.75 2430 2430.25 16785 0 VX M7-CF 11.6 11.75 11.58 11.7 3737 0 -0.001643217 0.011235955 -6.941089619     -0.001643217 -4 0.011235955 -0.795190709 -0.795190709 2511.460749 2.654396241 2141.75 0.001871126 0.79514286 2222.960749 -0.930583022 Short VX M7-CF 11.6 11.75 11.58 11.7 3737 0 1872 -0.006552806  27.73075716  23.68800858 23.61134075 4.119416411 19.49192434 Short 11.776 0.165714286 11.94171429 11.61028571 12.10742857 11.44457143 N N N N Short
ES M7 6/2/2017 8:29 2430.25 2431 2429 2430.75 37511 0 VX M7-CF 11.7 11.8 11.53 11.58 15635 0 0.00020574 -0.01025641 -6.944443722     0.00020574 0.5 -0.01025641 -0.801967629 -0.801967629 2511.166658 2.646332626 2141.25 -0.000233454 0.801808413 2221.666658 -0.997646802 Short VX M7-CF 11.7 11.8 11.53 11.58 15635 0 1873 -0.006629471  27.90272657  23.82506069 23.74829141 4.154435156 19.59385626 Short 11.773 0.167907287 11.94090729 11.60509271 12.10881457 11.43718543 Long N N N Short
ES M7 6/2/2017 9:29 2432.25 2433.75 2432.25 2433.25 26047 0 VX M7-CF 11.55 11.7 11.55 11.63 7148 0 0.001028489 0.004317789 -6.902663206     0.001028489 2.5 0.004317789 -0.50559849 -0.50559849 2513.527973 2.711077152 2138.75 -0.001167542 0.506119457 2219.027973 -1.134391675 Short VX M7-CF 11.55 11.7 11.55 11.63 7148 0 1874 -0.006703266  28.06957526  23.95751485 23.87955587 4.190019391 19.68953648 Short 11.7706 0.169096157 11.93969616 11.60150384 12.10879231 11.43240769 N N N N Short
ES M7 6/2/2017 10:29 2435.75 2437 2435.5 2436.75 31594 0 VX M7-CF 11.65 11.65 11.55 11.61 5090 0 0.001438405 -0.00171969 -6.862573345     0.001438405 3.5 -0.00171969 -0.494655304 -0.494655304 2516.424477 2.790495933 2135.25 -0.00163647 0.495088995 2214.924477 -1.347047627 Short VX M7-CF 11.65 11.65 11.55 11.61 5090 0 1875 -0.006773515  28.23118528  24.08370058 24.00506007 4.226125209 19.77893486 Short 11.7608 0.163729992 11.92452999 11.59707001 12.08825998 11.43334002 N N N N Short
ES M7 6/2/2017 11:29 2436 2437 2435.5 2436.75 25538 0 VX M7-CF 11.65 11.65 11.55 11.57 2278 0 0 -0.003445306 -6.86522263     0 0 -0.003445306 -0.46654779 -0.46654779 2516.180626 2.783809828 2135.25 0 0.466999626 2214.680626 -1.359684729 Short VX M7-CF 11.65 11.65 11.55 11.57 2278 0 1876 -0.00683482  28.37745101  24.19388406 24.11480519 4.262645818 19.85215938 Short 11.7512 0.160466666 11.91166667 11.59073333 12.07213333 11.43026667 Long N N N Short
ES M7 6/2/2017 12:29 2437.75 2438.75 2435.5 2435.75 37037 0 VX M7-CF 11.58 11.69 11.55 11.67 4309 0 -0.000410383 0.008643042 -6.890566028     -0.000410383 -1 0.008643042 -0.503091577 -0.503091577 2516.162906 2.783323958 2136.25 0.000468329 0.503595438 2216.662906 -1.25695683 Short VX M7-CF 11.58 11.69 11.55 11.67 4309 0 1877 -0.006883805  28.50205329  24.28297379 24.20263978 4.299413516 19.90322626 Short 11.7436 0.154929345 11.89852935 11.58867065 12.05345869 11.43374131 N N N N Short
ES M7 6/2/2017 13:29 2437.75 2438.5 2437 2437.75 26228 0 VX M7-CF 11.68 11.7 11.55 11.64 8570 0 0.000821102 -0.002570694 -6.88244494     0.000821102 2 -0.002570694 -0.520801285 -0.520801285 2517.861659 2.82990182 2134.25 -0.00093622 0.521308056 2214.361659 -1.376214577 Short VX M7-CF 11.68 11.7 11.55 11.64 8570 0 1878 -0.006929786  28.62236572  24.3666349 24.2859722 4.336393523 19.94957867 Short 11.734 0.145728291 11.87972829 11.58827171 12.02545658 11.44254342 N N N N Short
ES M7 6/2/2017 14:29 2437.75 2437.75 2437.75 2437.75 1 0 VX M7-CF 11.6 11.7 11.55 11.63 28177 0 0 -0.000859107 -6.904693941     0 0 -0.000859107 -0.516701901 -0.516701901 2518.051591 2.835109521 2134.25 0 0.517232222 2214.551591 -1.36637174 Short VX M7-CF 11.6 11.7 11.55 11.63 28177 0 1879 -0.006969382  28.73142917  24.4389793 24.35792539 4.37350378 19.98442161 Short 11.724 0.13474087 11.85874087 11.58925913 11.99348174 11.45451826 N N N N Short

EDIT: Here's the new code, based on the below suggestion:

AggregatedA = pd.read_csv(max(glob.iglob(r"C:\Users\cost9\OneDrive\Documents\PYTHON\Daily Tasks\Pairs Trading\VX_ES\CSV\15M\Lead_Lag\*.csv")), usecols=['Ticker_x', 'Date', 'Close_x', 'Ticker_y', 'Close_y', 'Lead_Lag', 'Ticker', '15M_Trend', 'Bollinger_1SD', 'Bollinger_2SD', 'Bollinger_and_Trend_1SD', 'Bollinger_and_Trend_2SD'], delimiter='\t')

AggregatedA.to_csv(r"C:\Users\cost9\OneDrive\Documents\PYTHON\Daily Tasks\Individual Trading\VX\CSV\Aggregated\VX_ES_15M\blah2.csv")

Which gives the error:

ValueError: Usecols do not match names.

edit: I also tried using delimiter=',' rather than delimiter='\t', which got rid of the error. However, the right columns remain blank.

Body:
Assuming that the input is as given, it is surprising that pandas parses the dataframe at all, as the delimiter should be given explicitly. Doing that, the code works as it should. If in.txt contains the lines, you provided, then running

In [26]: AggregatedA = pd.read_csv('in.txt', usecols=['Ticker_x', 'Date', 'Close_x', 'Ticker_y', 'Close_y', 'Lead_Lag', 'Ticker', '15M_Trend', 'Bollinger_1SD', 'Bollinger_2SD', 'Bollinger_and_Trend_1SD', 'Bollinger_and_Trend_2SD'], delimiter='\t')

In [25]: AggregatedA.to_csv('out.txt')

will give an out.txt with the following contents:

$ cat out.txt
,Ticker_x,Date,Close_x,Ticker_y,Close_y,Lead_Lag,Ticker,15M_Trend,Bollinger_1SD,Bollinger_2SD,Bollinger_and_Trend_1SD,Bollinger_and_Trend_2SD
0,ES M7,6/2/2017 3:29,2433.75,VX M7-CF,11.6,N,VX M7-CF,Short,Long,N,N,N
1,ES M7,6/2/2017 4:29,2434.75,VX M7-CF,11.6,Short,VX M7-CF,Short,Long,N,N,N
2,ES M7,6/2/2017 5:29,2435.0,VX M7-CF,11.55,N,VX M7-CF,Short,Long,N,N,N
3,ES M7,6/2/2017 6:29,2434.25,VX M7-CF,11.57,N,VX M7-CF,Short,Long,N,N,N
4,ES M7,6/2/2017 7:29,2430.25,VX M7-CF,11.7,Short,VX M7-CF,Short,N,N,N,N
5,ES M7,6/2/2017 8:29,2430.75,VX M7-CF,11.58,Short,VX M7-CF,Short,Long,N,N,N
6,ES M7,6/2/2017 9:29,2433.25,VX M7-CF,11.63,Short,VX M7-CF,Short,N,N,N,N
7,ES M7,6/2/2017 10:29,2436.75,VX M7-CF,11.61,Short,VX M7-CF,Short,N,N,N,N
8,ES M7,6/2/2017 11:29,2436.75,VX M7-CF,11.57,Short,VX M7-CF,Short,Long,N,N,N
9,ES M7,6/2/2017 12:29,2435.75,VX M7-CF,11.67,Short,VX M7-CF,Short,N,N,N,N
10,ES M7,6/2/2017 13:29,2437.75,VX M7-CF,11.64,Short,VX M7-CF,Short,N,N,N,N
11,ES M7,6/2/2017 14:29,2437.75,VX M7-CF,11.63,Short,VX M7-CF,Short,N,N,N,N