问:
VC++ GetComputerName returns uppercase on Win10
Why GetComputerName keeps original case for Win server 2012, but always returns uppercase for Win10?</p>

答:
the result of GetComputerName is same as the value in the Windows registry key HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\ComputerName
so please verify your result with the above registry value.


来源: stackexchange

问:
python numpy: iterate for different conditions without using a loop
I am trying to iterate over numpy arrays and generate an output, which has conditions similar to that described below:

```<code>min1 = 3
max1 = 1
a1 = np.array([1, 2, 5, 3, 4])
a2 = np.array([5, 2, 6, 2, 1])
output = np.zeros(5)
for i in range(0, 5):
  if((a1[i] - a2[i]) > min1):
    output[i] = 3 * (a1[i] - a2[i])

  if((a1[i] - a2[i]) < max1):
    output = 5 * (a1[i] - a2[i])
</code>```

I need to optimize the above code, so that I utilize the numpy functionalities as the best and also avoid using a loop. How should I do it?

答:
While functions like select and where can condense the code, I think it's a good idea to know how to do this with basic boolean masking.  It's applicable in many cases, and nearly always as fast.

Calculate the difference which is used several times:

```<code>In [432]: diff = a1-a2
In [433]: diff
Out[433]: array([-4,  0, -1,  1,  3])
In [435]: output = np.zeros_like(a1)
</code>```

find those cases where it meets the first condition, and set the corresponding elements of output:

```<code>In [436]: mask1 = diff>min1
In [437]: output[mask1] = 3*diff[mask1]
</code>```

repeat for the second condtion:

```<code>In [438]: mask2 = diff<max1
In [439]: output[mask2] = 5*diff[mask2]
</code>```

and again if there are more conditions.

```<code>In [440]: output
Out[440]: array([-20,   0,  -5,   0,   0])
</code>```

In this example, only the -4 and -1 met condition 2, and none condition 1.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to iterate over numpy arrays and generate an output, which has conditions similar to that described below:

min1 = 3
max1 = 1
a1 = np.array([1, 2, 5, 3, 4])
a2 = np.array([5, 2, 6, 2, 1])
output = np.zeros(5)
for i in range(0, 5):
  if((a1[i] - a2[i]) > min1):
    output[i] = 3 * (a1[i] - a2[i])

  if((a1[i] - a2[i]) < max1):
    output = 5 * (a1[i] - a2[i])

I need to optimize the above code, so that I utilize the numpy functionalities as the best and also avoid using a loop. How should I do it?

Body:
While functions like select and where can condense the code, I think it's a good idea to know how to do this with basic boolean masking.  It's applicable in many cases, and nearly always as fast.

Calculate the difference which is used several times:

In [432]: diff = a1-a2
In [433]: diff
Out[433]: array([-4,  0, -1,  1,  3])
In [435]: output = np.zeros_like(a1)

find those cases where it meets the first condition, and set the corresponding elements of output:

In [436]: mask1 = diff>min1
In [437]: output[mask1] = 3*diff[mask1]

repeat for the second condtion:

In [438]: mask2 = diff<max1
In [439]: output[mask2] = 5*diff[mask2]

and again if there are more conditions.

In [440]: output
Out[440]: array([-20,   0,  -5,   0,   0])

In this example, only the -4 and -1 met condition 2, and none condition 1.


问:
How to add a UsernameToken to the RequestSoapContext property of web service proxy class
I have a service that I have referenced which creates a proxy class "MyWebService". However when I use that class its object doesnt seem to have the RequestSoapContext property.
Here below is how I was expecting to consume the service:

```<code>            MyWebService objWS = new MyWebService();
            UsernameToken token = new UsernameToken("User","Password", PasswordOption.SendPlainText);
            objWS.RequestSoapContext.Security.Timestamp.TtlInSeconds = 60;
            objWS.RequestSoapContext.Security.Tokens.Add(token);
            objWS.RequestSoapContext.Security.MustUnderstand = false;
</code>```

Is there some configuration/modification that I need to make to the generated proxy class so that I can get the RequestSoapContext in there proxy class or do I need to do something on service side?

Thanks for your time...

答:
After referencing your webreference, click web reference at solution explorer to find reference.cs file. If you find it, open that file. You can see your web service class is dervied from System.Web.Services.xxxx. Change that to

public partial class MyWebService: Microsoft.Web.Services3.WebServicesClientProtocol

ContentLicense: CC BY-SA 2.5

Body:
I have a service that I have referenced which creates a proxy class "MyWebService". However when I use that class its object doesnt seem to have the RequestSoapContext property.
Here below is how I was expecting to consume the service:

            MyWebService objWS = new MyWebService();
            UsernameToken token = new UsernameToken("User","Password", PasswordOption.SendPlainText);
            objWS.RequestSoapContext.Security.Timestamp.TtlInSeconds = 60;
            objWS.RequestSoapContext.Security.Tokens.Add(token);
            objWS.RequestSoapContext.Security.MustUnderstand = false;

Is there some configuration/modification that I need to make to the generated proxy class so that I can get the RequestSoapContext in there proxy class or do I need to do something on service side?

Thanks for your time...


问:
Draw vertical line in scatter plot?
I'm using Libreoffice (but I think that this is similar in Excel) and I need to draw a vertical line in correspondence of the green points in this image:

Possibly follow the line style that I used in the legend. How can I do this?

答: In Excel you can use vertical error bars. If you want to have a line drop vertically to the axis, use  the settings with Minus and 100%

Title: Draw vertical line in scatter plot?


问:
Array of Objects Won't Clear
I have an array that's a property called .phrases of an object called a Passage.  I have a function that's a property of that same object.  In the function, I have code like this:

```<code>var returnPassage=new Passage();
returnPassage.phrases=[];
console.log(returnPassage.phrases);
</code>```

The console log in Google Chrome shows an empty array on one level, but if I click the drop-down it shows that the array hasn't changed at all.  This is true whether I try to clear the array with .pop() or .splice() or by replacing it with a new Array().  It's also, bizarrely(!!!) true if I do this:

```<code>var returnPassage=new Passage();
returnPassage.phrases=null;
returnPassage.phrases=[];
console.log(returnPassage.phrases);
</code>```

The console log shows the array same as original, not a blank array like i expect.  What could possibly be going on here???

答:
What could be going on is that phrases is just a property with a getter only, without seeing the Passage object, it is hard to say what is going on.

You can imagine having a setup like this inside your Passage object

function Passage() {
 Object.defineProperty(this, 'phrases', {
   get: function() {
     return ['phrase 1', 'phrase2'];
    },
    set: function() {
     // no setter
    }
  })
}

var passage = new Passage();
passage.phrases = null;
passage.phrases = [];
console.log(passage.phrases);```

Title: Array of Objects Won't Clear

Body:
I have an array that's a property called .phrases of an object called a Passage.  I have a function that's a property of that same object.  In the function, I have code like this:

var returnPassage=new Passage();
returnPassage.phrases=[];
console.log(returnPassage.phrases);

The console log in Google Chrome shows an empty array on one level, but if I click the drop-down it shows that the array hasn't changed at all.  This is true whether I try to clear the array with .pop() or .splice() or by replacing it with a new Array().  It's also, bizarrely(!!!) true if I do this:

var returnPassage=new Passage();
returnPassage.phrases=null;
returnPassage.phrases=[];
console.log(returnPassage.phrases);

The console log shows the array same as original, not a blank array like i expect.  What could possibly be going on here???


问:
Sync Sqlite Database With Remote Server in Android
I store data with sqlite database from remote server with AsyncTask..
I have used Retrofit to fetch data, and now I want to store that data into sqlite... I already have DatabaseHelper.class , Model Class and NavigationDrawer in that i am performing AsynckTask in MainActivity.

```<code> private class getDataToSqlite extends AsyncTask<Post, Void, Void>{

    @Override
    protected Void doInBackground(Post... params) {
           apiInterface.getContacts().enqueue(new Callback<List<Post>>() {
                @Override
                public void onResponse(Call<List<Post>> call, Response<List<Post>> response) {
                    if (response.isSuccessful()){

                        contacts = response.body();

                        for (int i=0; i < contacts.size(); i++){

                            Post post = contacts.get(i);

                            SaveToDatabase task = new SaveToDatabase();

                            task.execute(post);

                            adapter.addPost(post);

                        }
                    }else {

                    }

                }

                @Override
                public void onFailure(Call<List<Post>> call, Throwable t) {

                    Toast.makeText(getApplicationContext(), "Error" + t.toString(), Toast.LENGTH_SHORT).show();

                }
            });

        return null ;
    }
}

