问:
Dynamic ng-bind inside a custom directive merging
I have a button formed from my custom directive where once the user clicks it will go into $scope.countClicker in the controller where it will count the number of times the button has been clicked. The number of times it being clicked will associate the city name it will pass through to the Data factory. Then from the data from the Data factory it will create a panel as shown in directive.js

My problem is once I click more than once, all the expressions that SHOULD be unique turn to be the same. For example, $scope.name3 should only show "Osaka", but the previous 3 panels which all should have unique ID from my for loop ($scope.name0, $scope.name1, $scope.name2) all have "Osaka" as their title as well. I originally planned that the number of clicks could be used as an unique ID so each panel wouldn't clash with each other, but for some reason it is.

If anyone can please help point out why this is happening that would be greatly appreciated. Thank you!

directive.js:

```<code>app.directive('addbuttonsbutton', function() {
    return {
        restrict: "A",
        template: "<md-button addbuttons ng-click='clickCounter()' class='md-fab md-mini'>+</md-button>"
    }
});

//Directive for adding buttons on click that show an alert on click

 app.directive('addbuttons', function($compile) {
     return function(scope, element, attrs) {
         element.bind("click", function() {
             scope.count++;
             var counter = scope.count;
             console.log('this is scope count' + scope.count);
             angular.element(document.getElementById('space-for-buttons')).prepend($compile( //adding a panel to my view
                 "<div class= panel>" +
                 "<h3 id=title" + scope.count + ">{{name" + scope.count + "| uppercase}}</h3><br>" +
                 "<i ng-class=weatherClass id=icon></i>" +
                 "<h3 id= temp >{{fTemp" + scope.count + " | uppercase}}</h3>" +
                 "<p style= 'color: #FAFAFA;' >{{description" + scope.count + "| uppercase}}</p>" +
                 "<p>{{location}}</p><br>" +
                 "<div id= wrapper ><div id= first ><i id= smallIcons  class= 'wi wi-horizon-alt' ></i>" +
                 "<p id= eventID >SUNRISE</p><p id= subID >{{formattedSunrise" + scope.count + "}}</p></div>" +
                 "<div id= second ><i class=  'wi wi-strong-wind'  id= smallIcons ></i>" +
                 "<p id= eventID >WIND</p><p id= subID >{{speed" + scope.count + "}}</p></div>" +
                 "<div id= third ><i class=  'wi wi-humidity'  id= smallIcons ></i>" +
                 "<p id= eventID >HUMIDITY</p><p id= subID >{{humidity}}</p></div></div></div>")(scope));
         });
     };
 });
</code>```

Controller:

```<code>var app = angular.module('weatherApp.controllers', []);

app.controller('weatherCtrl', ['$scope', 'Data',

        function($scope, Data) {
            $scope.count = -1;

            $scope.city = 'Berkeley';
            var cityCounting = 0;
            var counter = 0;

            var cities = [
          'Sydney, AU',
          'Melbourne, AU',
          'Tokyo',
          'Osaka',
          'Seoul',
          'Hong Kong',
          'London',
          'Amsterdam',
          'Berlin',
          'Paris',
          'Barcelona',
          'New York',
          'Dubai',
          'Antarctica'
        ];

            $scope.clickCounter = function(){
                cityCounting = counter++;
                $scope.city = cities[cityCounting];
                console.log($scope.city);
                console.log(cityCounting);
               Data.getApps($scope.city).then(function(data) {

             for (var i = 0; i < 14; i++) {
                $scope.data = data;

                $scope['name' + i] = data.name;

                $scope['temp'+i] = data.main.temp;

                $scope['fTemp' + i ] = ($scope['temp' + i] * (9 / 5) - 459.67).toFixed(1) + " °F";
            }//end of for loop

            }); end of Data service
            }//end of controller
</code>```

答:
You can remove your for loop which is reassigning the same data to every variable by the help of your click count.</p>

```<code>$scope['name' + cityCounting] = data.name;

$scope['temp'+cityCounting] = data.main.temp;

$scope['fTemp' + cityCounting] = ($scope['temp' + cityCounting] * (9 / 5) - 459.67).toFixed(1) + " °F";
</code>```

Body:
I have a button formed from my custom directive where once the user clicks it will go into $scope.countClicker in the controller where it will count the number of times the button has been clicked. The number of times it being clicked will associate the city name it will pass through to the Data factory. Then from the data from the Data factory it will create a panel as shown in directive.js

My problem is once I click more than once, all the expressions that SHOULD be unique turn to be the same. For example, $scope.name3 should only show "Osaka", but the previous 3 panels which all should have unique ID from my for loop ($scope.name0, $scope.name1, $scope.name2) all have "Osaka" as their title as well. I originally planned that the number of clicks could be used as an unique ID so each panel wouldn't clash with each other, but for some reason it is.

If anyone can please help point out why this is happening that would be greatly appreciated. Thank you!

directive.js:

app.directive('addbuttonsbutton', function() {
    return {
        restrict: "A",
        template: "<md-button addbuttons ng-click='clickCounter()' class='md-fab md-mini'>+</md-button>"
    }
});