private  class  SaveToDatabase extends AsyncTask<Post, Void , Void> {
    @Override
    protected Void doInBackground(Post... params) {
        Post post = params[0];
        try {
            myDb.addData(post);

        } catch (Exception e) {
            Log.d(TAG, e.getMessage());
        }
        return null;
    }
}
</code>```

That class present in MainActivity

and i call the class in onCreate

```<code>   new getDataToSqlite();
</code>```

where i doing wrong please tell me

答:
You can do something like this that I have already Done :

```<code>public boolean SyncCityMasterToDevice() {
        try {
            DatabaseHandler db = new DatabaseHandler(mContext);
            db.dbDelete(TableCityMaster.TABLE);
            List<CityMaster> cityMasterList = ServerRepo.getCities();
            db.dbAddCity(cityMasterList);

            Log.d(TAG, "SyncCityMasterToDevice: ");
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }
</code>```

ServerRepo.getCities(); is a Retrofit Call.

I have called SyncCityMasterToDevice() method in an Async task

```<code>`DatabaseHandler`  is the Database Helper Class.
</code>```

Body:
I store data with sqlite database from remote server with AsyncTask..
I have used Retrofit to fetch data, and now I want to store that data into sqlite... I already have DatabaseHelper.class , Model Class and NavigationDrawer in that i am performing AsynckTask in MainActivity.

 private class getDataToSqlite extends AsyncTask<Post, Void, Void>{

    @Override
    protected Void doInBackground(Post... params) {
           apiInterface.getContacts().enqueue(new Callback<List<Post>>() {
                @Override
                public void onResponse(Call<List<Post>> call, Response<List<Post>> response) {
                    if (response.isSuccessful()){

                        contacts = response.body();

                        for (int i=0; i < contacts.size(); i++){

                            Post post = contacts.get(i);

                            SaveToDatabase task = new SaveToDatabase();

                            task.execute(post);

                            adapter.addPost(post);

                        }
                    }else {

                    }

                }

                @Override
                public void onFailure(Call<List<Post>> call, Throwable t) {

                    Toast.makeText(getApplicationContext(), "Error" + t.toString(), Toast.LENGTH_SHORT).show();

                }
            });

        return null ;
    }
}

private  class  SaveToDatabase extends AsyncTask<Post, Void , Void> {
    @Override
    protected Void doInBackground(Post... params) {
        Post post = params[0];
        try {
            myDb.addData(post);

        } catch (Exception e) {
            Log.d(TAG, e.getMessage());
        }
        return null;
    }
}

That class present in MainActivity

and i call the class in onCreate

   new getDataToSqlite();

where i doing wrong please tell me

Body:
You can do something like this that I have already Done :

public boolean SyncCityMasterToDevice() {
        try {
            DatabaseHandler db = new DatabaseHandler(mContext);
            db.dbDelete(TableCityMaster.TABLE);
            List<CityMaster> cityMasterList = ServerRepo.getCities();
            db.dbAddCity(cityMasterList);

            Log.d(TAG, "SyncCityMasterToDevice: ");
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

ServerRepo.getCities(); is a Retrofit Call.

I have called SyncCityMasterToDevice() method in an Async task

`DatabaseHandler`  is the Database Helper Class.


问:
JavaFX Alert Border
I am currently designing a GUI with JavaFX and style it with css. However, the alert behaves very strangely, as a matter of fact, the border is bugging around when pressing certain buttons or changing the focused window. It also doesn't completely draw the border, I suspect it has something to do with the image.

The formatting in the .css:

```<code>.dialog-pane {
    -fx-background-color: #1d1d1d;
    -fx-border-color: #e2e2e2;
    -fx-border-width: 2;
}
</code>```

The initial state of the Dialog:

The Dialog after pressing 'tab' a few times:

The borders are somewhat hard to make out here due to them being so light, but the white space that is inserted in the second screenshot isn't actually the same colour as the border. (it is simply white whereas the border is #e2e2e2)

Any help would be greatly appreciated!

答:
Ok, so I found a bugreport that states that this is actually a bug for JDK versions below 8.60 (I was working on an older laptop and didn't bother updating - I see that was stupid now).

So simply updating it to the newest version fixed this for me, no additional steps required.

Title: JavaFX Alert Border

Body:
I am currently designing a GUI with JavaFX and style it with css. However, the alert behaves very strangely, as a matter of fact, the border is bugging around when pressing certain buttons or changing the focused window. It also doesn't completely draw the border, I suspect it has something to do with the image.

The formatting in the .css:

.dialog-pane {
    -fx-background-color: #1d1d1d;
    -fx-border-color: #e2e2e2;
    -fx-border-width: 2;
}

The initial state of the Dialog:

The Dialog after pressing 'tab' a few times:

The borders are somewhat hard to make out here due to them being so light, but the white space that is inserted in the second screenshot isn't actually the same colour as the border. (it is simply white whereas the border is #e2e2e2)

Any help would be greatly appreciated!


问:
Can I precompile my ASP.NET MVC application?
I tried to precompile my ASP.NET MVC application and deploy it to an IIS6 box (with wildcard mapping), however I am getting an error with rendering partial views (user controls).  Its working fine on my dev machine before precompiling.

The error is:

Server Error in '/' Application.

  The partial view 'ListGrid' could not

  be found. The following locations were

  searched:

  ~/Views/Initiative/ListGrid.aspx

  ~/Views/Initiative/ListGrid.ascx

  ~/Views/Shared/ListGrid.aspx

  ~/Views/Shared/ListGrid.ascx

I checked Views\Shared for the file and it was not there, which I thought was normal because its precompiled.  But just for giggles I put a blank file in that folder names ListGrid.ascx, but then I got this error:

Server Error in '/' Application.

  The file '/Views/Shared/ListGrid.ascx'

  has not been pre-compiled, and cannot

  be requested.

I googled and searched SO but could not find any similar problems, but had no luck.

答:
You can precompile an MVC app by placing this in the post-build actions in project properties:

```<code>C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_compiler -p "$(ProjectDir)." -v /$(ProjectName)
</code>```

This takes a little longer than without it, however you get the added ability to detect some errors that would occur at runtime prior to deployment.

Compilation will fail if you have invalid code in your views or are missing views by using this method.

Body:
You can precompile an MVC app by placing this in the post-build actions in project properties:

C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_compiler -p "$(ProjectDir)." -v /$(ProjectName)

This takes a little longer than without it, however you get the added ability to detect some errors that would occur at runtime prior to deployment.

Compilation will fail if you have invalid code in your views or are missing views by using this method.


问:
How to check the conditions and save files by using in one .csv file in C#
I have a .csv file. I want to create files by using this file. This is format of the .csv file. This is a small part of my .csv file. I have 60000 more rows in my original file.

```<code>Date,Pass,CutMark1,Marks1,CutMark2,Marks2,
22/06/2017 13:04:18,FALSE,TRUE,40,FALSE,35,
22/06/2017 13:04:20,FALSE,TRUE,35,FALSE,35,
22/06/2017 13:04:35,FALSE,TRUE,55,FALSE,55,
22/06/2017 13:04:37,FALSE,TRUE,100,FALSE,55,
22/06/2017 13:04:37,FALSE,TRUE,38,FALSE,55,
22/06/2017 13:04:38,FALSE,FALSE,35,FALSE,55,
22/06/2017 13:04:39,FALSE,FALSE,35,FALSE,38,
22/06/2017 13:04:40,FALSE,FALSE,35,TRUE,38,
22/06/2017 13:04:41,FALSE,FALSE,55,TRUE,38,
22/06/2017 13:04:42,FALSE,FALSE,55,TRUE,55,
22/06/2017 13:04:44,FALSE,FALSE,38,TRUE,55,
22/06/2017 13:04:45,TRUE,FALSE,38,TRUE,40,
22/06/2017 13:04:46,TRUE,FALSE,38,TRUE,40,
22/06/2017 13:04:48,TRUE,FALSE,55,FALSE,40,
22/06/2017 13:04:49,TRUE,FALSE,55,FALSE,25,
22/06/2017 13:04:50,TRUE,FALSE,55,FALSE,45,
22/06/2017 13:04:52,FALSE,TRUE,55,FALSE,60,
22/06/2017 13:04:53,FALSE,TRUE,40,FALSE,80,
22/06/2017 13:04:54,FALSE,TRUE,40,FALSE,80,
22/06/2017 13:04:56,FALSE,TRUE,40,FALSE,75,
22/06/2017 13:04:57,FALSE,TRUE,40,FALSE,90,
22/06/2017 13:04:58,FALSE,TRUE,55,FALSE,88,
22/06/2017 13:05:00,TRUE,TRUE,55,TRUE,23,
22/06/2017 13:05:01,TRUE,TRUE,55,TRUE,45,
22/06/2017 13:05:02,TRUE,TRUE,20,TRUE,78,
22/06/2017 13:05:04,TRUE,TRUE,45,TRUE,45,
22/06/2017 13:05:05,TRUE,TRUE,85,TRUE,69,
22/06/2017 13:05:06,TRUE,TRUE,62,TRUE,45,
22/06/2017 13:05:08,TRUE,TRUE,100,TRUE,35,
</code>```

I want to save this files as follows. In here "Pass" column want to check. There is False then True after that False then again True and etc So I want to save files by using this. As an example I want to save this file first meet False values as False1.csv then secondly True1.csv then again meet False2.csv like that I want to add numbers into the file name which that True or False meet in how many times. I want that rows save particular all other column in this .csvfile.

I use this example for explain for me, I want to save first all false and true values in different files. I get this  example for that. In here first 11 rows of Pass column is "False". So I want to save those (1-11 )rows in one file should save as False1.csv, then meet pass "True" there are rows (12-16) should save as True1.csv, then Pass value has again meet "False" then save those rows(17-22) as False2.csv again meet pass column is "True" then that rows(23-29) save as True2.csv, likewise I want to save, I have 60000 raws in my .csv file.

This is my code for reading the .csv file.

```<code>using System.Globalization;

public static string dateFormatString = "dd/MM/yyyy HH:mm:ss";

private void btnSeperateFile_Click(object sender, EventArgs e)
{
    if (tbOutputFilePath2 != null)
    {
        List<DrawNew> ObservingData = new List<DrawNew>(); // List to store all available DrawNew objects from the CSV

        // Loops through each lines in the CSV
        foreach (string line in System.IO.File.ReadAllLines(outputFilePath.Text).Skip(1)) // .Skip(1) is for skipping header
        {
            string[] valuesCsvLine = line.Split(',');
            DrawNew mngInstance = new DrawNew();

            mngInstance.Date = DateTime.ParseExact(valuesCsvLine[0], dateFormatString, CultureInfo.InvariantCulture);
            mngInstance.Pass = (valuesCsvLine[1] == "TRUE" ? true : false);
            mngInstance.CutMark1 = (valuesCsvLine[2] == "TRUE" ?true: false);
            mngInstance.Marks1 = int.Parse(valuesCsvLine[3]);
            mngInstance.CutMark2 = (valuesCsvLine[4] == "TRUE" ? true : false);
            mngInstance.Marks2 = int.Parse(valuesCsvLine[5]);

            ObserveData.Add(mngInstance);
        }
    }
}
</code>```

This is the class for storing data of .csv file:

```<code>class DrawNew
{
    public DateTime Date { get; set; } // property to store Date
    public bool Pass { get; set; } // property to store Pass
    public bool CutMark1 { get; set; } // property to store CutMark1
    public int Marks1 { get; set; } // property to store Marks1
    public bool CutMark2 { get; set; } // property to store CutMark2
    public int Marks2 { get; set; } // property to store Marks2
}
</code>```

答:
Probably not the best or most performant or even nicest way to do it, but it might get you started:</p>

```<code>using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;

[...]

public void StoreSeparatedByPass(IEnumerable<DrawNew> observingData)
{
  // keep the file numbers easily accessible
  var fileCounts
    = new Dictionary<bool, int>
      {
        { false, 0 },
        { true, 0 }
      };

  bool? pass = null;
  var lines = new List<DrawNew>();

  foreach (var drawNew in observingData)
  {
    // to differentiate between "starting with false"
    // and "starting with true".
    // (only interesting on first item)
    if (pass.HasValue == false)
    {
      pass = drawNew.Pass;
    }

    if (pass.Value != drawNew.Pass)
    {
      // the value of drawNew.Pass changed, the previous "part" has ended.
      // now we need to do store the collected lines (if there are any)...
      if (lines.Any())
      {
        fileCounts[pass.Value]++;
        StoreLines(lines, pass.Value.ToString() + fileCounts[pass.Value] + ".csv");

        // then clear the stored list for the next part...
        lines.Clear();
      }

      // and change the part indicator.
      pass = drawNew.Pass;
    }

    lines.Add(drawNew);
  }

  // don't forget to store the last part...
  if (pass.HasValue && lines.Any())
  {
    fileCounts[pass.Value]++;
    StoreLines(lines, pass.Value.ToString() + fileCounts[pass.Value] + ".csv");
  }
}
public void StoreLines(IEnumerable<DrawNew> lines, string fileName)
{
  // TODO: actually write the DrawNew items to the given filename
}
</code>```

Body:
I have a .csv file. I want to create files by using this file. This is format of the .csv file. This is a small part of my .csv file. I have 60000 more rows in my original file.

Date,Pass,CutMark1,Marks1,CutMark2,Marks2,
22/06/2017 13:04:18,FALSE,TRUE,40,FALSE,35,
22/06/2017 13:04:20,FALSE,TRUE,35,FALSE,35,
22/06/2017 13:04:35,FALSE,TRUE,55,FALSE,55,
22/06/2017 13:04:37,FALSE,TRUE,100,FALSE,55,
22/06/2017 13:04:37,FALSE,TRUE,38,FALSE,55,
22/06/2017 13:04:38,FALSE,FALSE,35,FALSE,55,
22/06/2017 13:04:39,FALSE,FALSE,35,FALSE,38,
22/06/2017 13:04:40,FALSE,FALSE,35,TRUE,38,
22/06/2017 13:04:41,FALSE,FALSE,55,TRUE,38,
22/06/2017 13:04:42,FALSE,FALSE,55,TRUE,55,
22/06/2017 13:04:44,FALSE,FALSE,38,TRUE,55,
22/06/2017 13:04:45,TRUE,FALSE,38,TRUE,40,
22/06/2017 13:04:46,TRUE,FALSE,38,TRUE,40,
22/06/2017 13:04:48,TRUE,FALSE,55,FALSE,40,
22/06/2017 13:04:49,TRUE,FALSE,55,FALSE,25,
22/06/2017 13:04:50,TRUE,FALSE,55,FALSE,45,
22/06/2017 13:04:52,FALSE,TRUE,55,FALSE,60,
22/06/2017 13:04:53,FALSE,TRUE,40,FALSE,80,
22/06/2017 13:04:54,FALSE,TRUE,40,FALSE,80,
22/06/2017 13:04:56,FALSE,TRUE,40,FALSE,75,
22/06/2017 13:04:57,FALSE,TRUE,40,FALSE,90,
22/06/2017 13:04:58,FALSE,TRUE,55,FALSE,88,
22/06/2017 13:05:00,TRUE,TRUE,55,TRUE,23,
22/06/2017 13:05:01,TRUE,TRUE,55,TRUE,45,
22/06/2017 13:05:02,TRUE,TRUE,20,TRUE,78,
22/06/2017 13:05:04,TRUE,TRUE,45,TRUE,45,
22/06/2017 13:05:05,TRUE,TRUE,85,TRUE,69,
22/06/2017 13:05:06,TRUE,TRUE,62,TRUE,45,
22/06/2017 13:05:08,TRUE,TRUE,100,TRUE,35,

I want to save this files as follows. In here "Pass" column want to check. There is False then True after that False then again True and etc So I want to save files by using this. As an example I want to save this file first meet False values as False1.csv then secondly True1.csv then again meet False2.csv like that I want to add numbers into the file name which that True or False meet in how many times. I want that rows save particular all other column in this .csvfile.

I use this example for explain for me, I want to save first all false and true values in different files. I get this  example for that. In here first 11 rows of Pass column is "False". So I want to save those (1-11 )rows in one file should save as False1.csv, then meet pass "True" there are rows (12-16) should save as True1.csv, then Pass value has again meet "False" then save those rows(17-22) as False2.csv again meet pass column is "True" then that rows(23-29) save as True2.csv, likewise I want to save, I have 60000 raws in my .csv file.

This is my code for reading the .csv file.

using System.Globalization;

public static string dateFormatString = "dd/MM/yyyy HH:mm:ss";

private void btnSeperateFile_Click(object sender, EventArgs e)
{
    if (tbOutputFilePath2 != null)
    {
        List<DrawNew> ObservingData = new List<DrawNew>(); // List to store all available DrawNew objects from the CSV

        // Loops through each lines in the CSV
        foreach (string line in System.IO.File.ReadAllLines(outputFilePath.Text).Skip(1)) // .Skip(1) is for skipping header
        {
            string[] valuesCsvLine = line.Split(',');
            DrawNew mngInstance = new DrawNew();

            mngInstance.Date = DateTime.ParseExact(valuesCsvLine[0], dateFormatString, CultureInfo.InvariantCulture);
            mngInstance.Pass = (valuesCsvLine[1] == "TRUE" ? true : false);
            mngInstance.CutMark1 = (valuesCsvLine[2] == "TRUE" ?true: false);
            mngInstance.Marks1 = int.Parse(valuesCsvLine[3]);
            mngInstance.CutMark2 = (valuesCsvLine[4] == "TRUE" ? true : false);
            mngInstance.Marks2 = int.Parse(valuesCsvLine[5]);

            ObserveData.Add(mngInstance);
        }
    }
}

This is the class for storing data of .csv file:

class DrawNew
{
    public DateTime Date { get; set; } // property to store Date
    public bool Pass { get; set; } // property to store Pass
    public bool CutMark1 { get; set; } // property to store CutMark1
    public int Marks1 { get; set; } // property to store Marks1
    public bool CutMark2 { get; set; } // property to store CutMark2
    public int Marks2 { get; set; } // property to store Marks2
}

Body:
Probably not the best or most performant or even nicest way to do it, but it might get you started:

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;

[...]

public void StoreSeparatedByPass(IEnumerable<DrawNew> observingData)
{
  // keep the file numbers easily accessible
  var fileCounts
    = new Dictionary<bool, int>
      {
        { false, 0 },
        { true, 0 }
      };

  bool? pass = null;
  var lines = new List<DrawNew>();

  foreach (var drawNew in observingData)
  {
    // to differentiate between "starting with false"
    // and "starting with true".
    // (only interesting on first item)
    if (pass.HasValue == false)
    {
      pass = drawNew.Pass;
    }

    if (pass.Value != drawNew.Pass)
    {
      // the value of drawNew.Pass changed, the previous "part" has ended.
      // now we need to do store the collected lines (if there are any)...
      if (lines.Any())
      {
        fileCounts[pass.Value]++;
        StoreLines(lines, pass.Value.ToString() + fileCounts[pass.Value] + ".csv");

        // then clear the stored list for the next part...
        lines.Clear();
      }

      // and change the part indicator.
      pass = drawNew.Pass;
    }

    lines.Add(drawNew);
  }

  // don't forget to store the last part...
  if (pass.HasValue && lines.Any())
  {
    fileCounts[pass.Value]++;
    StoreLines(lines, pass.Value.ToString() + fileCounts[pass.Value] + ".csv");
  }
}
public void StoreLines(IEnumerable<DrawNew> lines, string fileName)
{
  // TODO: actually write the DrawNew items to the given filename
}


问:
Gradle Replace token
I am using gradle filtering to replace a token in one log4j.xml using below code.

```<code>import org.apache.tools.ant.filters.ReplaceTokens
task copylog4jEnvSpecific(type:Copy){
       from("$config_dir/"+"$env")
       into("$webAppDir/WEB-INF/classes")
       include "**/log4j.xml"
       filter(ReplaceTokens, tokens: [LOG_HOME: project.rootDir])
}
</code>```

but I am getting an error saying

```<code>Execution failed for task ':copylog4jEnvSpecific'.
</code>```

Could not copy file 'C:\Users\<>\rws\conf\<>\configuration\dev\log4j.xml' to 'C:\Users\<>\rws\build\WebContent\WEB-INF\classes\log4j.xml'.

答:
Need more information here. Run your build with --stacktrace maybe we can get some more info there.

I presume C:\Users\<>\rws is your project path?

When do you run the task? maybe the build directory does not exist yet?
As well what is creating WebContent\WEB-INF\classes\ ?

You can make sure that your task is executed after the build task with:

```<code>copylog4jEnvSpecific.dependsOn build
</code>```

Title: Gradle Replace token

Body:
I am using gradle filtering to replace a token in one log4j.xml using below code.

import org.apache.tools.ant.filters.ReplaceTokens
task copylog4jEnvSpecific(type:Copy){
       from("$config_dir/"+"$env")
       into("$webAppDir/WEB-INF/classes")
       include "**/log4j.xml"
       filter(ReplaceTokens, tokens: [LOG_HOME: project.rootDir])
}

but I am getting an error saying

Execution failed for task ':copylog4jEnvSpecific'.

Could not copy file 'C:\Users\<>\rws\conf\<>\configuration\dev\log4j.xml' to 'C:\Users\<>\rws\build\WebContent\WEB-INF\classes\log4j.xml'.

Body:
Need more information here. Run your build with --stacktrace maybe we can get some more info there.

I presume C:\Users\<>\rws is your project path?

When do you run the task? maybe the build directory does not exist yet?
As well what is creating WebContent\WEB-INF\classes\ ?

You can make sure that your task is executed after the build task with:

copylog4jEnvSpecific.dependsOn build


问:
Make a HMTL  hyperlink not appear as a hyperlink
I'm making a website (for schoolwork) using a combination of php, html and css. I'm currently working on the initial design stages of my site and as I'm inexperienced at html / css, I am going slowly through tutorials trying to learn.

Including the hyperlink my banner looks like:

Not including the hyperlink my banner looks like:

I want to have the functionality of the link, but the visual design effect of without the link.

The necessary code is:

```<code><html>
    <head>
        <link rel="stylesheet" type="text/css" href="style.css">
    </head>
    <center>
    <div id = "indexBackgroundOne"><h2 style="font-family:verdana"> Q U E S T S ®</h2></div>
    </center>
</html>
</code>```

Thanks!

答:
.noline{
text-decoration:none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
    <head>
        <link rel="stylesheet" type="text/css" href="style.css">
    </head>
    <center>
    <div id = "indexBackgroundOne"><h2 style="font-family:verdana"> Q U E S T S ®</h2></div>
    </center>
</html></code>```

you can make a class and add it to  and make text-decoration:none in css

Title: Make a HMTL <a href> hyperlink not appear as a hyperlink

Body:
I'm making a website (for schoolwork) using a combination of php, html and css. I'm currently working on the initial design stages of my site and as I'm inexperienced at html / css, I am going slowly through tutorials trying to learn.

Including the hyperlink my banner looks like:

Not including the hyperlink my banner looks like:

I want to have the functionality of the link, but the visual design effect of without the link.

The necessary code is:

        <link rel="stylesheet" type="text/css" href="style.css">

 Q U E S T S ®

Thanks!

Body:
.noline{
text-decoration:none;
}

<html>
    <head>
        <link rel="stylesheet" type="text/css" href="style.css">
    </head>
    <center>
    <div id = "indexBackgroundOne"><a class="noline"href="#your link"><h2 style="font-family:verdana"> Q U E S T S &reg;</h2></a></div>
    </center>
</html>

you can make a class and add it to  and make text-decoration:none in css


问:
Git Shell in Windows: patch's default character encoding is UCS-2 Little Endian - how to change this to ANSI or UTF-8 without BOM?
When creating a diff patch with Git Shell in Windows (when using GitHub for Windows), the character encoding of the patch will be UCS-2 Little Endian according to Notepad++ (see the screenshots below).

How can I change this behavior, and force git to create patches with ANSI or UTF-8 without BOM character encoding?

It causes a problem because UCS-2 Little Endian encoded patches can not be applied, I have to manually convert it to ANSI. If I don't, I get "fatal: unrecognized input" error.

Since then, I also realized that I have to manually convert the EOL from Windows format (\r\n) to UNIX (\n) in Notepad++ (Edit > EOL Conversion > UNIX). If I don't do this, I get "trailing whitespace" error (even if all the whitespaces are trimmed: "TextFX" > "TextFX Edit" > "Trim Trailing Spaces").

So, the steps I need to do for the patch to be applied:

create patch (here is the result)

convert character encoding to ANSI

EOL conversion to UNIX format

apply patch

Please, take a look at this screenshot:

答:
If you use powershell you can also just do:

```<code>cmd /c "git diff > patch.diff"
</code>```

This makes command to be run through CMD which writes to output file as is.

Body:
If you use powershell you can also just do:

cmd /c "git diff > patch.diff"

This makes command to be run through CMD which writes to output file as is.


问:
Apply function to each cell in DataFrame that depends on the column name in pandas
How can I apply function to each cell in a DataFrame that depends on the column name?

I'm aware of pandas.DataFrame.applymap but it doesn't seem to allow depending on the column name:

```<code>import numpy as np
import pandas as pd
np.random.seed(1)
frame = pd.DataFrame(np.random.randn(4, 3), columns=list('bde'),
                     index=['Utah', 'Ohio', 'Texas', 'Oregon'])
print(frame)
format = lambda x: '%.2f' % x
frame = frame.applymap(format)
print(frame)
</code>```

returns:

```<code>               b         d         e
Utah    1.624345 -0.611756 -0.528172
Ohio   -1.072969  0.865408 -2.301539
Texas   1.744812 -0.761207  0.319039
Oregon -0.249370  1.462108 -2.060141

            b      d      e
Utah     1.62  -0.61  -0.53
Ohio    -1.07   0.87  -2.30
Texas    1.74  -0.76   0.32
Oregon  -0.25   1.46  -2.06
</code>```

Instead, I want the function that I applied to each cell to use the column name of the current cell as an argument.

I don't want to have to loop myself over each column, like:

```<code>def format2(cell_value, column_name):
    return '{0}_{1:.2f}'.format(column_name, cell_value)

for column_name in frame.columns.values:
    print('column_name: {0}'.format(column_name))
    frame[column_name]=frame[column_name].apply(format2, args=(column_name))
print(frame)
</code>```

Returns:

```<code>              b        d        e
Utah     b_1.62  d_-0.61  e_-0.53
Ohio    b_-1.07   d_0.87  e_-2.30
Texas    b_1.74  d_-0.76   e_0.32
Oregon  b_-0.25   d_1.46  e_-2.06
</code>```

(This is just one example. The functions I want to apply on the cells may do more than just appending the column name)

答:
If you don't want to loop through the columns, you can do something like this:

```<code>frame.T.apply(lambda x: x.apply(format2,args=(x.name)), axis=1).T
Out[289]:
              b        d        e
Utah     b_0.90  d_-0.68  e_-0.12
Ohio    b_-0.94  d_-0.27   e_0.53
Texas   b_-0.69  d_-0.40  e_-0.69
Oregon  b_-0.85  d_-0.67  e_-0.01
</code>```

After transposing the df, the column names become index which can be referenced in apply function by using the .name attribute.

Body:
How can I apply function to each cell in a DataFrame that depends on the column name?

I'm aware of pandas.DataFrame.applymap but it doesn't seem to allow depending on the column name:

import numpy as np
import pandas as pd
np.random.seed(1)
frame = pd.DataFrame(np.random.randn(4, 3), columns=list('bde'),
                     index=['Utah', 'Ohio', 'Texas', 'Oregon'])
print(frame)
format = lambda x: '%.2f' % x
frame = frame.applymap(format)
print(frame)

returns:

               b         d         e
Utah    1.624345 -0.611756 -0.528172
Ohio   -1.072969  0.865408 -2.301539
Texas   1.744812 -0.761207  0.319039
Oregon -0.249370  1.462108 -2.060141

            b      d      e
Utah     1.62  -0.61  -0.53
Ohio    -1.07   0.87  -2.30
Texas    1.74  -0.76   0.32
Oregon  -0.25   1.46  -2.06

Instead, I want the function that I applied to each cell to use the column name of the current cell as an argument.

I don't want to have to loop myself over each column, like:

def format2(cell_value, column_name):
    return '{0}_{1:.2f}'.format(column_name, cell_value)

for column_name in frame.columns.values:
    print('column_name: {0}'.format(column_name))
    frame[column_name]=frame[column_name].apply(format2, args=(column_name))
print(frame)

Returns:

              b        d        e
Utah     b_1.62  d_-0.61  e_-0.53
Ohio    b_-1.07   d_0.87  e_-2.30
Texas    b_1.74  d_-0.76   e_0.32
Oregon  b_-0.25   d_1.46  e_-2.06

(This is just one example. The functions I want to apply on the cells may do more than just appending the column name)

Body:
If you don't want to loop through the columns, you can do something like this:

frame.T.apply(lambda x: x.apply(format2,args=(x.name)), axis=1).T
Out[289]:
              b        d        e
Utah     b_0.90  d_-0.68  e_-0.12
Ohio    b_-0.94  d_-0.27   e_0.53
Texas   b_-0.69  d_-0.40  e_-0.69
Oregon  b_-0.85  d_-0.67  e_-0.01

After transposing the df, the column names become index which can be referenced in apply function by using the .name attribute.


问:
Programmatically binding List to ListBox
Let's say, for instance, I have the following extremely simple window:

```<code><Window x:Class="CalendarGenerator.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Window1"
        Height="300"
        Width="447">
  <Grid>
    <ListBox Margin="12,40,0,12"
             Name="eventList"
             HorizontalAlignment="Left"
             Width="134" />
  </Grid>
</Window>
</code>```

And a simple list defined as:

```<code>List<String> ListOfNames = new List<String>();
</code>```

And let's assume that the list has several names in it. How would I go about binding the List to the ListBox using as much code-behind as possible?

答:
Use Binding class if you want to customize binding:

```<code>List<String> listOfNames = new List<String>() {"a", "b"};
Binding myBinding = new Binding();
//set binding parameters if necessary
myBinding.Source = listOfNames;
eventList.SetBinding(ItemsControl.ItemsSourceProperty, myBinding);
</code>```

or

directly assign data to ItemsSource property:

```<code>eventList.ItemsSource = listOfNames;
</code>```

OwnerDisplayName: Jason Miesionczek

ContentLicense: CC BY-SA 4.0

Body:
Let's say, for instance, I have the following extremely simple window:

<Window x:Class="CalendarGenerator.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Window1"
        Height="300"
        Width="447">
  <Grid>
    <ListBox Margin="12,40,0,12"
             Name="eventList"
             HorizontalAlignment="Left"
             Width="134" />
  </Grid>
</Window>

And a simple list defined as:

List<String> ListOfNames = new List<String>();

And let's assume that the list has several names in it. How would I go about binding the List to the ListBox using as much code-behind as possible?

Body:
Use Binding class if you want to customize binding:

List<String> listOfNames = new List<String>() {"a", "b"};
Binding myBinding = new Binding();
//set binding parameters if necessary
myBinding.Source = listOfNames;
eventList.SetBinding(ItemsControl.ItemsSourceProperty, myBinding);

or

directly assign data to ItemsSource property:

eventList.ItemsSource = listOfNames;

OwnerDisplayName: aku


问:
Extract base url from full url
Any quick way to extract base url from full url? for e.g., if i have http://test.example.com/abcd/test.html - i want only http://test.example.com. </p>

<p>I can always do string parsing - but wanted to know if there is something in Uri where I can get it directly.  </p>

答:
There's nothing in the Android URI class that gives you the base URL directly-  As gnuf suggests, you'd have to construct it as the protocol + getHost().

The string parsing way might be easier and let you avoid stuffing everything in a try/catch block.  Just take a substring of the URL, everything from the beginning of the string to the third "/" symbol.

Title: Extract base url from full url

Body:
Any quick way to extract base url from full url? for e.g., if i have http://test.example.com/abcd/test.html - i want only http://test.example.com.

I can always do string parsing - but wanted to know if there is something in Uri where I can get it directly.


问:
How to write a service which consumes 2 different types of objects but have a single endpoint?
How to write a service which consumes 2 different types of objects but have a single endpoint ?

/hello is the endpoint I should be able to handle Class Hello1 and Class Hello2 in that...both having different parameters.

```<code>@CrossOrigin
@ResponseStatus(HttpStatus.OK)
@RequestMapping(value = "/hello", method = RequestMethod.POST)
public BaseResponseDTO geteula(@RequestBody Hello1 request) {}

@CrossOrigin
@ResponseStatus(HttpStatus.OK)
@RequestMapping(value = "/hello", method = RequestMethod.POST)
public BaseResponseDTO geteula(@RequestBody Hello2 request) {}
</code>```

Above is what I need actually...but it needs to be a single endpoint.

答:
If you really want to do this I guess you can inhert your Hello1 and Hello2 class from some abstract class Hello, for example, and use it as a parameter. Also you should take advange of Jackson @JsonSubTypes and @JsonTypeInfo annotations. But in this case you should also send additional property from your client so Jackson nows what exaclty implementation class it should instantiate. For example:

```<code>@JsonTypeInfo(
    use = JsonTypeInfo.Id.NAME,
    include = JsonTypeInfo.As.PROPERTY,
    property = "type")
@JsonSubTypes({
    @JsonSubTypes.Type(value = Hello1.class, name = "hello1"),
    @JsonSubTypes.Type(value = Hello2.class, name = "hello2")
})
public abstract class Hello {
   ...
}
</code>```

Then extend this class with your classes:

```<code>public class Hello1 extends Hello {
   ...
}

public class Hello2 extends Hello {
   ...
}
</code>```

And your controller:

```<code>@CrossOrigin
@ResponseStatus(HttpStatus.OK)
@RequestMapping(value = "/hello", method = RequestMethod.POST)
public BaseResponseDTO geteula(@RequestBody Hello request) {
    if (request instanceof Hello1) {
        // some logic
    }
    if (request instanceof Hello2) {
        // some logic
    }
    ...
}
</code>```

Please note, that in this case, your JSON should include type property as defined ablove property = "type" (you can name it whatever you like):

```<code>{"type" : "hello1", .....}
</code>```

Body:
How to write a service which consumes 2 different types of objects but have a single endpoint ?

/hello is the endpoint I should be able to handle Class Hello1 and Class Hello2 in that...both having different parameters.

@CrossOrigin
@ResponseStatus(HttpStatus.OK)
@RequestMapping(value = "/hello", method = RequestMethod.POST)
public BaseResponseDTO geteula(@RequestBody Hello1 request) {}

@CrossOrigin
@ResponseStatus(HttpStatus.OK)
@RequestMapping(value = "/hello", method = RequestMethod.POST)
public BaseResponseDTO geteula(@RequestBody Hello2 request) {}

Above is what I need actually...but it needs to be a single endpoint.

Body:
If you really want to do this I guess you can inhert your Hello1 and Hello2 class from some abstract class Hello, for example, and use it as a parameter. Also you should take advange of Jackson @JsonSubTypes and @JsonTypeInfo annotations. But in this case you should also send additional property from your client so Jackson nows what exaclty implementation class it should instantiate. For example:

@JsonTypeInfo(
    use = JsonTypeInfo.Id.NAME,
    include = JsonTypeInfo.As.PROPERTY,
    property = "type")
@JsonSubTypes({
    @JsonSubTypes.Type(value = Hello1.class, name = "hello1"),
    @JsonSubTypes.Type(value = Hello2.class, name = "hello2")
})
public abstract class Hello {
   ...
}

Then extend this class with your classes:

public class Hello1 extends Hello {
   ...
}

public class Hello2 extends Hello {
   ...
}

And your controller:

@CrossOrigin
@ResponseStatus(HttpStatus.OK)
@RequestMapping(value = "/hello", method = RequestMethod.POST)
public BaseResponseDTO geteula(@RequestBody Hello request) {
    if (request instanceof Hello1) {
        // some logic
    }
    if (request instanceof Hello2) {
        // some logic
    }
    ...
}

Please note, that in this case, your JSON should include type property as defined ablove property = "type" (you can name it whatever you like):

{"type" : "hello1", .....}


问:
How to get String output as in single quote in javascript
Advance thanks, Question looks like simple but i could not able to find the solution.

```<code>function sumStrings(a, b)
{
return  +a + +b;
}
sumStrings('1','2') //=>3
</code>```

Expected output

```<code>sumStrings('1','2') // => '3'
</code>```

答:
If you want to escape the single quote, you can try to add a backslash before the single quote.
i.e.</p>

```<code>var x = '\'5\'';
</code>```

Body:
Advance thanks, Question looks like simple but i could not able to find the solution.

function sumStrings(a, b)
{
return  +a + +b;
}
sumStrings('1','2') //=>3

Expected output

sumStrings('1','2') // => '3'

Body:
If you want to escape the single quote, you can try to add a backslash before the single quote.
i.e.

var x = '\'5\'';


问:
How does c++ handle 0*(large expression)
Concerning speed, if I need to calculate a large expression, say:

```<code>switch1*(large expression 1)+switch2*(large expression 2)
</code>```

Depending on my input, switch1 can be 0 or 1, as can switch2 be. What would be the quickest for c++ to do, making an if statement or write it down as above?

答:
So, essentially you are asking about Short-Circuit Evaluation, and you are asking whether C++ does it for arithmetic expressions besides boolean expressions.

It is kind of hard to prove a negative, but as far as I know, C++ only does short-circuit evaluation for logical expressions, so there is no equivalent for arithmetic expressions.  Also, I can think of plenty of code that would horribly break if arithmetic expressions were being evaluated in a short-circuit fashion, so I don't think that could ever be so.

Body:
Concerning speed, if I need to calculate a large expression, say:

switch1*(large expression 1)+switch2*(large expression 2)

Depending on my input, switch1 can be 0 or 1, as can switch2 be. What would be the quickest for c++ to do, making an if statement or write it down as above?


问:
Defining keys using push method in JavaScript
I'm developing a simple shopping cart solution in JavaScript (Ionic 2 / Angular).

In PHP I just do the following:

```<code><?php
$cart = array(
    48131 => array(
        'size' => 'STANDART',
        'qty' => 1,
    )
);

print_r($cart);
</code>```

And the 48131 is the index, so after I can easily delete it (since I know that the key is 48131).

This is my JavaScript code (an example):

```<code>function addToCart() {
    this.cart = [];

    this.cart.push({
        id: this.id,
        size: this.size,
        qty: this.qty
    });

    console.log(this.cart);
}
</code>```

And this is what I get -

It looks like the push method just adds another key, starting from 0 (which I guess is normal). I've tried many things, I can't do it right... Can someone help?

答:
```<code>this.cart = {};
function addToCart() {
    this.cart[this.id]= {
        size: this.size,
        qty: this.qty
    };
   console.log(this.cart);
}
</code>```

Body:
I'm developing a simple shopping cart solution in JavaScript (Ionic 2 / Angular).

In PHP I just do the following:

<?php
$cart = array(
    48131 => array(
        'size' => 'STANDART',
        'qty' => 1,
    )
);

print_r($cart);

And the 48131 is the index, so after I can easily delete it (since I know that the key is 48131).

This is my JavaScript code (an example):

function addToCart() {
    this.cart = [];

    this.cart.push({
        id: this.id,
        size: this.size,
        qty: this.qty
    });

    console.log(this.cart);
}

And this is what I get -

It looks like the push method just adds another key, starting from 0 (which I guess is normal). I've tried many things, I can't do it right... Can someone help?


问:
what is the exception being thrown in this code:
```<code>public class Testex
{
    public static void main ( String[] args ) {
       double [] scores = new double [5];
       scores [5] = 95.75;

    }
}
</code>```

im not sure what exception is being thrown here, any help please

答: Are you trying to initialize score outside of bound? Java arrays start at 0. This looks like homework...</p>

Body:
public class Testex
{
    public static void main ( String[] args ) {
       double [] scores = new double [5];
       scores [5] = 95.75;

    }
}

im not sure what exception is being thrown here, any help please


问:
Add security headers to help protection from injection attacks in c# asp.net
I have a C# asp.net application.It was sent to security assessment and below were the risks.

```<code>-Missing "Content-Security-Policy" header
-Missing "X-Content-Type-Options" header
-Missing "X-XSS-Protection" header
-It was observed that server banner is getting disclosed in HTTP response.
-It was observed that service version is getting disclosed in HTTP response.
</code>```

I have the below code in the web.cofig file

```<code><httpProtocol>
<customHeaders>

<remove name="X-Powered-By"/>
<add name="X-Frame-Options" value="DENY"/>
<add name="X-XSS-Protection" value="1; mode=block"/>
<add name="X-Content-Type-Options" value="nosniff "/>

</customHeaders>
</httpProtocol>
</code>```

I thought this will add the headers. But the security team says the issue is not fixed. Is there any alternate for this.And for the Banner disclosure, I don't have access to server. can I fix this within the application.
After research I found this: Inside Global.asax I have this code:

```<code>protected void Application_PreSendRequestHeaders()
    {
        // Response.Headers.Remove("Server");
        Response.Headers.Set("Server", "My httpd server");
        Response.Headers.Remove("X-AspNet-Version");
        Response.Headers.Remove("X-AspNetMvc-Version");
    }

    protected void Application_BeginRequest(object sender, EventArgs e)
    {
        var app = sender as HttpApplication;
        if (app != null && app.Context != null)
        {
            app.Context.Response.Headers.Remove("Server");
        }
    }
</code>```

Is this the correct fix. Please help

答:
Adding and removing headers during Application_BeginRequest always leads to headaches with your server complaining about not being able to do things after headers are set.

Typically "X-AspNet-Version" and "X-AspNetMvc-Version" are IIS custom headers and removing them depends on the verion of IIS you are using.

With new versions of IIS you can set it in Web.Config:

```<code><system.web>
    <httpRuntime enableVersionHeader="false" />
</system.web>
</code>```

In older version you need to use IIS manager (see https://www.google.com/search?q=iis+remove++X-AspNet-Version&ie=utf-8&oe=utf-8):

You can remove the MVC header in app_start in Global.asax

```<code>MvcHandler.DisableMvcResponseHeader = true;
</code>```

Your web.config should work fine:

```<code><add name="X-Frame-Options" value="DENY"/>
<add name="X-XSS-Protection" value="1; mode=block"/>
<add name="X-Content-Type-Options" value="nosniff "/>
</code>```

If not, Application_PreSendRequestHeaders is an appropriate place to add or remove headers well.

```<code>HttpContext.Current.Response.Headers.Add("X-Frame-Options", "DENY");
HttpContext.Current.Response.Headers.Add("X-XSS-Protection", "1; mode=block");
HttpContext.Current.Response.Headers.Add("X-Content-Type-Options", "nosniff");
HttpContext.Current.Response.Headers.Remove("Server");
</code>```

You can use the web developer console on your web browser (usually opened by hitting F12) and click on the network tab to see what headers the server is sending.

Body:
I have a C# asp.net application.It was sent to security assessment and below were the risks.

-Missing "Content-Security-Policy" header
-Missing "X-Content-Type-Options" header
-Missing "X-XSS-Protection" header
-It was observed that server banner is getting disclosed in HTTP response.
-It was observed that service version is getting disclosed in HTTP response.

I have the below code in the web.cofig file

<httpProtocol>
<customHeaders>

<remove name="X-Powered-By"/>
<add name="X-Frame-Options" value="DENY"/>
<add name="X-XSS-Protection" value="1; mode=block"/>
<add name="X-Content-Type-Options" value="nosniff "/>

</customHeaders>
</httpProtocol>

I thought this will add the headers. But the security team says the issue is not fixed. Is there any alternate for this.And for the Banner disclosure, I don't have access to server. can I fix this within the application.
After research I found this: Inside Global.asax I have this code:

protected void Application_PreSendRequestHeaders()
    {
        // Response.Headers.Remove("Server");
        Response.Headers.Set("Server", "My httpd server");
        Response.Headers.Remove("X-AspNet-Version");
        Response.Headers.Remove("X-AspNetMvc-Version");
    }

    protected void Application_BeginRequest(object sender, EventArgs e)
    {
        var app = sender as HttpApplication;
        if (app != null && app.Context != null)
        {
            app.Context.Response.Headers.Remove("Server");
        }
    }

Is this the correct fix. Please help

Body:
Adding and removing headers during Application_BeginRequest always leads to headaches with your server complaining about not being able to do things after headers are set.

Typically "X-AspNet-Version" and "X-AspNetMvc-Version" are IIS custom headers and removing them depends on the verion of IIS you are using.

With new versions of IIS you can set it in Web.Config:

<system.web>
    <httpRuntime enableVersionHeader="false" />
</system.web>

In older version you need to use IIS manager (see https://www.google.com/search?q=iis+remove++X-AspNet-Version&ie=utf-8&oe=utf-8):

You can remove the MVC header in app_start in Global.asax

MvcHandler.DisableMvcResponseHeader = true;

Your web.config should work fine:

<add name="X-Frame-Options" value="DENY"/>
<add name="X-XSS-Protection" value="1; mode=block"/>
<add name="X-Content-Type-Options" value="nosniff "/>

If not, Application_PreSendRequestHeaders is an appropriate place to add or remove headers well.

HttpContext.Current.Response.Headers.Add("X-Frame-Options", "DENY");
HttpContext.Current.Response.Headers.Add("X-XSS-Protection", "1; mode=block");
HttpContext.Current.Response.Headers.Add("X-Content-Type-Options", "nosniff");
HttpContext.Current.Response.Headers.Remove("Server");

You can use the web developer console on your web browser (usually opened by hitting F12) and click on the network tab to see what headers the server is sending.


答:
Simply do </p>

```<code>function addToCart() {
    this.cart = [];

    this.cart['48131'] = {
        id: this.id,
        size: this.size,
        qty: this.qty
    };

    console.log(this.cart);
}
</code>```

Title: Defining keys using push method in JavaScript

Body:
Simply do

function addToCart() {
    this.cart = [];

    this.cart['48131'] = {
        id: this.id,
        size: this.size,
        qty: this.qty
    };

    console.log(this.cart);
}


问:
Why CreateDirectoryEx with long folder name is not working?
This is a sample code i have written to check if i am able to create a folder with name length greater than MAX_PATH -

```<code>wstring s = L"D:\\Test";
wstring s2 = L"\\?\D:\\datafffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffr700000000000000datafffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffr700000000000000datafffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffr700000000000000datafffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffr700000000000000datafffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffr700000000000000";

int ret = CreateDirectoryEx(s.c_str(), s2.c_str(), NULL);

int error = GetLastError();
</code>```

It did not work, the returned error is ERROR_PATH_NOT_FOUND. Can anyone please tell me whats the problem in the code?

Note: "D:\Test" folder is an existing folder. I am using Windows 7.

答: Because the path sizes are limited (to 160 caracters I think on W7 but not sure)</p>

Body:
This is a sample code i have written to check if i am able to create a folder with name length greater than MAX_PATH -

wstring s = L"D:\\Test";
wstring s2 = L"\\?\D:\\datafffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffr700000000000000datafffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffr700000000000000datafffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffr700000000000000datafffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffr700000000000000datafffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffr700000000000000";

int ret = CreateDirectoryEx(s.c_str(), s2.c_str(), NULL);

int error = GetLastError();

It did not work, the returned error is ERROR_PATH_NOT_FOUND. Can anyone please tell me whats the problem in the code?

Note: "D:\Test" folder is an existing folder. I am using Windows 7.


问:
required android.permission Read_External_storage, or grantUrlPermissions error
I think my permissions properly located on AndroidManifest.xml.

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.ganedu.intent">

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="23" />

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />

            </intent-filter>
        </activity>

        <activity android:name=".NextActivity"
            android:label="This is next_activity"/>
    </application>

</manifest>
</code>```

I have "android.permission.READ_EXTERNAL_STORAGE" and "android.permission.WRITE_EXTERNAL_STORAGE" right after manifest.

but the error is keep occured.

Caused by: java.lang.SecurityException: Permission Denial: reading
  com.android.providers.media.MediaProvider uri
  content://media/external/images/media/40 from pid=2473, uid=10073
  requires android.permission.READ_EXTERNAL_STORAGE, or
  grantUriPermission()

and this is my MainActivity.java

```<code>public class MainActivity extends AppCompatActivity {

public static final int IMAGE_GALLERY_REQUEST = 20;
Button btnStart;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
   }

public void gallery_open(View view) {
    Intent galleryPickerIntent = new Intent(Intent.ACTION_PICK);
    File pictureDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
    String pictureDirectoryPath = pictureDirectory.getPath();
    Uri data = Uri.parse(pictureDirectoryPath);
    galleryPickerIntent.setDataAndType(data,"image/*");
    startActivityForResult(galleryPickerIntent, IMAGE_GALLERY_REQUEST);

}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent){
    super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
    if(resultCode == Activity.RESULT_OK){
        if(requestCode ==  IMAGE_GALLERY_REQUEST) {
            onSelectedFromGalleryResult(imageReturnedIntent);
        }
    }

}

private void onSelectedFromGalleryResult(Intent data){
    Bitmap bm  = null;
    if(data != null){
        try{
            bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
        }catch(IOException e){
            e.printStackTrace();
        }
        //ivImage.setImageBitmap(bm);
        ImageView imgView = (ImageView)findViewById(R.id.ivImage);
        imgView.setImageBitmap(bm);

    }
}
</code>```

答:
James I suppose you are facing this error on Android 6.0 or onwards. You need to handle the permissions explicitly in these versions.
Please find the android developer link

https://developer.android.com/guide/topics/permissions/requesting.html

Body:
I think my permissions properly located on AndroidManifest.xml.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.ganedu.intent">

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="23" />

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />

            </intent-filter>
        </activity>

        <activity android:name=".NextActivity"
            android:label="This is next_activity"/>
    </application>

</manifest>

I have "android.permission.READ_EXTERNAL_STORAGE" and "android.permission.WRITE_EXTERNAL_STORAGE" right after manifest.

but the error is keep occured.

Caused by: java.lang.SecurityException: Permission Denial: reading
  com.android.providers.media.MediaProvider uri
  content://media/external/images/media/40 from pid=2473, uid=10073
  requires android.permission.READ_EXTERNAL_STORAGE, or
  grantUriPermission()

and this is my MainActivity.java

public class MainActivity extends AppCompatActivity {

public static final int IMAGE_GALLERY_REQUEST = 20;
Button btnStart;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
   }

public void gallery_open(View view) {
    Intent galleryPickerIntent = new Intent(Intent.ACTION_PICK);
    File pictureDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
    String pictureDirectoryPath = pictureDirectory.getPath();
    Uri data = Uri.parse(pictureDirectoryPath);
    galleryPickerIntent.setDataAndType(data,"image/*");
    startActivityForResult(galleryPickerIntent, IMAGE_GALLERY_REQUEST);

}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent){
    super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
    if(resultCode == Activity.RESULT_OK){
        if(requestCode ==  IMAGE_GALLERY_REQUEST) {
            onSelectedFromGalleryResult(imageReturnedIntent);
        }
    }

}

private void onSelectedFromGalleryResult(Intent data){
    Bitmap bm  = null;
    if(data != null){
        try{
            bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
        }catch(IOException e){
            e.printStackTrace();
        }
        //ivImage.setImageBitmap(bm);
        ImageView imgView = (ImageView)findViewById(R.id.ivImage);
        imgView.setImageBitmap(bm);

    }
}


问:
Loading sklearn model in Java. Model created with DNNClassifier in python
The goal is to open in Java a model created/trained in python with tensorflow.contrib.learn.learn.DNNClassifier.

At the moment the main issue is to know the name of the "tensor" to give in java on the session runner method.

I have this test code in python :

```<code>    from __future__ import division, print_function, absolute_import
import tensorflow as tf
import pandas as pd
import tensorflow.contrib.learn as learn
import numpy as np
from sklearn import metrics
from sklearn.cross_validation import train_test_split
from tensorflow.contrib import layers
from tensorflow.contrib.learn.python.learn.utils import input_fn_utils
from tensorflow.python.ops import array_ops
from tensorflow.python.framework import dtypes
from tensorflow.python.util.compat import as_text

print(tf.VERSION)

df = pd.read_csv('../NNNormalizeData-out.csv')

inputs = []
target = []

y=0;
for x in df.columns:
    if y != 35 :
        #print("added %d" %y)
        inputs.append(x)
    else :
        target.append(x)
    y+=1

total_inputs,total_output = df.as_matrix(inputs).astype(np.float32),df.as_matrix([target]).astype(np.int32)

train_inputs, test_inputs, train_output, test_output = train_test_split(total_inputs, total_output, test_size=0.2, random_state=42)

feature_columns = [tf.contrib.layers.real_valued_column("", dimension=train_inputs.shape[1],dtype=tf.float32)]
#target_column = [tf.contrib.layers.real_valued_column("output", dimension=train_output.shape[1])]

classifier = learn.DNNClassifier(hidden_units=[10, 20, 5], n_classes=5
                                 ,feature_columns=feature_columns)

classifier.fit(train_inputs, train_output, steps=100)

#Save Model into saved_model.pbtxt file (possible to Load in Java)
tfrecord_serving_input_fn = tf.contrib.learn.build_parsing_serving_input_fn(layers.create_feature_spec_for_parsing(feature_columns))
classifier.export_savedmodel(export_dir_base="test", serving_input_fn = tfrecord_serving_input_fn,as_text=True)

# Measure accuracy
pred = list(classifier.predict(test_inputs, as_iterable=True))
score = metrics.accuracy_score(test_output, pred)
print("Final score: {}".format(score))

# test individual samples
sample_1 = np.array( [[0.37671986791414125,0.28395908337619136,-0.0966095873607713,-1.0,0.06891621389763203,-0.09716678086712205,0.726029084013637,4.984689881073479E-4,-0.30296253267499107,-0.16192917054985334,0.04820256230479658,0.4951319883569152,0.5269983894210499,-0.2560313828048315,-0.3710980821053321,-0.4845867212612598,-0.8647234314469595,-0.6491591208322198,-1.0,-0.5004549422844073,-0.9880910165770813,0.5540293108747256,0.5625990251930839,0.7420121698556554,0.5445551415657979,0.4644276850235627,0.7316976292340245,0.636690006814346,0.16486621649984112,-0.0466018967678159,0.5261100063227044,0.6256168612312738,-0.544295484930702,0.379125782517193,0.6959368575211544]], dtype=float)
sample_2 = np.array( [[1.0,0.7982741870963959,1.0,-0.46270838239235024,0.040320274521029376,0.443451913224413,-1.0,1.0,1.0,-1.0,0.36689718911339564,-0.13577379160035796,-0.5162916256414466,-0.03373651520104648,1.0,1.0,1.0,1.0,0.786999801054777,-0.43856035121103853,-0.8199093927945158,1.0,-1.0,-1.0,-0.1134921695894473,-1.0,0.6420892436196663,0.7871737734493178,1.0,0.6501788845358409,1.0,1.0,1.0,-0.17586627413625022,0.8817194210401085]], dtype=float)

pred = list(classifier.predict(sample_2, as_iterable=True))
print("Prediction for sample_1 is:{} ".format(pred))

pred = list(classifier.predict_proba(sample_2, as_iterable=True))
print("Prediction for sample_2 is:{} ".format(pred))
</code>```

A model_saved.pbtxt file is created.

I try to load this model in Java with the following code :

```<code>    public class HelloTF {
    public static void main(String[] args) throws Exception {
        SavedModelBundle bundle=SavedModelBundle.load("/java/workspace/APIJavaSampleCode/tfModels/dnn/ModelSave","serve");
        Session s = bundle.session();

        double[] inputDouble = {1.0,0.7982741870963959,1.0,-0.46270838239235024,0.040320274521029376,0.443451913224413,-1.0,1.0,1.0,-1.0,0.36689718911339564,-0.13577379160035796,-0.5162916256414466,-0.03373651520104648,1.0,1.0,1.0,1.0,0.786999801054777,-0.43856035121103853,-0.8199093927945158,1.0,-1.0,-1.0,-0.1134921695894473,-1.0,0.6420892436196663,0.7871737734493178,1.0,0.6501788845358409,1.0,1.0,1.0,-0.17586627413625022,0.8817194210401085};
        float [] inputfloat=new float[inputDouble.length];
        for(int i=0;i<inputfloat.length;i++)
        {
            inputfloat[i]=(float)inputDouble[i];
        }
        Tensor inputTensor = Tensor.create(new long[] {35}, FloatBuffer.wrap(inputfloat) );

        Tensor result = s.runner()
                .feed("input_example_tensor", inputTensor)
                .fetch("dnn/multi_class_head/predictions/probabilities")
                .run().get(0);

         float[] m = new float[5];
         float[] vector = result.copyTo(m);
         float maxVal = 0;
         int inc = 0;
         int predict = -1;
         for(float val : vector)
         {
             System.out.println(val+"  ");
             if(val > maxVal) {
                 predict = inc;
                 maxVal = val;
             }
             inc++;
         }
         System.out.println(predict);

    }
}
</code>```

I get the error on the  .run().get(0); line  :

```<code>Exception in thread "main" org.tensorflow.TensorFlowException: Output 0 of type float does not match declared output type string for node _recv_input_example_tensor_0 = _Recv[_output_shapes=[[-1]], client_terminated=true, recv_device="/job:localhost/replica:0/task:0/cpu:0", send_device="/job:localhost/replica:0/task:0/cpu:0", send_device_incarnation=3663984897684684554, tensor_name="input_example_tensor:0", tensor_type=DT_STRING, _device="/job:localhost/replica:0/task:0/cpu:0"]()
    at org.tensorflow.Session.run(Native Method)
    at org.tensorflow.Session.access$100(Session.java:48)
    at org.tensorflow.Session$Runner.runHelper(Session.java:285)
    at org.tensorflow.Session$Runner.run(Session.java:235)
    at tensorflow.HelloTF.main(HelloTF.java:35)
</code>```

答:
Your parameters in .feed() and .fetch() should be matching with your input and output datatype.

You can look at your savedmodel.pbtxt file. There are details about your paramaters and their input/output types.

For instance,

my java code

```<code>Tensor result = s.runner()
        .feed("ParseExample/ParseExample", inputTensor)
        .fetch("dnn/binary_logistic_head/predictions/probabilities")
        .run().get(0);
</code>```

my savedModel.pbtxt (part of it)

```<code>node {
  name: "ParseExample/ParseExample"
  op: "ParseExample"
  input: "input_example_tensor"
  input: "ParseExample/ParseExample/names"
  input: "ParseExample/ParseExample/dense_keys_0"
  input: "ParseExample/Const"
  attr {
    key: "Ndense"
    value {
      i: 1
    }
  }
  attr {
    key: "Nsparse"
    value {
      i: 0
    }
  }
  attr {
    key: "Tdense"
    value {
      list {
        type: DT_FLOAT
      }
    }
  }
  attr {
    key: "_output_shapes"
    value {
      list {
        shape {
          dim {
            size: -1
          }
          dim {
            size: 2
          }
        }
      }
    }
  }
  attr {
    key: "dense_shapes"
    value {
      list {
        shape {
          dim {
            size: 2
          }
        }
      }
    }
  }
  attr {
    key: "sparse_types"
    value {
      list {
      }
    }
  }
}
  outputs {
    key: "scores"
    value {
      name: "dnn/binary_logistic_head/predictions/probabilities:0"
      dtype: DT_FLOAT
      tensor_shape {
        dim {
          size: -1
        }
        dim {
          size: 2
        }
      }
    }
  }
</code>```

They both compatible with my datatype, float.

Body:
The goal is to open in Java a model created/trained in python with tensorflow.contrib.learn.learn.DNNClassifier.

At the moment the main issue is to know the name of the "tensor" to give in java on the session runner method.

I have this test code in python :

    from __future__ import division, print_function, absolute_import
import tensorflow as tf
import pandas as pd
import tensorflow.contrib.learn as learn
import numpy as np
from sklearn import metrics
from sklearn.cross_validation import train_test_split
from tensorflow.contrib import layers
from tensorflow.contrib.learn.python.learn.utils import input_fn_utils
from tensorflow.python.ops import array_ops
from tensorflow.python.framework import dtypes
from tensorflow.python.util.compat import as_text

print(tf.VERSION)

df = pd.read_csv('../NNNormalizeData-out.csv')

inputs = []
target = []

y=0;
for x in df.columns:
    if y != 35 :
        #print("added %d" %y)
        inputs.append(x)
    else :
        target.append(x)
    y+=1

total_inputs,total_output = df.as_matrix(inputs).astype(np.float32),df.as_matrix([target]).astype(np.int32)

train_inputs, test_inputs, train_output, test_output = train_test_split(total_inputs, total_output, test_size=0.2, random_state=42)

feature_columns = [tf.contrib.layers.real_valued_column("", dimension=train_inputs.shape[1],dtype=tf.float32)]
#target_column = [tf.contrib.layers.real_valued_column("output", dimension=train_output.shape[1])]

classifier = learn.DNNClassifier(hidden_units=[10, 20, 5], n_classes=5
                                 ,feature_columns=feature_columns)

classifier.fit(train_inputs, train_output, steps=100)

#Save Model into saved_model.pbtxt file (possible to Load in Java)
tfrecord_serving_input_fn = tf.contrib.learn.build_parsing_serving_input_fn(layers.create_feature_spec_for_parsing(feature_columns))
classifier.export_savedmodel(export_dir_base="test", serving_input_fn = tfrecord_serving_input_fn,as_text=True)

# Measure accuracy
pred = list(classifier.predict(test_inputs, as_iterable=True))
score = metrics.accuracy_score(test_output, pred)
print("Final score: {}".format(score))

# test individual samples
sample_1 = np.array( [[0.37671986791414125,0.28395908337619136,-0.0966095873607713,-1.0,0.06891621389763203,-0.09716678086712205,0.726029084013637,4.984689881073479E-4,-0.30296253267499107,-0.16192917054985334,0.04820256230479658,0.4951319883569152,0.5269983894210499,-0.2560313828048315,-0.3710980821053321,-0.4845867212612598,-0.8647234314469595,-0.6491591208322198,-1.0,-0.5004549422844073,-0.9880910165770813,0.5540293108747256,0.5625990251930839,0.7420121698556554,0.5445551415657979,0.4644276850235627,0.7316976292340245,0.636690006814346,0.16486621649984112,-0.0466018967678159,0.5261100063227044,0.6256168612312738,-0.544295484930702,0.379125782517193,0.6959368575211544]], dtype=float)
sample_2 = np.array( [[1.0,0.7982741870963959,1.0,-0.46270838239235024,0.040320274521029376,0.443451913224413,-1.0,1.0,1.0,-1.0,0.36689718911339564,-0.13577379160035796,-0.5162916256414466,-0.03373651520104648,1.0,1.0,1.0,1.0,0.786999801054777,-0.43856035121103853,-0.8199093927945158,1.0,-1.0,-1.0,-0.1134921695894473,-1.0,0.6420892436196663,0.7871737734493178,1.0,0.6501788845358409,1.0,1.0,1.0,-0.17586627413625022,0.8817194210401085]], dtype=float)

pred = list(classifier.predict(sample_2, as_iterable=True))
print("Prediction for sample_1 is:{} ".format(pred))

pred = list(classifier.predict_proba(sample_2, as_iterable=True))
print("Prediction for sample_2 is:{} ".format(pred))

A model_saved.pbtxt file is created.

I try to load this model in Java with the following code :

    public class HelloTF {
    public static void main(String[] args) throws Exception {
        SavedModelBundle bundle=SavedModelBundle.load("/java/workspace/APIJavaSampleCode/tfModels/dnn/ModelSave","serve");
        Session s = bundle.session();

        double[] inputDouble = {1.0,0.7982741870963959,1.0,-0.46270838239235024,0.040320274521029376,0.443451913224413,-1.0,1.0,1.0,-1.0,0.36689718911339564,-0.13577379160035796,-0.5162916256414466,-0.03373651520104648,1.0,1.0,1.0,1.0,0.786999801054777,-0.43856035121103853,-0.8199093927945158,1.0,-1.0,-1.0,-0.1134921695894473,-1.0,0.6420892436196663,0.7871737734493178,1.0,0.6501788845358409,1.0,1.0,1.0,-0.17586627413625022,0.8817194210401085};
        float [] inputfloat=new float[inputDouble.length];
        for(int i=0;i<inputfloat.length;i++)
        {
            inputfloat[i]=(float)inputDouble[i];
        }
        Tensor inputTensor = Tensor.create(new long[] {35}, FloatBuffer.wrap(inputfloat) );

        Tensor result = s.runner()
                .feed("input_example_tensor", inputTensor)
                .fetch("dnn/multi_class_head/predictions/probabilities")
                .run().get(0);

         float[] m = new float[5];
         float[] vector = result.copyTo(m);
         float maxVal = 0;
         int inc = 0;
         int predict = -1;
         for(float val : vector)
         {
             System.out.println(val+"  ");
             if(val > maxVal) {
                 predict = inc;
                 maxVal = val;
             }
             inc++;
         }
         System.out.println(predict);

    }
}

I get the error on the  .run().get(0); line  :

Exception in thread "main" org.tensorflow.TensorFlowException: Output 0 of type float does not match declared output type string for node _recv_input_example_tensor_0 = _Recv[_output_shapes=[[-1]], client_terminated=true, recv_device="/job:localhost/replica:0/task:0/cpu:0", send_device="/job:localhost/replica:0/task:0/cpu:0", send_device_incarnation=3663984897684684554, tensor_name="input_example_tensor:0", tensor_type=DT_STRING, _device="/job:localhost/replica:0/task:0/cpu:0"]()
    at org.tensorflow.Session.run(Native Method)
    at org.tensorflow.Session.access$100(Session.java:48)
    at org.tensorflow.Session$Runner.runHelper(Session.java:285)
    at org.tensorflow.Session$Runner.run(Session.java:235)
    at tensorflow.HelloTF.main(HelloTF.java:35)

Body:
Your parameters in .feed() and .fetch() should be matching with your input and output datatype.

You can look at your savedmodel.pbtxt file. There are details about your paramaters and their input/output types.

For instance,

my java code

Tensor result = s.runner()
        .feed("ParseExample/ParseExample", inputTensor)
        .fetch("dnn/binary_logistic_head/predictions/probabilities")
        .run().get(0);

my savedModel.pbtxt (part of it)

node {
  name: "ParseExample/ParseExample"
  op: "ParseExample"
  input: "input_example_tensor"
  input: "ParseExample/ParseExample/names"
  input: "ParseExample/ParseExample/dense_keys_0"
  input: "ParseExample/Const"
  attr {
    key: "Ndense"
    value {
      i: 1
    }
  }
  attr {
    key: "Nsparse"
    value {
      i: 0
    }
  }
  attr {
    key: "Tdense"
    value {
      list {
        type: DT_FLOAT
      }
    }
  }
  attr {
    key: "_output_shapes"
    value {
      list {
        shape {
          dim {
            size: -1
          }
          dim {
            size: 2
          }
        }
      }
    }
  }
  attr {
    key: "dense_shapes"
    value {
      list {
        shape {
          dim {
            size: 2
          }
        }
      }
    }
  }
  attr {
    key: "sparse_types"
    value {
      list {
      }
    }
  }
}
  outputs {
    key: "scores"
    value {
      name: "dnn/binary_logistic_head/predictions/probabilities:0"
      dtype: DT_FLOAT
      tensor_shape {
        dim {
          size: -1
        }
        dim {
          size: 2
        }
      }
    }
  }

They both compatible with my datatype, float.


问:
Admin LTE theme + Laravel Mini sidebar issue
I used Admin LTE theme with Laravel and stucked at one known issue,
there is no solution of that in Admin LTE theme,
IF I toggle side bar its showing miniside bar,
but when i navigate to another page the toggled sidebar again opened,
It should not open because i already minimized it,

Please help,

答:
Your Sidebar is open. So the body doesn't have the class sidebar-collapse.

Once you toggle it, the mini sidebar shows up. So the body has sidebar-collapse.

Now when you navigate to other url the body will not have the class sidebar-collapse, that's why side bar is opened.

Now you need to add the class sidebar-collapse when you navigate to another page.

Trigger the sidebar-toggle and add a variable to localstorage which will have TRUE as its value.

Now when you navigate to another page, fetch the localstorage variable value and add the class to body by checking localstorage variable.

Ex :

```<code>$('.sidebar-toggle').on('click',function(){
           var cls =  $('body').hasClass('sidebar-collapse');
           if(cls == true){
                localStorage.setItem('collapse',0);
           } else {
                localStorage.setItem('collapse',1);
           }

    });

   window.onload = function() {
       var collapse = localStorage.getItem('collapse');
       if(collapse == true){
            $('body').addClass('sidebar-collapse');
       } else if(collapse == false) {
            $('body').removeClass('sidebar-collapse');
       }
    }
</code>```

I hope this will help you.

Body:
Your Sidebar is open. So the body doesn't have the class sidebar-collapse.

Once you toggle it, the mini sidebar shows up. So the body has sidebar-collapse.

Now when you navigate to other url the body will not have the class sidebar-collapse, that's why side bar is opened.

Now you need to add the class sidebar-collapse when you navigate to another page.

Trigger the sidebar-toggle and add a variable to localstorage which will have TRUE as its value.

Now when you navigate to another page, fetch the localstorage variable value and add the class to body by checking localstorage variable.

Ex :

$('.sidebar-toggle').on('click',function(){
           var cls =  $('body').hasClass('sidebar-collapse');
           if(cls == true){
                localStorage.setItem('collapse',0);
           } else {
                localStorage.setItem('collapse',1);
           }

    });

   window.onload = function() {
       var collapse = localStorage.getItem('collapse');
       if(collapse == true){
            $('body').addClass('sidebar-collapse');
       } else if(collapse == false) {
            $('body').removeClass('sidebar-collapse');
       }
    }

I hope this will help you.


问:
How to add Facebook dependency in offline mode on Android Studio
I am trying to write a program that can make Facebook updates but i have issues adding the Facebook dependency. I already have the sdk but couldn't add to my project because...
even though i have tried adding the gradle.prperties file to the extracted Facebook folder as a comment suggested here

Next i tried adding as suggested on the Facebook official page but i hit this snag...

Now, because if the price of data where I'm from, I'd rather not go online since I already have the sdk locally so my question is how can i manually cache the sdk into my project?

EDIT: For clarity, my question is HOW DO I ADD THE FACEBOOK SDK INTO MY PROJECT WITHOUT GOING ONLINE (i.e. OFFLINE BUILD)?

答: try this offline mode on Android Studio

Body: try this offline mode on Android Studio


问:
Queue of node-horseman calls
I'm developing a web scraper (in its early stages) and I plan to do x horseman calls. This calls are promise based but I want the calls to be sequentially, when one finishes, the next starts.

How can I achieve this behavior?

答:
You can simply do something like:

```<code>asyncCall(args[1]).done(() => asyncCall(args[2]))
</code>```

Here asyncCall is whatever function you need to call. It takes some arguments and returns a Promise.

So you are basically waiting for the result of one call and then invoking the second call.

However, this can get pretty unwieldy when there's a lot of calls to make. If you are using async/await, which you should, given that you're working on a new project,  you can code it much better like:

```<code>await asyncCall(args[1]);
await asyncCall(args[2]);
...
</code>```

Or, even better:

```<code>for (let arg of args) {
    await asyncCall(arg)
}
</code>```

Title: Queue of node-horseman calls

Body:
You can simply do something like:

asyncCall(args[1]).done(() => asyncCall(args[2]))

Here asyncCall is whatever function you need to call. It takes some arguments and returns a Promise.

So you are basically waiting for the result of one call and then invoking the second call.

However, this can get pretty unwieldy when there's a lot of calls to make. If you are using async/await, which you should, given that you're working on a new project,  you can code it much better like:

await asyncCall(args[1]);
await asyncCall(args[2]);
...

Or, even better:

for (let arg of args) {
    await asyncCall(arg)
}


问:
MalformedJsonException on Retrofit and Gson
I'm trying to make a retrofit call and i'm getting MalformedJsonException.

This is my call:

```<code>String idFoto = "1ead0a1f-bbc4-46bd-901c-7988c0e6c68b";
Retrofit retrofit = new Retrofit.Builder()
     .baseUrl(Global.URL_BASE)
     .addConverterFactory(GsonConverterFactory.create())
     .build();
FotosAPI service = retrofit.create(FotosAPI.class);
Call<String> obtenerFotoCall = service.getFoto(Global.getToken(), idFoto);
</code>```

This is my interface:

```<code>public interface FotosAPI {
     @GET(Global.URL_FOTO + "{id}")
     Call<String> getFoto(@Header("Authorization") String token, @Path("id") String id);
}
</code>```

The call enqueue enters onFailure method, and the error is "com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 2 path $".

I made the changes to set lenient like this:

```<code>Gson gson = new GsonBuilder().setLenient().create();
Retrofit retrofit = new Retrofit.Builder()
     .baseUrl(Global.URL_BASE)
     .addConverterFactory(GsonConverterFactory.create(gson))
     .build();
</code>```

Then, I have a different error: "com.google.gson.stream.MalformedJsonException: Expected value at line 1 column 1 path $"

I think that the error maybe is in the conversion of Gson of the idFoto string value, but I don't know what is wrong.

Can someone help me please?

Thank you guys!

答:
Like M D says (thank you very much man!), the solution is to change GsonConverter for ToStringCorverterFactory.

This is the class that I use:

```<code>import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;

public class ToStringConverterFactory extends Converter.Factory {
    private static final MediaType MEDIA_TYPE = MediaType.parse("text/plain");

    @Override
    public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
        if (String.class.equals(type)) {
            return new Converter<ResponseBody, String>() {
                @Override
                public String convert(ResponseBody value) throws IOException {
                    return value.string();
                }
            };
        }
        return null;
    }

    @Override
    public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations,
                                                          Annotation[] methodAnnotations, Retrofit retrofit) {

        if (String.class.equals(type)) {
            return new Converter<String, RequestBody>() {
                @Override
                public RequestBody convert(String value) throws IOException {
                    return RequestBody.create(MEDIA_TYPE, value);
                }
            };
        }
        return null;
    }
}
</code>```

And then you only have to change the retrofit builder to this:

```<code>Retrofit retrofit = new Retrofit.Builder()
                        .baseUrl(Global.URL_BASE)
                        .addConverterFactory(new ToStringConverterFactory())
                        .build();