//Directive for adding buttons on click that show an alert on click

 app.directive('addbuttons', function($compile) {
     return function(scope, element, attrs) {
         element.bind("click", function() {
             scope.count++;
             var counter = scope.count;
             console.log('this is scope count' + scope.count);
             angular.element(document.getElementById('space-for-buttons')).prepend($compile( //adding a panel to my view
                 "
" +
                 "
{{name" + scope.count + "| uppercase}}

" +
                 "" +
                 "
{{fTemp" + scope.count + " | uppercase}}
" +
                 "
{{description" + scope.count + "| uppercase}}
" +
                 "
{{location}}

" +
                 "

" +
                 "
SUNRISE

{{formattedSunrise" + scope.count + "}}

" +
                 "
" +
                 "
WIND

{{speed" + scope.count + "}}

" +
                 "
" +
                 "
HUMIDITY

{{humidity}}

")(scope));
         });
     };
 });

Controller:

var app = angular.module('weatherApp.controllers', []);

app.controller('weatherCtrl', ['$scope', 'Data',

        function($scope, Data) {
            $scope.count = -1;

            $scope.city = 'Berkeley';
            var cityCounting = 0;
            var counter = 0;

            var cities = [
          'Sydney, AU',
          'Melbourne, AU',
          'Tokyo',
          'Osaka',
          'Seoul',
          'Hong Kong',
          'London',
          'Amsterdam',
          'Berlin',
          'Paris',
          'Barcelona',
          'New York',
          'Dubai',
          'Antarctica'
        ];

            $scope.clickCounter = function(){
                cityCounting = counter++;
                $scope.city = cities[cityCounting];
                console.log($scope.city);
                console.log(cityCounting);
               Data.getApps($scope.city).then(function(data) {

             for (var i = 0; i < 14; i++) {
                $scope.data = data;

                $scope['name' + i] = data.name;

                $scope['temp'+i] = data.main.temp;

                $scope['fTemp' + i ] = ($scope['temp' + i] * (9 / 5) - 459.67).toFixed(1) + " °F";
            }//end of for loop

            }); end of Data service
            }//end of controller

Body:
You can remove your for loop which is reassigning the same data to every variable by the help of your click count.

$scope['name' + cityCounting] = data.name;

$scope['temp'+cityCounting] = data.main.temp;

$scope['fTemp' + cityCounting] = ($scope['temp' + cityCounting] * (9 / 5) - 459.67).toFixed(1) + " °F";


来源: stackexchange

问:
What does "@Override" and "<? extends Page>" mean?
```<code>@Override
public Class< ? extends Page> getHomePage() {
            return HomePage.class;
}

public Class<HomePage> getHomePage(){
        return HomePage.class;
}
</code>```

The first one has an annotation
    Override. What does that mean or
    what does it send to the framework.

Will both the methods return the same class. I mean what does this mean  ? extends Page. I mean the ? Mark.

答:
1) Override Annotation

Javadoc : Indicates that a method declaration is intended to override a method declaration in a superclass. If a method is annotated with this annotation type but does not override a superclass method, compilers are required to generate an error message.

2) ? means any. for example :  < ? > means any java data type can be here

< ? extends Page > means any subclass of Page is allowed here.

ContentLicense: CC BY-SA 2.5

Body:
@Override
public Class< ? extends Page> getHomePage() {
            return HomePage.class;
}

public Class<HomePage> getHomePage(){
        return HomePage.class;
}

The first one has an annotation
    Override. What does that mean or
    what does it send to the framework.

Will both the methods return the same class. I mean what does this mean  ? extends Page. I mean the ? Mark.


问:
Changing Drawer left and right button image dynamically?
react-native-router-flux v3.37.0
react-native v0.42.0

I'm trying to update drawer navigation bar right image dynamically where I have used leftButtonImage, rightButtonImage, where once user read all the notification I want to change the button image.

I could not manage to re-render or update this button image, Is this feature not supported or is there something that I'm missing?

答:
You can call Actions.refresh when you need to refresh the view, example:

```<code>Actions.refresh({key: 'profileView', renderRightButton: this.renderRightButton });
</code>```

and also define renderRightButton:

```<code>renderRightButton() {
    return (
          <TouchableOpacity onPress={ console.log(this) } >
             <Text>Logout</Text>
          </TouchableOpacity>
        )
}
</code>```

and lastly don't forget to import Actions from react-native-router-flux

```<code>import {Actions} from 'react-native-router-flux';
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You can call Actions.refresh when you need to refresh the view, example:

Actions.refresh({key: 'profileView', renderRightButton: this.renderRightButton });

and also define renderRightButton:

renderRightButton() {
    return (
          <TouchableOpacity onPress={ console.log(this) } >
             <Text>Logout</Text>
          </TouchableOpacity>
        )
}

and lastly don't forget to import Actions from react-native-router-flux

import {Actions} from 'react-native-router-flux';


问:
Returning a value of match in images from feature point detection
I'm using a feature point detection algorithm I found in a tutorial as shown below. The output of this code are lines drawn between the two images where feature points match.

Here's what I would like to know: Is there a way to return some value (floating point value) to determine if the two images are almost same, somewhat similar or not same?

```<code>def feature_matching():

    img1 = cv2.imread('image1.jpeg', 0)

    img2 = cv2.imread('image2.jpeg', 0)

    # Initiate SIFT detector
    sift = cv2.SIFT()

    # find the keypoints and descriptors with SIFT
    kp1, des1 = sift.detectAndCompute(img1,None)
    kp2, des2 = sift.detectAndCompute(img2,None)

    # BFMatcher with default params
    bf = cv2.BFMatcher()
    matches = bf.knnMatch(des1,des2, k=2)

    # Apply ratio test
    good = []
    for m,n in matches:
        if m.distance < 0.75*n.distance:
            good.append(m)

    #gray1 = cv2.cvtColor(img1,cv2.COLOR_BGR2GRAY)
    #gray2 = cv2.cvtColor(img2,cv2.COLOR_BGR2GRAY)
    # cv2.drawMatchesKnn expects list of lists as matches.
    img3 = drawMatches(img1,kp1,img2,kp2,good)

    plt.imshow(img3),plt.show()
</code>```

答:
If you want a simple float value indicating the measure of the match, you can use some very simple techniques like template matching. If you have a lot of training images you can use a machine learning approach like the HOG SVMs

These are simpler techniques to performing feature detection, matching, etc

Body:
I'm using a feature point detection algorithm I found in a tutorial as shown below. The output of this code are lines drawn between the two images where feature points match.

Here's what I would like to know: Is there a way to return some value (floating point value) to determine if the two images are almost same, somewhat similar or not same?

def feature_matching():

    img1 = cv2.imread('image1.jpeg', 0)

    img2 = cv2.imread('image2.jpeg', 0)

    # Initiate SIFT detector
    sift = cv2.SIFT()

    # find the keypoints and descriptors with SIFT
    kp1, des1 = sift.detectAndCompute(img1,None)
    kp2, des2 = sift.detectAndCompute(img2,None)

    # BFMatcher with default params
    bf = cv2.BFMatcher()
    matches = bf.knnMatch(des1,des2, k=2)

    # Apply ratio test
    good = []
    for m,n in matches:
        if m.distance < 0.75*n.distance:
            good.append(m)

    #gray1 = cv2.cvtColor(img1,cv2.COLOR_BGR2GRAY)
    #gray2 = cv2.cvtColor(img2,cv2.COLOR_BGR2GRAY)
    # cv2.drawMatchesKnn expects list of lists as matches.
    img3 = drawMatches(img1,kp1,img2,kp2,good)

    plt.imshow(img3),plt.show()


问:
How to save another new files one by one in different name by using .csv file in C#
I have .csv file that sample of file is like this,

```<code>    Date,Pass,CutMark1,Marks1,CutMark2,Marks2
22/06/2017 13:04:18,FALSE,TRUE,TRUE,FALSE,FALSE
22/06/2017 13:04:20,FALSE,TRUE,TRUE,FALSE,FALSE
22/06/2017 13:04:35,FALSE,TRUE,TRUE,FALSE,FALSE
22/06/2017 13:04:37,FALSE,TRUE,TRUE,FALSE,FALSE
22/06/2017 13:04:37,FALSE,TRUE,TRUE,FALSE,FALSE
22/06/2017 13:04:38,FALSE,FALSE,TRUE,FALSE,FALSE
22/06/2017 13:04:39,FALSE,FALSE,TRUE,FALSE,FALSE
22/06/2017 13:04:40,FALSE,FALSE,TRUE,TRUE,FALSE
22/06/2017 13:04:41,FALSE,FALSE,TRUE,TRUE,TRUE
22/06/2017 13:04:42,FALSE,FALSE,FALSE,TRUE,TRUE
22/06/2017 13:04:44,FALSE,FALSE,FALSE,TRUE,TRUE
22/06/2017 13:04:45,TRUE,FALSE,FALSE,TRUE,TRUE
22/06/2017 13:04:46,TRUE,FALSE,FALSE,TRUE,TRUE
22/06/2017 13:04:48,TRUE,FALSE,FALSE,FALSE,TRUE
22/06/2017 13:04:49,TRUE,FALSE,FALSE,FALSE,TRUE
22/06/2017 13:04:50,TRUE,FALSE,FALSE,FALSE,TRUE
22/06/2017 13:04:52,FALSE,TRUE,TRUE,FALSE,TRUE
22/06/2017 13:04:53,FALSE,TRUE,TRUE,FALSE,TRUE
22/06/2017 13:04:54,FALSE,TRUE,TRUE,FALSE,TRUE
22/06/2017 13:04:56,FALSE,TRUE,TRUE,FALSE,TRUE
22/06/2017 13:04:57,FALSE,TRUE,TRUE,FALSE,TRUE
22/06/2017 13:04:58,FALSE,TRUE,TRUE,FALSE,TRUE
22/06/2017 13:05:00,TRUE,TRUE,TRUE,TRUE,FALSE
22/06/2017 13:05:01,TRUE,TRUE,TRUE,TRUE,FALSE
22/06/2017 13:05:02,TRUE,TRUE,TRUE,TRUE,FALSE
22/06/2017 13:05:04,TRUE,TRUE,TRUE,TRUE,FALSE
22/06/2017 13:05:05,TRUE,TRUE,TRUE,TRUE,FALSE
22/06/2017 13:05:06,TRUE,TRUE,TRUE,TRUE,FALSE
22/06/2017 13:05:08,TRUE,TRUE,TRUE,TRUE,FALSE
</code>```

So now I want to save this file as follows;In here Pass column data flow is like this,FALSE>TRUE>FALSE>TRUE ..this is sample of my .csv file.but there is more raw in original file.In here I want to Separate this original .csv file like following ;

First met False so all of False details And check Marks1=TRUE then save Discharge1_Mark1.csv,and look at Marks2 column and if that column true then save Discharge1_Mark2.csv.

Secondly Pass column meet True then check Marks1=TRUE then save Charge1_Mark1.csv,then if  Marks2=true then save Charge1_Mark2.csv.

NOw again Pass column meet False then want to save file Discharge2_Marks1.csv.
like that I want to save my files.

I want to say in here Accordingly Pass column TRUE,False you want to save file like i mentioned before as which time that TRUE,FALSE meet.1,2,3,...you want to check respective pass column TRUE false with respective Marks1,Marks2 column.
In here I want to save my generated file respective therir columns.

If I save Marks1 then column headers should (Date,Pass,CutMarks1,Marks1 )
If i save Marks2 then column header should (Date,Pass,CutMarks2,Marks2)

Please give how I generate files as I mentioned before in my code.my code is following.

```<code>using System.Globalization;

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

  private void btnSeperateFile_Click(object sender, EventArgs e)
        {
            int discharge_counter = 0;
            int charge_counter = 0;

            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 = (valuesCsvLine[3] == "TRUE" ?true: false);
                    mngInstance.CutMark2 = (valuesCsvLine[4] == "TRUE" ? true : false);
                    mngInstance.Marks2 = (valuesCsvLine[5] == "TRUE" ?true: false);

                    ObserveData.Add(mngInstance);

                    if (mngInstance.Pass==true && mngInstance.Marks1==true)
                    {

                    }
                    if (mngInstance.Pass == false && mngInstance.Marks1 == true)
                    {

                    }
                    if (mngInstance.Pass == true && mngInstance.Marks2 == true)
                    {

                    }
                    if (mngInstance.Pass == false && mngInstance.Marks2 == true )
                    {

                    }
                }
            }
</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 ChargeMode
        public bool CutMark1 { get; set; } // property to store ChargeMode
        public bool Marks1 { get; set; } // property to store ScheduleStep
        public bool CutMark2 { get; set; } // property to store ChargeMode
        public bool Marks2 { get; set; } // property to store ScheduleStep
     }
</code>```

My problem is How I generate these files as I mentioned before.please help to solve my problem.

答:
I wrote up my draft idea as below. I just focus on 4 cases:

Pass = True, CutMark1 = True.

Pass = True, CutMark2 = True.

Pass = False, CutMark1 = True.

Pass = False, CutMark2 = True.

There're maybe another cases, I think.

So, first, I create a new model to store data.

```<code>public class Charge
{
    public DateTime Date { get; set; }
    public bool Pass { get; set; }
    public bool CutMark { get; set; }
    public int Marks { get; set; }
}
</code>```

Then, I create 4 lists to store data for 4 cases:

```<code>var discharge1Mark1 = new List<Charge>();
var discharge1Mark2 = new List<Charge>();
var charge1Mark1 = new List<Charge>();
var charge1Mark2 = new List<Charge>();
</code>```

In your for loop, I will process like below:

```<code>var date = DateTime.ParseExact(valuesCsvLine[0], dateFormatString, CultureInfo.InvariantCulture);
            var pass = (valuesCsvLine[1] == "TRUE" ? true : false);
            var cutMark1 = (valuesCsvLine[2] == "TRUE" ? true : false);
            var marks1 = int.Parse(valuesCsvLine[3]);
            var cutMark2 = (valuesCsvLine[4] == "TRUE" ? true : false);
            var marks2 = int.Parse(valuesCsvLine[5]);
            if (pass)
            {
                if (cutMark1)
                    discharge1Mark1.Add(new Charge
                    {
                        Date = date,
                        Pass = pass,
                        Marks = marks1,
                        CutMark = cutMark1
                    });
                else
                    discharge1Mark2.Add(new Charge
                    {
                        Date = date,
                        Pass = pass,
                        Marks = marks2,
                        CutMark = cutMark2
                    });
            }else
            {
                if (cutMark1)
                    charge1Mark1.Add(new Charge
                    {
                        Date = date,
                        Pass = pass,
                        Marks = marks1,
                        CutMark = cutMark1
                    });
                else
                    charge1Mark2.Add(new Charge
                    {
                        Date = date,
                        Pass = pass,
                        Marks = marks2,
                        CutMark = cutMark2
                    });
            }
</code>```

To programmatic create headers for CSV, you can just simply do as below:

```<code>private void ExportToCSV(List<Charge> data, bool discharge, int num)
{
    var filename = discharge ? "Discharge1" : "Charge1";
    filename += (num == 1) ? "_Mark1.csv" : "_Mark2.csv";
    var headerCol1 = "Date";
    var headerCol2 = "Pass";
    var headerCol3 = (num == 1) ? "CutMark1" : "CutMark2";
    var headerCol4 = (num == 1) ? "Mark1" : "Mark2";
    //your exporting function below
}
</code>```

Hope you understand and my idea could helps.

Body:
I have .csv file that sample of file is like this,

    Date,Pass,CutMark1,Marks1,CutMark2,Marks2
22/06/2017 13:04:18,FALSE,TRUE,TRUE,FALSE,FALSE
22/06/2017 13:04:20,FALSE,TRUE,TRUE,FALSE,FALSE
22/06/2017 13:04:35,FALSE,TRUE,TRUE,FALSE,FALSE
22/06/2017 13:04:37,FALSE,TRUE,TRUE,FALSE,FALSE
22/06/2017 13:04:37,FALSE,TRUE,TRUE,FALSE,FALSE
22/06/2017 13:04:38,FALSE,FALSE,TRUE,FALSE,FALSE
22/06/2017 13:04:39,FALSE,FALSE,TRUE,FALSE,FALSE
22/06/2017 13:04:40,FALSE,FALSE,TRUE,TRUE,FALSE
22/06/2017 13:04:41,FALSE,FALSE,TRUE,TRUE,TRUE
22/06/2017 13:04:42,FALSE,FALSE,FALSE,TRUE,TRUE
22/06/2017 13:04:44,FALSE,FALSE,FALSE,TRUE,TRUE
22/06/2017 13:04:45,TRUE,FALSE,FALSE,TRUE,TRUE
22/06/2017 13:04:46,TRUE,FALSE,FALSE,TRUE,TRUE
22/06/2017 13:04:48,TRUE,FALSE,FALSE,FALSE,TRUE
22/06/2017 13:04:49,TRUE,FALSE,FALSE,FALSE,TRUE
22/06/2017 13:04:50,TRUE,FALSE,FALSE,FALSE,TRUE
22/06/2017 13:04:52,FALSE,TRUE,TRUE,FALSE,TRUE
22/06/2017 13:04:53,FALSE,TRUE,TRUE,FALSE,TRUE
22/06/2017 13:04:54,FALSE,TRUE,TRUE,FALSE,TRUE
22/06/2017 13:04:56,FALSE,TRUE,TRUE,FALSE,TRUE
22/06/2017 13:04:57,FALSE,TRUE,TRUE,FALSE,TRUE
22/06/2017 13:04:58,FALSE,TRUE,TRUE,FALSE,TRUE
22/06/2017 13:05:00,TRUE,TRUE,TRUE,TRUE,FALSE
22/06/2017 13:05:01,TRUE,TRUE,TRUE,TRUE,FALSE
22/06/2017 13:05:02,TRUE,TRUE,TRUE,TRUE,FALSE
22/06/2017 13:05:04,TRUE,TRUE,TRUE,TRUE,FALSE
22/06/2017 13:05:05,TRUE,TRUE,TRUE,TRUE,FALSE
22/06/2017 13:05:06,TRUE,TRUE,TRUE,TRUE,FALSE
22/06/2017 13:05:08,TRUE,TRUE,TRUE,TRUE,FALSE

So now I want to save this file as follows;In here Pass column data flow is like this,FALSE>TRUE>FALSE>TRUE ..this is sample of my .csv file.but there is more raw in original file.In here I want to Separate this original .csv file like following ;

First met False so all of False details And check Marks1=TRUE then save Discharge1_Mark1.csv,and look at Marks2 column and if that column true then save Discharge1_Mark2.csv.

Secondly Pass column meet True then check Marks1=TRUE then save Charge1_Mark1.csv,then if  Marks2=true then save Charge1_Mark2.csv.

NOw again Pass column meet False then want to save file Discharge2_Marks1.csv.
like that I want to save my files.

I want to say in here Accordingly Pass column TRUE,False you want to save file like i mentioned before as which time that TRUE,FALSE meet.1,2,3,...you want to check respective pass column TRUE false with respective Marks1,Marks2 column.
In here I want to save my generated file respective therir columns.

If I save Marks1 then column headers should (Date,Pass,CutMarks1,Marks1 )
If i save Marks2 then column header should (Date,Pass,CutMarks2,Marks2)

Please give how I generate files as I mentioned before in my code.my code is following.

using System.Globalization;

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

  private void btnSeperateFile_Click(object sender, EventArgs e)
        {
            int discharge_counter = 0;
            int charge_counter = 0;

            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 = (valuesCsvLine[3] == "TRUE" ?true: false);
                    mngInstance.CutMark2 = (valuesCsvLine[4] == "TRUE" ? true : false);
                    mngInstance.Marks2 = (valuesCsvLine[5] == "TRUE" ?true: false);

                    ObserveData.Add(mngInstance);

                    if (mngInstance.Pass==true && mngInstance.Marks1==true)
                    {

                    }
                    if (mngInstance.Pass == false && mngInstance.Marks1 == true)
                    {

                    }
                    if (mngInstance.Pass == true && mngInstance.Marks2 == true)
                    {

                    }
                    if (mngInstance.Pass == false && mngInstance.Marks2 == true )
                    {

                    }
                }
            }

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 ChargeMode
        public bool CutMark1 { get; set; } // property to store ChargeMode
        public bool Marks1 { get; set; } // property to store ScheduleStep
        public bool CutMark2 { get; set; } // property to store ChargeMode
        public bool Marks2 { get; set; } // property to store ScheduleStep
     }

My problem is How I generate these files as I mentioned before.please help to solve my problem.

Body:
I wrote up my draft idea as below. I just focus on 4 cases:

Pass = True, CutMark1 = True.

Pass = True, CutMark2 = True.

Pass = False, CutMark1 = True.

Pass = False, CutMark2 = True.

There're maybe another cases, I think.

So, first, I create a new model to store data.

public class Charge
{
    public DateTime Date { get; set; }
    public bool Pass { get; set; }
    public bool CutMark { get; set; }
    public int Marks { get; set; }
}

Then, I create 4 lists to store data for 4 cases:

var discharge1Mark1 = new List<Charge>();
var discharge1Mark2 = new List<Charge>();
var charge1Mark1 = new List<Charge>();
var charge1Mark2 = new List<Charge>();

In your for loop, I will process like below:

var date = DateTime.ParseExact(valuesCsvLine[0], dateFormatString, CultureInfo.InvariantCulture);
            var pass = (valuesCsvLine[1] == "TRUE" ? true : false);
            var cutMark1 = (valuesCsvLine[2] == "TRUE" ? true : false);
            var marks1 = int.Parse(valuesCsvLine[3]);
            var cutMark2 = (valuesCsvLine[4] == "TRUE" ? true : false);
            var marks2 = int.Parse(valuesCsvLine[5]);
            if (pass)
            {
                if (cutMark1)
                    discharge1Mark1.Add(new Charge
                    {
                        Date = date,
                        Pass = pass,
                        Marks = marks1,
                        CutMark = cutMark1
                    });
                else
                    discharge1Mark2.Add(new Charge
                    {
                        Date = date,
                        Pass = pass,
                        Marks = marks2,
                        CutMark = cutMark2
                    });
            }else
            {
                if (cutMark1)
                    charge1Mark1.Add(new Charge
                    {
                        Date = date,
                        Pass = pass,
                        Marks = marks1,
                        CutMark = cutMark1
                    });
                else
                    charge1Mark2.Add(new Charge
                    {
                        Date = date,
                        Pass = pass,
                        Marks = marks2,
                        CutMark = cutMark2
                    });
            }

To programmatic create headers for CSV, you can just simply do as below:

private void ExportToCSV(List<Charge> data, bool discharge, int num)
{
    var filename = discharge ? "Discharge1" : "Charge1";
    filename += (num == 1) ? "_Mark1.csv" : "_Mark2.csv";
    var headerCol1 = "Date";
    var headerCol2 = "Pass";
    var headerCol3 = (num == 1) ? "CutMark1" : "CutMark2";
    var headerCol4 = (num == 1) ? "Mark1" : "Mark2";
    //your exporting function below
}

Hope you understand and my idea could helps.


问:
Java regex expression to include underscore
I am trying with the below line, which ignores underscore but I want to change it to include underscore.

```<code>String name = "$SF_Update$";
String regexp = "\\$(.*?)(?:[\\_].*)?\\$"; // want to change this line
Pattern pattern = Pattern.compile(regexp);
Matcher matcher = pattern.matcher(name);
</code>```

I tried the below options:

```<code>String regexp ="\\$([a-zA-Z]+(?:_[a-zA-Z]+)*)\\$"
</code>```

It includes underscore but it is considering the next line strings which doesn't have a $ at the end as well, like:
"$SF_Update$"
"$SF_Updateone"
Please provide a solution.

答:
Try with this expresion:

```<code>\$[A-Za-z]+(_[A-Za-z]+)*\$
</code>```

I do it in Regex Online

And if the name could have numbers:

```<code>\$[A-Za-z0-9]+(_[A-Za-z0-9]+)*\$
</code>```

And it rules for me.

Body:
I am trying with the below line, which ignores underscore but I want to change it to include underscore.

String name = "$SF_Update$";
String regexp = "\\$(.*?)(?:[\\_].*)?\\$"; // want to change this line
Pattern pattern = Pattern.compile(regexp);
Matcher matcher = pattern.matcher(name);

I tried the below options:

String regexp ="\\$([a-zA-Z]+(?:_[a-zA-Z]+)*)\\$"

It includes underscore but it is considering the next line strings which doesn't have a $ at the end as well, like:
"$SF_Update$"
"$SF_Updateone"
Please provide a solution.

Body:
Try with this expresion:

\$[A-Za-z]+(_[A-Za-z]+)*\$

I do it in Regex Online

And if the name could have numbers:

\$[A-Za-z0-9]+(_[A-Za-z0-9]+)*\$

And it rules for me.


问:
AngularJS apply filter in javascript instead of html
I have a ng-repeat to create table:

```<code>ng-repeat="equipment in equipments | filter: equipmentFilter | dateFilter: dateStart: dateEnd | pageFilter: currentPage * pageSize | limitTo: pageSize"
</code>```

I need to get:

```<code>(equipments | dateFilter: dateStart: dateEnd | filter: equipmentFilter).length
</code>```

to update number of total page in paging feature. I've tried:

```<code>ng-init="equipmentsForPaging = (equipments | dateFilter: dateStart: dateEnd | filter: equipmentFilter)"
</code>```

But it isn't working at all, also I don't think using ng-init is a good idea. So are there anyway to do this in javascript?

答:
There are $filter, you can inject and use it in your controller.

But if you use that, you will re use filter so there are 2 filter treatments (2 loops) so in my opinion it's not good idea.

You already got that filtered array in your view, you just need to assign it to a variable, in the ng-repeat, and use parenthesis to distinct your needed array:

ng-repeat="equipment in filtered = (equipments | filter: equipmentFilter | dateFilter: dateStart: dateEnd) | pageFilter: currentPage * pageSize | limitTo: pageSize"

then you can just use {{filtered.length}}

Body:
I have a ng-repeat to create table:

ng-repeat="equipment in equipments | filter: equipmentFilter | dateFilter: dateStart: dateEnd | pageFilter: currentPage * pageSize | limitTo: pageSize"

I need to get:

(equipments | dateFilter: dateStart: dateEnd | filter: equipmentFilter).length

to update number of total page in paging feature. I've tried:

ng-init="equipmentsForPaging = (equipments | dateFilter: dateStart: dateEnd | filter: equipmentFilter)"

But it isn't working at all, also I don't think using ng-init is a good idea. So are there anyway to do this in javascript?


问:
Swift - how to store a struct instance in a class propriety
I am very new to Swift so I apologize upfront if this is a "dumb" question. I am just working on a playgrounds script for generating random items, in this case, weapons. When I run my code I get this error: error: Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0). What I was trying to do is hold an instance of a structure(which is handle) in my class normalBladeType in variable weaponHandle. I've tried researching about this topic but I've yet to find an answer. Any suggestions would be great. For all I know I may be going about this all wrong.

Thanks,

my code:

```<code>//: Playground - noun: a place where people can play

import Cocoa

let handleWoods = ["White Ash", "Oak", "White Oak", "Elm", "Maple","Walnut", "Cherry", "Rosewood", "Ash", "Hickory", "Birch", "Hemlock", "Cedar", "Pine"]
let handleGrips = ["Leather", "Buckskin", "Sharkskin", "Goat Skin", "Deerskin", "Elk Skin", "Rayskin", "Snakeskin", "Silk Cord", "Cotton Cord"]
let gripQualities = ["Simple", "Interwoven", "Ornate", "Smooth", "Thin", "Thick", "Ruff", "Worn"]

func returnRandomItem( _ list: [Any])-> Any {
    return list[Int(UInt32(list.count))]
}

struct handle {
    var name: String
    var value, grip: Int
    var weight: Double
    var withGrip: Bool

    init(withGrip: Bool) {
        self.weight = 0.25
        self.withGrip = withGrip
        let handleNameWithWood = "\(returnRandomItem(handleWoods)) Handle"
        if self.withGrip {
            let randGrip = "\(returnRandomItem(gripQualities)) \(returnRandomItem(handleGrips)) Grip)"
            self.name = "\(randGrip) (\(handleNameWithWood))"
            self.grip = 75
            self.value = 2
        } else {
            self.name = handleNameWithWood
            self.grip = 50
            self.value = 1
        }
    }

    func description() {
        print("Handle Description \(self.name)")
        }

}

class weapon {
    var TypeOfWeapon: String
    var weaponHandle: handle

    init(weaponType: String, doesHaveGrip: Bool) {
        self.TypeOfWeapon = weaponType
        self.weaponHandle = handle(withGrip: doesHaveGrip)
    }
}

class normalBladeType: weapon {
    init() {
        super.init(weaponType: "normalBladeType", doesHaveGrip: false)
    }

    func description() {
        print("TypeOfWeapon: \(self.TypeOfWeapon)")
        print("TypeDescription: normal hilt (guard - handle - pommel) + straight blade")
    }
}

var foo = normalBladeType()
foo.description()
</code>```

答:
Your returnRandomItem function is wrong. You should change it to

```<code>func returnRandomItem( _ list: [Any])-> Any {
    let index: UInt32 = arc4random_uniform(UInt32(list.count))
    return list[Int(index)]
}
</code>```

It is working fine for me with this code.

Body:
I am very new to Swift so I apologize upfront if this is a "dumb" question. I am just working on a playgrounds script for generating random items, in this case, weapons. When I run my code I get this error: error: Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0). What I was trying to do is hold an instance of a structure(which is handle) in my class normalBladeType in variable weaponHandle. I've tried researching about this topic but I've yet to find an answer. Any suggestions would be great. For all I know I may be going about this all wrong.

Thanks,

my code:

//: Playground - noun: a place where people can play

import Cocoa

let handleWoods = ["White Ash", "Oak", "White Oak", "Elm", "Maple","Walnut", "Cherry", "Rosewood", "Ash", "Hickory", "Birch", "Hemlock", "Cedar", "Pine"]
let handleGrips = ["Leather", "Buckskin", "Sharkskin", "Goat Skin", "Deerskin", "Elk Skin", "Rayskin", "Snakeskin", "Silk Cord", "Cotton Cord"]
let gripQualities = ["Simple", "Interwoven", "Ornate", "Smooth", "Thin", "Thick", "Ruff", "Worn"]

func returnRandomItem( _ list: [Any])-> Any {
    return list[Int(UInt32(list.count))]
}

struct handle {
    var name: String
    var value, grip: Int
    var weight: Double
    var withGrip: Bool

    init(withGrip: Bool) {
        self.weight = 0.25
        self.withGrip = withGrip
        let handleNameWithWood = "\(returnRandomItem(handleWoods)) Handle"
        if self.withGrip {
            let randGrip = "\(returnRandomItem(gripQualities)) \(returnRandomItem(handleGrips)) Grip)"
            self.name = "\(randGrip) (\(handleNameWithWood))"
            self.grip = 75
            self.value = 2
        } else {
            self.name = handleNameWithWood
            self.grip = 50
            self.value = 1
        }
    }

    func description() {
        print("Handle Description \(self.name)")
        }

}

class weapon {
    var TypeOfWeapon: String
    var weaponHandle: handle

    init(weaponType: String, doesHaveGrip: Bool) {
        self.TypeOfWeapon = weaponType
        self.weaponHandle = handle(withGrip: doesHaveGrip)
    }
}

class normalBladeType: weapon {
    init() {
        super.init(weaponType: "normalBladeType", doesHaveGrip: false)
    }

    func description() {
        print("TypeOfWeapon: \(self.TypeOfWeapon)")
        print("TypeDescription: normal hilt (guard - handle - pommel) + straight blade")
    }
}

var foo = normalBladeType()
foo.description()

Body:
Your returnRandomItem function is wrong. You should change it to

func returnRandomItem( _ list: [Any])-> Any {
    let index: UInt32 = arc4random_uniform(UInt32(list.count))
    return list[Int(index)]
}

It is working fine for me with this code.


问:
Why are [range(10)] and list(range(10)) not the same?
Why are [range(10)] and list(range(10)) different in Python 3?

Output is as follows:

```<code>>>> print([range(10)])
[range(0, 10)]
>>> print(list(range(10)))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
</code>```

答:
[x] means "make a list whose one element is x".

list(x) means "make a list whose elements are the elements of x".

range(10) returns an object that prints as range(0, 10) (since it shows the starting value when it prints) and whose elements are the integers from 0 to 9, so [range(10)] gives the one-element list [range(0, 10)] and list(range(10)) gives the 10-element list [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].

Body:
Why are [range(10)] and list(range(10)) different in Python 3?

Output is as follows:

>>> print([range(10)])
[range(0, 10)]
>>> print(list(range(10)))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]


问:
Python home directory in Windows / Problem with multiple versions
I'm using Python 3 for developing and CollabNet Subversion Edge as versioning software. Subversion Edge comes with a little program called ViewVC which is written in Python 2, which is also directly bundled with it. There is a system environment variable called PYTHONHOME.

If it is set to the Python 2 distribution from Subversion Edge, my Python 3 won't start (not even IDLE), instead giving a runtime error messagebox.

If it is set to Python 3, ViewVC doesn't work.

Is there a way to make both work at the same time?

答: Write a .bat or cmd file that saves the value of the PYTHONHOME env var, invokes ViewVC and wait for it to finish, then restores PYTHONHOME to the saved value.</p>


答:
Quoting the docs, "lists may be constructed in several ways":

```<code>[range(10)]
</code>```

builds a list of 1 item, the range object. In general a comma separated list of items enclosed in square brackets constructs a list of said items.

```<code>list(range(10))
</code>```

passes the range object as an argument to the list constructor:

class list([iterable])

The constructor builds a list whose items are the same and in the same order as iterable‘s items. iterable may be either a sequence, a container that supports iteration, or an iterator object. If iterable is already a list, a copy is made and returned, similar to iterable[:]. For example, list('abc') returns ['a', 'b', 'c'] and list( (1, 2, 3) ) returns [1, 2, 3]. If no argument is given, the constructor creates a new empty list, [].

A range in Python 3 represents an immutable sequence of numbers, so in your case the resulting list is a list of numbers from the range.

Title: Why are [range(10)] and list(range(10)) not the same?

Body:
Quoting the docs, "lists may be constructed in several ways":

[range(10)]

builds a list of 1 item, the range object. In general a comma separated list of items enclosed in square brackets constructs a list of said items.

list(range(10))

passes the range object as an argument to the list constructor:

class list([iterable])

The constructor builds a list whose items are the same and in the same order as iterable‘s items. iterable may be either a sequence, a container that supports iteration, or an iterator object. If iterable is already a list, a copy is made and returned, similar to iterable[:]. For example, list('abc') returns ['a', 'b', 'c'] and list( (1, 2, 3) ) returns [1, 2, 3]. If no argument is given, the constructor creates a new empty list, [].

A range in Python 3 represents an immutable sequence of numbers, so in your case the resulting list is a list of numbers from the range.


问:
How to get the name of the service for the corresponding UUID in bluetooth?
I am developing an Bluetooth application, and i need to get the name of the services provided by a particular client Bluetooth device. I am using the following code to get the UUID's.

Code Snippet:

```<code> if(BluetoothDevice.ACTION_UUID.equals(action))
 {
 BluetoothDevice device =       intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
 Parcelable[] uuidExtra =    intent.getParcelableArrayExtra(BluetoothDevice.EXTRA_UUID);
 for (int i = 0; i < uuidExtra.length; i++) {
String abc=uuidExtra[i].toString());
 }
 }