</code>```

Body:
I'm trying to make a retrofit call and i'm getting MalformedJsonException.

This is my call:

String idFoto = "1ead0a1f-bbc4-46bd-901c-7988c0e6c68b";
Retrofit retrofit = new Retrofit.Builder()
     .baseUrl(Global.URL_BASE)
     .addConverterFactory(GsonConverterFactory.create())
     .build();
FotosAPI service = retrofit.create(FotosAPI.class);
Call<String> obtenerFotoCall = service.getFoto(Global.getToken(), idFoto);

This is my interface:

public interface FotosAPI {
     @GET(Global.URL_FOTO + "{id}")
     Call<String> getFoto(@Header("Authorization") String token, @Path("id") String id);
}

The call enqueue enters onFailure method, and the error is "com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 2 path $".

I made the changes to set lenient like this:

Gson gson = new GsonBuilder().setLenient().create();
Retrofit retrofit = new Retrofit.Builder()
     .baseUrl(Global.URL_BASE)
     .addConverterFactory(GsonConverterFactory.create(gson))
     .build();

Then, I have a different error: "com.google.gson.stream.MalformedJsonException: Expected value at line 1 column 1 path $"

I think that the error maybe is in the conversion of Gson of the idFoto string value, but I don't know what is wrong.

Can someone help me please?

Thank you guys!

Body:
Like M D says (thank you very much man!), the solution is to change GsonConverter for ToStringCorverterFactory.

This is the class that I use:

import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;

public class ToStringConverterFactory extends Converter.Factory {
    private static final MediaType MEDIA_TYPE = MediaType.parse("text/plain");

    @Override
    public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
        if (String.class.equals(type)) {
            return new Converter<ResponseBody, String>() {
                @Override
                public String convert(ResponseBody value) throws IOException {
                    return value.string();
                }
            };
        }
        return null;
    }

    @Override
    public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations,
                                                          Annotation[] methodAnnotations, Retrofit retrofit) {

        if (String.class.equals(type)) {
            return new Converter<String, RequestBody>() {
                @Override
                public RequestBody convert(String value) throws IOException {
                    return RequestBody.create(MEDIA_TYPE, value);
                }
            };
        }
        return null;
    }
}

And then you only have to change the retrofit builder to this:

Retrofit retrofit = new Retrofit.Builder()
                        .baseUrl(Global.URL_BASE)
                        .addConverterFactory(new ToStringConverterFactory())
                        .build();


问:
When I git commit some code, it prompts some errors as follows, what's wrong?

And the code management system that I used is Gerrit.

答:
Git expects a commit message description, through which you can explain what the code change is for etc. This helps other developers to understand your changes. Since you are using Gerrit, your code reviewers will know the reason for your changes easier.

Coming to the problem, For you it expects default editor to be "mate". Easier solution could be,

Pass the message as part git commit command itself.

Example: git commit -m "This commit is to fix problem XXXX"

Practical problems: If commit message is too long, this method is difficult. Better suited for smaller, single line commit messages.

Update the GIT global configuration to the editor of your preference.

  #git config --global core.editor "vi"

This will open "vi" editor through which you can add your commit
message and save the same.

Additional info for understanding:

1. Commit message can be edited anytime using "git commit --amend" command.

2. All global configurations are stored in ".gitconfig" file, mostly in your HOME(~) directory. You can also edit and save the same.

Hope it helps.


问:
The width of my header and the wrapper/container below
Can I get some help on making my full width header and top menus the same width as my main wrapper/container?

Here's a picture: http://soccer-mate.com/content/uploads/2017/07/IMG_1247.jpg

Here's what I have as custom CSS so far:

```<code>/* Structure */
#wrapper{
    min-height: 100%;
    position: relative;
    padding: 0.5px 0 20px;
}
#main{
    padding: 10px 10px 0;
}