</code>```

I am getting the uuid value as for example "00001000-0000-1000-8000-00805F9B34FB" But i need its corresponding service name like the following.

BrowseGroupDescriptorServiceClassID = 00001001-0000-1000-8000-00805F9B34FB
PublicBrowseGroupServiceClass = 00001002-0000-1000-8000-00805F9B34FB

答:
By the way,it's different from iOS dev,we can't get service_name or charactistics_name through android public api(except uuid) when connected ,so if
 we want to extpand ourself service_name or charactistics_name that outside blutetooth SIG defined in remote bluetooth-hardware. we can't fetch target charactistics_name directly(e.g. charactistics.getUUIDName()) (still use mapping add myself charactistics_uuid is not interchangeable)

Body:
I am developing an Bluetooth application, and i need to get the name of the services provided by a particular client Bluetooth device. I am using the following code to get the UUID's.

Code Snippet:

 if(BluetoothDevice.ACTION_UUID.equals(action))
 {
 BluetoothDevice device =       intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
 Parcelable[] uuidExtra =    intent.getParcelableArrayExtra(BluetoothDevice.EXTRA_UUID);
 for (int i = 0; i < uuidExtra.length; i++) {
String abc=uuidExtra[i].toString());
 }
 }

I am getting the uuid value as for example "00001000-0000-1000-8000-00805F9B34FB" But i need its corresponding service name like the following.

BrowseGroupDescriptorServiceClassID = 00001001-0000-1000-8000-00805F9B34FB
PublicBrowseGroupServiceClass = 00001002-0000-1000-8000-00805F9B34FB


答:
In your first example you are simply creating a list object using square bracket notation, and placing a range() object inside. On the other hand, in your second example, you use the list() builtin to convert the range() object to a list.

The difference, is that using [] simply creates a list. It does nothing to the contents passed in. list() on the other hand, will either return an empty list if you pass nothing in, or attempt to convert what you passed in to a list object.

The documentation for list() notes this:

The constructor builds a list whose items are the same and in the same order as iterable‘s items. iterable may be either a sequence, a container that supports iteration, or an iterator object. If iterable is already a list, a copy is made and returned, similar to iterable[:]. For example, list('abc') returns ['a', 'b', 'c'] and list( (1, 2, 3) ) returns [1, 2, 3]. If no argument is given, the constructor creates a new empty list, [].


问:
grep a tab in UNIX
How do I grep tab (\t) in files on the Unix platform?

答:
The $'\t' notation given in other answers is shell-specific -- it seems to work in bash and zsh but is not universal.

NOTE: The following is for the fish shell and does not work in bash:

In the fish shell, one can use an unquoted \t, for example:

```<code>grep \t foo.txt
</code>```

Or one can use the hex or unicode notations e.g.:

```<code>grep \X09 foo.txt
grep \U0009 foo.txt
</code>```

(these notations are useful for more esoteric characters)

Since these values must be unquoted, one can combine quoted and unquoted values by concatenation:

```<code>grep "foo"\t"bar"
</code>```

Title: grep a tab in UNIX

Body:
The $'\t' notation given in other answers is shell-specific -- it seems to work in bash and zsh but is not universal.

NOTE: The following is for the fish shell and does not work in bash:

In the fish shell, one can use an unquoted \t, for example:

grep \t foo.txt

Or one can use the hex or unicode notations e.g.:

grep \X09 foo.txt
grep \U0009 foo.txt

(these notations are useful for more esoteric characters)

Since these values must be unquoted, one can combine quoted and unquoted values by concatenation:

grep "foo"\t"bar"


问:
Selenium Get popup and popunder currently open link
In my site when I search anything on homepage its open one leaves behind window and one popunder window.Using selenium I want to know its open correctly or not and also take this two window link.

I tried this but it's not working

```<code>public class Utility
{
    public static WebDriver getHandleToWindow(String title){

        //parentWindowHandle = WebDriverInitialize.getDriver().getWindowHandle(); // save the current window handle.
        WebDriver popup = null;
        Set<String> windowIterator = WebDriverInitialize.getDriver().getWindowHandles();
        System.err.println("No of windows :  " + windowIterator.size());
        for (String s : windowIterator) {
          String windowHandle = s;
          popup = WebDriverInitialize.getDriver().switchTo().window(windowHandle);
          System.out.println("Window Title : " + popup.getTitle());
          System.out.println("Window Url : " + popup.getCurrentUrl());
          if (popup.getTitle().equals(title) ){
              System.out.println("Selected Window Title : " + popup.getTitle());
              return popup;
          }

        }
                System.out.println("Window Title :" + popup.getTitle());
                System.out.println();
            return popup;
        }
}
</code>```

答:
When you've launched only one WebDriver process, there will be only one WebDriver. It contains a list of window handles. You don't need to have multiple instances of WebDriver. If you want to go to the new window (or tab) and then go back to the main window, you should store the windowHandle of the main window somewhere in the WebDriverInitialize class. My example below shows how to store the windowHandle in the Utility class.

```<code>public class Utility
{
    public static void switchToNewWindow(String title){
        Set<String> windowIterator = WebDriverInitialize.getDriver().getWindowHandles();
        System.err.println("No of windows :  " + windowIterator.size());
        for (String s : windowIterator) {
            String windowHandle = s;
            WebDriverInitialize.getDriver().switchTo().window(windowHandle);
            System.out.println("Window Title : " + WebDriverInitialize.getDriver().getTitle());
            System.out.println("Window Url : " + WebDriverInitialize.getDriver().getCurrentUrl());
            // you may use .getTitle().contains(title) if you cannot predict the full title
            if (WebDriverInitialize.getDriver().getTitle().equals(title) ){
                break;
            }
        }
    }

    public static string mainWindowHandle;

}

WebDriverInitialize.getDriver().get("https://www.rentalhomes.com/");
Utility.mainWindowHandle = WebDriverInitialize.getDriver().getWindowHandle();
...
WebDriverInitialize.getDriver().findElement(By.id("home-page-search-btn")).click();
// Switch to the new window
Utility.switchToNewWindow("San Francisco ...");
// Switch back to main window
WebDriverInitialize.getDriver().switchTo().window(Utility.mainWindowHandle);
</code>```

Body:
In my site when I search anything on homepage its open one leaves behind window and one popunder window.Using selenium I want to know its open correctly or not and also take this two window link.

I tried this but it's not working

public class Utility
{
    public static WebDriver getHandleToWindow(String title){

        //parentWindowHandle = WebDriverInitialize.getDriver().getWindowHandle(); // save the current window handle.
        WebDriver popup = null;
        Set<String> windowIterator = WebDriverInitialize.getDriver().getWindowHandles();
        System.err.println("No of windows :  " + windowIterator.size());
        for (String s : windowIterator) {
          String windowHandle = s;
          popup = WebDriverInitialize.getDriver().switchTo().window(windowHandle);
          System.out.println("Window Title : " + popup.getTitle());
          System.out.println("Window Url : " + popup.getCurrentUrl());
          if (popup.getTitle().equals(title) ){
              System.out.println("Selected Window Title : " + popup.getTitle());
              return popup;
          }

        }
                System.out.println("Window Title :" + popup.getTitle());
                System.out.println();
            return popup;
        }
}

Body:
When you've launched only one WebDriver process, there will be only one WebDriver. It contains a list of window handles. You don't need to have multiple instances of WebDriver. If you want to go to the new window (or tab) and then go back to the main window, you should store the windowHandle of the main window somewhere in the WebDriverInitialize class. My example below shows how to store the windowHandle in the Utility class.

public class Utility
{
    public static void switchToNewWindow(String title){
        Set<String> windowIterator = WebDriverInitialize.getDriver().getWindowHandles();
        System.err.println("No of windows :  " + windowIterator.size());
        for (String s : windowIterator) {
            String windowHandle = s;
            WebDriverInitialize.getDriver().switchTo().window(windowHandle);
            System.out.println("Window Title : " + WebDriverInitialize.getDriver().getTitle());
            System.out.println("Window Url : " + WebDriverInitialize.getDriver().getCurrentUrl());
            // you may use .getTitle().contains(title) if you cannot predict the full title
            if (WebDriverInitialize.getDriver().getTitle().equals(title) ){
                break;
            }
        }
    }

    public static string mainWindowHandle;

}

WebDriverInitialize.getDriver().get("https://www.rentalhomes.com/");
Utility.mainWindowHandle = WebDriverInitialize.getDriver().getWindowHandle();
...
WebDriverInitialize.getDriver().findElement(By.id("home-page-search-btn")).click();
// Switch to the new window
Utility.switchToNewWindow("San Francisco ...");
// Switch back to main window
WebDriverInitialize.getDriver().switchTo().window(Utility.mainWindowHandle);


答:
range() function in python 3.x is similar to the xrange() function in python 2.x.In Python 2.x range() produced a list, and xrange() returned an iterator - a sequence object

In python 2.x

```<code>>>> range(1)
[0]
>>> type(range(1))
<type 'list'>
</code>```

In python 3.x

```<code>>>> range(1)
range(0, 1)
>>> type(range(1))
<class 'range'>
</code>```

And to get a list, you can pass the generator in list()

```<code>>>> print (list(range(10)))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
</code>```

For further reference , read here

Body:
range() function in python 3.x is similar to the xrange() function in python 2.x.In Python 2.x range() produced a list, and xrange() returned an iterator - a sequence object

In python 2.x

>>> range(1)
[0]
>>> type(range(1))
<type 'list'>

In python 3.x

>>> range(1)
range(0, 1)
>>> type(range(1))
<class 'range'>

And to get a list, you can pass the generator in list()

>>> print (list(range(10)))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

For further reference , read here


问:
Login Page shared preference not working as expected
I have an android app in which I am using shared preferences for login.Until now I have a flow like user logs in..when login is successful the credentials are stored.And when the user opens the app again the username password appears in the edit text.I have a login button and have setonclicklistner to login and jump to the inner activities.
I am trying a flow like when the user logs in successfully..and the app is restarted the credentials are stored..it should automatically go the next activity(inner activity).
What I have tried until now..

In oncreate the onclicklistner that opens next activity if credentials are good

```<code>buttonlogin.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                if(etemail.getText().toString().equals("") && etpass.getText().toString().equals(""))
                {
                    Toast.makeText(getApplicationContext(),"Enter your username and Password",Toast.LENGTH_LONG).show();
                }
                else
                {
                    load_data();
                }

            }
        });