/* Header */
#header{
    min-width: 990px;
    padding: 0;
}
#branding{
    width: 980px;
    margin: 0 auto;
    padding: 0;
}
.logo{
    max-width: 590px;
    float: left;
    padding: 30px 0 34px 10px;
}
.blog-name{
    margin: 0 0 3px;
    line-height: 1em;
    display: block;
}
.blog-description{
    line-height: 1em;
    display: block;
    margin: 0;
    padding: 3px 0 0;
}
#top-menu, #nav{
    min-width: 990px;
}
#top-menu-content, #nav-content{
    margin: 0 auto; width: 978px;
}
</code>```

Thanks.

答:
like this : </p>

```<code>#wrapper
{ width:100%;min-height: 100%; position: relative; padding: 0.5px 0 20px; }
</code>```

Body:
Can I get some help on making my full width header and top menus the same width as my main wrapper/container?

Here's a picture: http://soccer-mate.com/content/uploads/2017/07/IMG_1247.jpg

Here's what I have as custom CSS so far:

/* Structure */
#wrapper{
    min-height: 100%;
    position: relative;
    padding: 0.5px 0 20px;
}
#main{
    padding: 10px 10px 0;
}

/* Header */
#header{
    min-width: 990px;
    padding: 0;
}
#branding{
    width: 980px;
    margin: 0 auto;
    padding: 0;
}
.logo{
    max-width: 590px;
    float: left;
    padding: 30px 0 34px 10px;
}
.blog-name{
    margin: 0 0 3px;
    line-height: 1em;
    display: block;
}
.blog-description{
    line-height: 1em;
    display: block;
    margin: 0;
    padding: 3px 0 0;
}
#top-menu, #nav{
    min-width: 990px;
}
#top-menu-content, #nav-content{
    margin: 0 auto; width: 978px;
}

Thanks.

Body:
like this :

#wrapper
{ width:100%;min-height: 100%; position: relative; padding: 0.5px 0 20px; }


问:
Data structures linked list
I was asked to solve this out:

There are two singly linked lists.
I need to write a method which get those two linked lists and returns a pointer to the starting point where the suffix is the same in those two lists.

Example:

given:

```<code>1->2->4->6->8->10->15
2->4->8->10->15
</code>```

the returned value would be a pointer to the member - 8.

But,
I need to do it without changing the lists or using more memory,
and - we need to scan the lists only once, means T(n)=O(n).

答:
This is a psuedocode.. not Python code for that matter
take the two lists and let p1 point to longer list and p2 point to shorter list,</p>

```<code>while p1->next!=NULL:
   if p1->value = p2->value:
      p1 = p1->next
      p2 = p2->next
   else:
      p1 = p1->next
      returnpointer = p1->next// if it happens that some elements are same towards end but not the last element.. p1->next would be pointing to NULL anyways and else.. it'll always be the element next to the last element which wasn't same
return returnpointer
</code>```

Title: Data structures linked list

Body:
I was asked to solve this out:

There are two singly linked lists.
I need to write a method which get those two linked lists and returns a pointer to the starting point where the suffix is the same in those two lists.

Example:

given:

1->2->4->6->8->10->15
2->4->8->10->15

the returned value would be a pointer to the member - 8.

But,
I need to do it without changing the lists or using more memory,
and - we need to scan the lists only once, means T(n)=O(n).

Body:
This is a psuedocode.. not Python code for that matter
take the two lists and let p1 point to longer list and p2 point to shorter list,

while p1->next!=NULL:
   if p1->value = p2->value:
      p1 = p1->next
      p2 = p2->next
   else:
      p1 = p1->next
      returnpointer = p1->next// if it happens that some elements are same towards end but not the last element.. p1->next would be pointing to NULL anyways and else.. it'll always be the element next to the last element which wasn't same
return returnpointer