</code>```

Code of shared pref

```<code>private void savePreferences() {
    SharedPreferences settings = getSharedPreferences(PREFS_NAME,
            Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = settings.edit();

    // Edit and commit
    UnameValue = etemail.getText().toString();
    PasswordValue = etpass.getText().toString();
    editor.putString(PREF_UNAME, UnameValue);
    editor.putString(PREF_PASSWORD, PasswordValue);
    editor.commit();
}

private void loadPreferences()
{
    SharedPreferences settings = getSharedPreferences(PREFS_NAME,
            Context.MODE_PRIVATE);

    // Get value
    UnameValue = settings.getString(PREF_UNAME, DefaultUnameValue);
    PasswordValue = settings.getString(PREF_PASSWORD, DefaultPasswordValue);

    etemail.setText(UnameValue);
    etpass.setText(PasswordValue);
}
</code>```

What should I do in order to achieve this??if username password is stored automatically open next activity instead of clicking login button??
Thanks

答:
Open the next activity first, and then in onCreate method check if the user is logged in. If not close the first, and open the loggin activity.

MainActivity.java

```<code> protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
session = new SessionManager(getApplicationContext());
        CheckLogin();
...
}
private void CheckLogin(){
        if(session.checkLogin()){finish();}
    }
</code>```

SessionManager.java

```<code>  public boolean checkLogin(){
        // Check login status
        if(!this.isUserLoggedIn()){

            // user is not logged in redirect him to Login Activity
            Intent i = new Intent(_context, LoginActivity.class);

            // Closing all the Activities from stack
            i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

            // Add new Flag to start new Activity
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

            // Staring Login Activity
            _context.startActivity(i);

            return true;
        }
        return false;
    }
</code>```

Body:
I have an android app in which I am using shared preferences for login.Until now I have a flow like user logs in..when login is successful the credentials are stored.And when the user opens the app again the username password appears in the edit text.I have a login button and have setonclicklistner to login and jump to the inner activities.
I am trying a flow like when the user logs in successfully..and the app is restarted the credentials are stored..it should automatically go the next activity(inner activity).
What I have tried until now..

In oncreate the onclicklistner that opens next activity if credentials are good

buttonlogin.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                if(etemail.getText().toString().equals("") && etpass.getText().toString().equals(""))
                {
                    Toast.makeText(getApplicationContext(),"Enter your username and Password",Toast.LENGTH_LONG).show();
                }
                else
                {
                    load_data();
                }

            }
        });

Code of shared pref

private void savePreferences() {
    SharedPreferences settings = getSharedPreferences(PREFS_NAME,
            Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = settings.edit();

    // Edit and commit
    UnameValue = etemail.getText().toString();
    PasswordValue = etpass.getText().toString();
    editor.putString(PREF_UNAME, UnameValue);
    editor.putString(PREF_PASSWORD, PasswordValue);
    editor.commit();
}

private void loadPreferences()
{
    SharedPreferences settings = getSharedPreferences(PREFS_NAME,
            Context.MODE_PRIVATE);

    // Get value
    UnameValue = settings.getString(PREF_UNAME, DefaultUnameValue);
    PasswordValue = settings.getString(PREF_PASSWORD, DefaultPasswordValue);

    etemail.setText(UnameValue);
    etpass.setText(PasswordValue);
}

What should I do in order to achieve this??if username password is stored automatically open next activity instead of clicking login button??
Thanks

Body:
Open the next activity first, and then in onCreate method check if the user is logged in. If not close the first, and open the loggin activity.

MainActivity.java

 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
session = new SessionManager(getApplicationContext());
        CheckLogin();
...
}
private void CheckLogin(){
        if(session.checkLogin()){finish();}
    }

SessionManager.java

  public boolean checkLogin(){
        // Check login status
        if(!this.isUserLoggedIn()){

            // user is not logged in redirect him to Login Activity
            Intent i = new Intent(_context, LoginActivity.class);

            // Closing all the Activities from stack
            i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

            // Add new Flag to start new Activity
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

            // Staring Login Activity
            _context.startActivity(i);

            return true;
        }
        return false;
    }


问:
Jquery .click function not working on chrome but fine on firefox
I found same question also posted on stackoverflow but i didn't get right answer so i posted its again what is the reason jquery click function working on firefox but not working on chrome
Jquery

```<code>$("#companypancard").click(function(){

            $(".nav a.active").removeClass("active");
            $("#registrationandlicenses").addClass("active");
            $("#sab2d").hide();

            $("#header-box-content").hide();
            $(".entire-box-content").show();
            $(".line, .back").show();

            $(".h1-content").html("Company Pancard");
            $(".p-discription").html("PAN is mandatory for every organization for financial transition and open a bank account.");
        });
        $("#registrationandlicenses").mouseenter(function(){$("#sab2d").show();});
        $("#sab2d").mouseleave(function(){$("#sab2d").hide();});
</code>```

EDIT

JSFiddle Is created here

**my code is working on js fiddle but when i upload on server not working on chrome but working on firefox..my 3rd tab is register your business its all sub menu working same code i use on next tab registration and licenses (first submenu) company pan card not working... **

答:
Hope this works for you </p>

```<code>$(document).on('click', '#companypancard',function(){
     // code to execute
});
</code>```

Body:
I found same question also posted on stackoverflow but i didn't get right answer so i posted its again what is the reason jquery click function working on firefox but not working on chrome
Jquery

$("#companypancard").click(function(){

            $(".nav a.active").removeClass("active");
            $("#registrationandlicenses").addClass("active");
            $("#sab2d").hide();

            $("#header-box-content").hide();
            $(".entire-box-content").show();
            $(".line, .back").show();

            $(".h1-content").html("Company Pancard");
            $(".p-discription").html("PAN is mandatory for every organization for financial transition and open a bank account.");
        });
        $("#registrationandlicenses").mouseenter(function(){$("#sab2d").show();});
        $("#sab2d").mouseleave(function(){$("#sab2d").hide();});

EDIT

JSFiddle Is created here

**my code is working on js fiddle but when i upload on server not working on chrome but working on firefox..my 3rd tab is register your business its all sub menu working same code i use on next tab registration and licenses (first submenu) company pan card not working... **

Body:
Hope this works for you

$(document).on('click', '#companypancard',function(){
     // code to execute
});


问:
What are some of Drupal's shortcomings?
Drupal is very much a "Do Everything" CMS. There are modules that allow you to add almost any functionality, which is great. However, it feels like a lot of the features (v5 and v6) seem scattered around and unintuitive for the user. As a developer, I'm left with the feeling of having patched a site together using bubble gum and string.

For example, to add text to the default search box (that disappears when clicked), you have to either add some jQuery code OR override the theme. I've also found the menu system more complicated than it should be.

Am I the only one with this opinion? What things (if any) would you change about Drupal's core?

答: I find that the default admin interface isn't very intuitive compared to other cms' like modx or joomla/mambo</p>

OwnerDisplayName: Matt

Title: What are some of Drupal's shortcomings?

LastEditorDisplayName: Matt

OwnerDisplayName: evh


问:
How to subsetting pyspark dataframe in to 4 dataframes?
I have a pyspark data frame with more than one million records, I need to subset in to 4 datafames. Like 1st 2.5 hundred thousand records in to one data frame and next 2.5 hundred thousand records in to next data frame. How can i do this? </p>

答:
I think the best way is to do this via index column.
If You don't have one, simplest way is to create one on rdd using .zipWithIndex()

example:

```<code>data = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
rdd = spark.sparkContext.parallelize(data).zipWithIndex()
</code>```

Then let's create a DF:

```<code>from pyspark.sql.types import *
from pyspark.sql.functions import *
df = spark.createDataFrame(rdd, ['letters', 'id'])
</code>```

calculate size:

```<code>size_of_df = df.count()/4
</code>```

and create parts of df:

```<code>df_part0 = df.where(col('id') < size_of_df)
df_part1 = df.where((col('id') > size_of_df) &
                    (col('id') <= 2*size_of_df))
df_part2 = df.where((col('id') > 2*size_of_df) &
                    (col('id') <= 3*size_of_df))
df_part3 = df.where((col('id') > 3*size_of_df) &
                    (col('id') <= 4*size_of_df))
</code>```

Body:
I think the best way is to do this via index column.
If You don't have one, simplest way is to create one on rdd using .zipWithIndex()

example:

data = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
rdd = spark.sparkContext.parallelize(data).zipWithIndex()

Then let's create a DF:

from pyspark.sql.types import *
from pyspark.sql.functions import *
df = spark.createDataFrame(rdd, ['letters', 'id'])

calculate size:

size_of_df = df.count()/4

and create parts of df:

df_part0 = df.where(col('id') < size_of_df)
df_part1 = df.where((col('id') > size_of_df) &
                    (col('id') <= 2*size_of_df))
df_part2 = df.where((col('id') > 2*size_of_df) &
                    (col('id') <= 3*size_of_df))
df_part3 = df.where((col('id') > 3*size_of_df) &
                    (col('id') <= 4*size_of_df))


问:
Posting a file and JSON data to Spring rest service
I am building a Spring rest service for uploading a file. There is a form that consists of various field and one field for uploading a file. On submitting that form, I am sending a multipart form request i.e. Content-Type as multipart/form-data.

So I tried with below

```<code>@RequestMapping(value = "/companies", method = RequestMethod.POST)
    public void createCompany(@RequestBody CompanyDTO companyDTO, @RequestParam(value = "image", required = false) MultipartFile image){
.................
</code>```

But, the above didn't work. So for time being,i sent JSON data as String and forming Company Object from that String in rest service like

```<code> @RequestMapping(value = "/companies", method = RequestMethod.POST)
        public void createCompany(@RequestParam("companyJson") String companyJson, @RequestParam(value = "image",required = false) MultipartFile image) throws JsonParseException, JsonMappingException, IOException{
            CompanyDTO companyDTO =  new ObjectMapper().readValue(companyJson, CompanyDTO.class);
.............................
</code>```

Can't I send JSON data with @RequestBody without passing JSON as String?

答:
create FormData() and append your json and file

```<code>        if (form.validate()) {
        var file = $scope.file;
        var fd = new FormData();
        fd.append('jsondata', $scope.jsonData);
        fd.append('file', file);
        MyService.submitFormWithFile('doc/store.html', fd, '', (response){
             console.log(response)
        });
    }
</code>```

//Service called in above

```<code>    MyService.submitFormWithFile = function(url, data, config, callback) {
    $http({
        method : 'POST',
        url : url,
        headers : {
            'Content-Type' : undefined
        },
        data : data,
        transformRequest : function(data, headersGetterFunction) {
            return data;
        }
    }).success(function(response, status, header, config) {
        if (status === 200) {
            callback(response);
        } else {
            console.log("error")
        }
    }).error(function(response, status, header, config) {
            console.log(response);
    });
};
</code>```

// in your java part using ObjectMapper

```<code>//it is like  string
fd.append('jsondata', JSON.stringify($scope.jsonData));

  @Autowired
  private ObjectMapper mapper;

 @RequestMapping(value = "/companies", method = RequestMethod.POST)
   public void createCompany(@RequestParam String jsondata,
        @RequestParam(required = true) MultipartFile file){

        CompanyDto companyDto=mapper.readValue(jsondata, CompanyDTO.class);
       ......
 }
</code>```

Body:
I am building a Spring rest service for uploading a file. There is a form that consists of various field and one field for uploading a file. On submitting that form, I am sending a multipart form request i.e. Content-Type as multipart/form-data.

So I tried with below

@RequestMapping(value = "/companies", method = RequestMethod.POST)
    public void createCompany(@RequestBody CompanyDTO companyDTO, @RequestParam(value = "image", required = false) MultipartFile image){
.................

But, the above didn't work. So for time being,i sent JSON data as String and forming Company Object from that String in rest service like

 @RequestMapping(value = "/companies", method = RequestMethod.POST)
        public void createCompany(@RequestParam("companyJson") String companyJson, @RequestParam(value = "image",required = false) MultipartFile image) throws JsonParseException, JsonMappingException, IOException{
            CompanyDTO companyDTO =  new ObjectMapper().readValue(companyJson, CompanyDTO.class);
.............................

Can't I send JSON data with @RequestBody without passing JSON as String?

Body:
create FormData() and append your json and file

        if (form.validate()) {
        var file = $scope.file;
        var fd = new FormData();
        fd.append('jsondata', $scope.jsonData);
        fd.append('file', file);
        MyService.submitFormWithFile('doc/store.html', fd, '', (response){
             console.log(response)
        });
    }

//Service called in above

    MyService.submitFormWithFile = function(url, data, config, callback) {
    $http({
        method : 'POST',
        url : url,
        headers : {
            'Content-Type' : undefined
        },
        data : data,
        transformRequest : function(data, headersGetterFunction) {
            return data;
        }
    }).success(function(response, status, header, config) {
        if (status === 200) {
            callback(response);
        } else {
            console.log("error")
        }
    }).error(function(response, status, header, config) {
            console.log(response);
    });
};

// in your java part using ObjectMapper

//it is like  string
fd.append('jsondata', JSON.stringify($scope.jsonData));

  @Autowired
  private ObjectMapper mapper;

 @RequestMapping(value = "/companies", method = RequestMethod.POST)
   public void createCompany(@RequestParam String jsondata,
        @RequestParam(required = true) MultipartFile file){

        CompanyDto companyDto=mapper.readValue(jsondata, CompanyDTO.class);
       ......
 }


问:
WordPress resuming an order from My Account page
I have been looking for a while but haven't found the answer. Can someone tell me if there is a WordPress/Woocommerce hook we can use when someone is paying for an order from My Account page. An order can be created but then perhaps payment fails or the customer cancels the transaction. If they go to their My Account page they can pay for the order & resume it. I need to do a check here & throw an error if a condition is not met before they make payment. So between clicking "Pay for order" & actually paying for the order.</p>

答:
I understood your problem. There are many types by which you can get this, but for you, you can use order status. First of all, check order status which is not completed, then pull that order and set status pending again. You can do it with the code and with admin panel, for your help.</p>

```<code>function mysite_woocommerce_order_status_completed( $order_id ) {
    error_log( "Order complete for order $order_id", 0 );
}
add_action( 'woocommerce_order_status_completed', 'mysite_woocommerce_order_status_completed', 10, 1 );
</code>```

Body:
I understood your problem. There are many types by which you can get this, but for you, you can use order status. First of all, check order status which is not completed, then pull that order and set status pending again. You can do it with the code and with admin panel, for your help.

function mysite_woocommerce_order_status_completed( $order_id ) {
    error_log( "Order complete for order $order_id", 0 );
}
add_action( 'woocommerce_order_status_completed', 'mysite_woocommerce_order_status_completed', 10, 1 );


问:
redis expireAt not getting expired in server
I am trying to auto expire the key in redis

```<code>when=10
unit='seconds'
redisClient.expireat(key,moment().add(when,unit));
</code>```

On redis cli
Keys *
I can see the key I have set

```<code>> TTL 472962f1-10ad8-4c4d-bc5e-2e38b632f36
(integer) -1
> Exists 472962f1-10ad8-4c4d-bc5e-2e38b632f36
(integer) 1
</code>```

and after 10 second it is not getting deleted !

I am using moment to get the time as I have to share the info in response that this key will not working after this.

```<code>var whenKeyExpire = moment().add(when,unit).format('MM-DD-YYYY hh:mm:ss A')
</code>```

答:
In your case, you're passing wrong value into the parameter of expireat function. For this function you have to check here. In this function you have to pass unixtime.
So for your scenario you can do something like this :

```<code>var when=10;
var unit="seconds";
redisClient.expireat(key, +new Date(moment().add(when,unit)), function (err, didSetExpiry){
   if(err){
      console.log("Error occured: " + err);
   } else {
      console.log("Redis Key Operation is successful");
   }
});
</code>```

Hope that it will help.

Body:
I am trying to auto expire the key in redis

when=10
unit='seconds'
redisClient.expireat(key,moment().add(when,unit));

On redis cli
Keys *
I can see the key I have set

> TTL 472962f1-10ad8-4c4d-bc5e-2e38b632f36
(integer) -1
> Exists 472962f1-10ad8-4c4d-bc5e-2e38b632f36
(integer) 1

and after 10 second it is not getting deleted !

I am using moment to get the time as I have to share the info in response that this key will not working after this.

var whenKeyExpire = moment().add(when,unit).format('MM-DD-YYYY hh:mm:ss A')

Body:
In your case, you're passing wrong value into the parameter of expireat function. For this function you have to check here. In this function you have to pass unixtime.
So for your scenario you can do something like this :

var when=10;
var unit="seconds";
redisClient.expireat(key, +new Date(moment().add(when,unit)), function (err, didSetExpiry){
   if(err){
      console.log("Error occured: " + err);
   } else {
      console.log("Redis Key Operation is successful");
   }
});

Hope that it will help.


问:
Scrape JSON from webpage with C#
New to C# here and to running asynchronous tasks.

I'm trying to scrape some music album info from a website. The webpage's search produces a JSON object in plaintext, but I can't seem to access any DOM info. Here's what I tried (using HtmlAgilityPack):

```<code>using HtmlAgilityPack;
using System;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp1 {
public partial class Form1 : Form {
    public Form1() {
        InitializeComponent();
    }

    public async Task<String> AlbumScraper(string albumname) {

        HtmlWeb web = new HtmlWeb();

        string albumurl = Uri.EscapeUriString("https://www.metal-archives.com/search/ajax-album-search/?field=title&query=" + albumname);
        Console.Write(albumurl);
        var albumdoc = await Task.Factory.StartNew(() => web.Load(albumurl));
        string albumjson = "";

        if (albumdoc.DocumentNode != null) {
            albumjson = albumdoc.DocumentNode.InnerText;
        }

        return albumjson;
    }

    private async void Form1_Load(object sender, EventArgs e) {
        string rawtext = await AlbumScraper("rust+in+peace");
        Console.Write(rawtext);
    }
}
}
</code>```

How can I grab the JSON text generated? I can see it clearly when I load the "albumurl" URL...

答:
Firstly you don't need HtmlAgilityPack.

Secondly,try:

```<code>using Newtonsoft.Json.Linq;

string albumurl = Uri.EscapeUriString("https://www.metal-archives.com/search/ajax-album-search/?field=title&query=rust+in+peace");
string doc = "";
using (System.Net.WebClient client = new System.Net.WebClient()) // WebClient class inherits IDisposable
{
    doc = client.DownloadString(albumurl);
}
</code>```

then you could deserialize it (@itikhomi)

```<code>AlbumSearchResponse data = JsonConvert.DeserializeObject<AlbumSearchResponse>(doc);
</code>```

You could also parse it manually

```<code>JObject json = JObject.Parse(doc);
string error= Convert.ToString(json["error"]);
. . .
string aaData= Convert.ToString(json["aaData"]);
JArray arr = JArray.Parse(aaData);
foreach(JToken token in arr)
{
    string[] strarr = token.ToObject<string[]>();
}
</code>```

Title: Scrape JSON from webpage with C#

Body:
New to C# here and to running asynchronous tasks.

I'm trying to scrape some music album info from a website. The webpage's search produces a JSON object in plaintext, but I can't seem to access any DOM info. Here's what I tried (using HtmlAgilityPack):

using HtmlAgilityPack;
using System;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp1 {
public partial class Form1 : Form {
    public Form1() {
        InitializeComponent();
    }

    public async Task<String> AlbumScraper(string albumname) {

        HtmlWeb web = new HtmlWeb();

        string albumurl = Uri.EscapeUriString("https://www.metal-archives.com/search/ajax-album-search/?field=title&query=" + albumname);
        Console.Write(albumurl);
        var albumdoc = await Task.Factory.StartNew(() => web.Load(albumurl));
        string albumjson = "";

        if (albumdoc.DocumentNode != null) {
            albumjson = albumdoc.DocumentNode.InnerText;
        }

        return albumjson;
    }

    private async void Form1_Load(object sender, EventArgs e) {
        string rawtext = await AlbumScraper("rust+in+peace");
        Console.Write(rawtext);
    }
}
}

How can I grab the JSON text generated? I can see it clearly when I load the "albumurl" URL...

Body:
Firstly you don't need HtmlAgilityPack.

Secondly,try:

using Newtonsoft.Json.Linq;

string albumurl = Uri.EscapeUriString("https://www.metal-archives.com/search/ajax-album-search/?field=title&query=rust+in+peace");
string doc = "";
using (System.Net.WebClient client = new System.Net.WebClient()) // WebClient class inherits IDisposable
{
    doc = client.DownloadString(albumurl);
}

then you could deserialize it (@itikhomi)

AlbumSearchResponse data = JsonConvert.DeserializeObject<AlbumSearchResponse>(doc);

You could also parse it manually

JObject json = JObject.Parse(doc);
string error= Convert.ToString(json["error"]);
. . .
string aaData= Convert.ToString(json["aaData"]);
JArray arr = JArray.Parse(aaData);
foreach(JToken token in arr)
{
    string[] strarr = token.ToObject<string[]>();
}