问:
Is try-catch like error handling possible in ASP Classic?
What options are there in ASP Classic for error handling?

For example:

I'm using the Mail.SendMail function but when switching on the testing server it doesn't work, which is normal. I want to test if mailing is possible, if not then continue and/or show a message.

Any ideas?

答:
Been a while since I was in ASP land, but iirc there's a couple of ways:

try catch finally can be reasonably simulated in VBS (good article here here)  and there's an event called class_terminate you can watch and catch exceptions globally in. Then there's the possibility of changing your scripting language...

OwnerDisplayName: Sander Versluys

OwnerDisplayName: annakata

LastEditorDisplayName: annakata


来源: stackexchange

问:
Scrapy JSON output - values empty
I would like to crawl a set of web pages using scrapy.  However, when I try to write some values into the json file, those fields don't show up.

Here is my code:

```<code>import scrapy

class LLPubs (scrapy.Spider):
    name = "linlinks"
    start_urls = [
        'http://www.linnaeuslink.org/records/record/1',
        'http://www.linnaeuslink.org/records/record/2',
    ]

    def parse(self, response):
        for container in response.css('div.item'):
            yield {
                'text': container.css('div.field.soulsbyNo .value span::text').extract(),
                'uniformtitle': container.css('div.field.uniformTitle .value span::text').extract(),
                'title': container.css('div.field.title .value span::text').extract(),
                'opac': container.css('div.field.localControlNo .value span::text').extract(),
                'url': container.css('div#digitalLinks li a').extract(),
                'partner': container.css('div.logoContainer  img:first-child').xpath('@src').extract(),
                }
</code>```

And an example of my output:

```<code>{
"text": ["Soulsby no. 46(1)"],
"uniformtitle": ["Systema naturae"],
"title": ["Caroli Linn\u00e6i ... Systema natur\u00e6\nin quo natur\u00e6 regna tria, secundum classes, ordines, genera, species, systematice proponuntur."],
"opac": ["002178079"],
"url": [],
"partner": []
},
</code>```

I am hoping I am doing something silly and easy to fix!  Both of the paths I am using for "url" and "partner" were working from here:

```<code>scrapy shell 'http://www.linnaeuslink.org/records/record/1'
</code>```

So, I just don't know what I am missing.

Oh, and exporting to json by using this command for now:

```<code>scrapy crawl linlinks -o quotes.json
</code>```

Thanks for your help!

答: The problem seems to be that those selectors are not "findable" inside any div.item you probably have validated them without the response.css('div.item') to replicate what you used in the shell just replace the container.css by response.css for the url and partner keys.

ContentLicense: CC BY-SA 3.0

Title: Scrapy JSON output - values empty

Body:
I would like to crawl a set of web pages using scrapy.  However, when I try to write some values into the json file, those fields don't show up.

Here is my code:

import scrapy

class LLPubs (scrapy.Spider):
    name = "linlinks"
    start_urls = [
        'http://www.linnaeuslink.org/records/record/1',
        'http://www.linnaeuslink.org/records/record/2',
    ]

    def parse(self, response):
        for container in response.css('div.item'):
            yield {
                'text': container.css('div.field.soulsbyNo .value span::text').extract(),
                'uniformtitle': container.css('div.field.uniformTitle .value span::text').extract(),
                'title': container.css('div.field.title .value span::text').extract(),
                'opac': container.css('div.field.localControlNo .value span::text').extract(),
                'url': container.css('div#digitalLinks li a').extract(),
                'partner': container.css('div.logoContainer  img:first-child').xpath('@src').extract(),
                }

And an example of my output:

{
"text": ["Soulsby no. 46(1)"],
"uniformtitle": ["Systema naturae"],
"title": ["Caroli Linn\u00e6i ... Systema natur\u00e6\nin quo natur\u00e6 regna tria, secundum classes, ordines, genera, species, systematice proponuntur."],
"opac": ["002178079"],
"url": [],
"partner": []
},

I am hoping I am doing something silly and easy to fix!  Both of the paths I am using for "url" and "partner" were working from here:

scrapy shell 'http://www.linnaeuslink.org/records/record/1'

So, I just don't know what I am missing.

Oh, and exporting to json by using this command for now:

scrapy crawl linlinks -o quotes.json

Thanks for your help!


问:
When an ASP.NET System.Web.HttpResponse.End() is called, the current thread is aborted?
when a System.Web.HttpResponse.End() is called a System.Thread.Abort is being fired, which i'm guessing is (or fires) an exception? I've got some logging and this is being listed in the log file...

A first chance

```<code>exception of type 'System.Threading.ThreadAbortException' occurred in mscorlib.dll
12/14/2008 01:09:31::
Error in Path :/authenticate
Raw Url :/authenticate
Message :Thread was being aborted.
Source :mscorlib
Stack Trace :   at System.Threading.Thread.AbortInternal()
   at System.Threading.Thread.Abort(Object stateInfo)
   at System.Web.HttpResponse.End()
   at DotNetOpenId.Response.Send()
   at DotNetOpenId.RelyingParty.AuthenticationRequest.RedirectToProvider()
   at MyProject.Services.Authentication.OpenIdAuthenticationService.GetOpenIdPersonaDetails(Uri serviceUri) in C:\Users\Pure Krome\Documents\Visual Studio 2008\Projects\MyProject\Projects\Services\Authentication\OpenIdAuthenticationService.cs:line 108
   at MyProject.Mvc.Controllers.AuthenticationController.Authenticate() in C:\Users\Pure Krome\Documents\Visual Studio 2008\Projects\MyProject\Projects\MVC Application\Controllers\AuthenticationController.cs:line 69
TargetSite :Void AbortInternal()
A first chance exception of type 'System.Threading.ThreadAbortException' occurred in Ackbar.Mvc.DLL
An exception of type 'System.Threading.ThreadAbortException' occurred in Ackbar.Mvc.DLL but was not handled in user code
</code>```

Is this normal behavior and is it possible to gracefully abort instead of (what looks like) a sudden abrupt abort?

Update

So far it the common census that it's by design. So i'm wondering if it's possible we could take this question and see if we could tweak the code to make it not feel like we're ending the thread prematurely and gracefully exit ... Possible? Code examples?

答:
I used all above changes but still I was getting same issue on my web application.

Then I contacted my hosting provide & asked them to check if any software or antivirus blocking our files to transfer via HTTP. or ISP/network is not allowing file to transfer.

They checked server settings & bypass the "Data Center Shared Firewall" for my server & now our application started to download the file.

Hope this answer will help someone.This is what worked for me

ContentLicense: CC BY-SA 2.5

Body:
when a System.Web.HttpResponse.End() is called a System.Thread.Abort is being fired, which i'm guessing is (or fires) an exception? I've got some logging and this is being listed in the log file...

A first chance

exception of type 'System.Threading.ThreadAbortException' occurred in mscorlib.dll
12/14/2008 01:09:31::
Error in Path :/authenticate
Raw Url :/authenticate
Message :Thread was being aborted.
Source :mscorlib
Stack Trace :   at System.Threading.Thread.AbortInternal()
   at System.Threading.Thread.Abort(Object stateInfo)
   at System.Web.HttpResponse.End()
   at DotNetOpenId.Response.Send()
   at DotNetOpenId.RelyingParty.AuthenticationRequest.RedirectToProvider()
   at MyProject.Services.Authentication.OpenIdAuthenticationService.GetOpenIdPersonaDetails(Uri serviceUri) in C:\Users\Pure Krome\Documents\Visual Studio 2008\Projects\MyProject\Projects\Services\Authentication\OpenIdAuthenticationService.cs:line 108
   at MyProject.Mvc.Controllers.AuthenticationController.Authenticate() in C:\Users\Pure Krome\Documents\Visual Studio 2008\Projects\MyProject\Projects\MVC Application\Controllers\AuthenticationController.cs:line 69
TargetSite :Void AbortInternal()
A first chance exception of type 'System.Threading.ThreadAbortException' occurred in Ackbar.Mvc.DLL
An exception of type 'System.Threading.ThreadAbortException' occurred in Ackbar.Mvc.DLL but was not handled in user code

Is this normal behavior and is it possible to gracefully abort instead of (what looks like) a sudden abrupt abort?

Update

So far it the common census that it's by design. So i'm wondering if it's possible we could take this question and see if we could tweak the code to make it not feel like we're ending the thread prematurely and gracefully exit ... Possible? Code examples?


问:
Appcelerator Android Facebook login error code 2500
Little Appcelerator Facebook login problem with Android API 6.2.0. The Facebook login screen shows. I login with no problem. It says that I've previously given permission to that app with Facebook. I click to "Continue". Then I get this error code 2500. Here's the log:

```<code>// I added the X's to the token & uid for this log

[DEBUG] :  TiFacebookModule: (main) [1,298128] authorize called, permissions length: 1
[DEBUG] :  TiFacebookModule: (main) [1,298129] authorizing permission: email
[DEBUG] :  ActivityWorkerProxy: (main) [27137,325266] ActivityWorkerProxy onActivityResult
[DEBUG] :  TiFacebookModule: (main) [251,325517] user is not null
[DEBUG] :  TiFacebookModule: (main) [0,325517] firing login event from module
[WARN] :   TiFacebookModule: (main) [0,325517] The getCanPresentOpenGraphActionDialog property is deprecated. This always returns true.
[DEBUG] :  TiFacebookModule: (main) [1,325518] get accessToken
[WARN] :   TiFacebookModule: (main) [0,325518] The getCanPresentShareDialog property is deprecated. This always returns true.
[INFO] :   Facebook: SUCCESS // {"type":"login","source":{"loggedIn":true,"canPresentOpenGraphActionDialog":true,"permissions":["email","public_profile"],"accessToken":"EAADVQzAhldwBAN3ZCLDyeVF6NiWoIxLV1x8KTeAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXifLwjJPSDE7BFckLwMxJPmTu3BecteHVyutEc2uxbTV4ccG6OciIIOsXpTpewNlZC5hJkV1l0NtsjrFZARKdZBABOcZASPHjs0XZA6o9JRqlwkAX2S40ZCG0AqzsZD","loginBehavior":null,"canPresentShareDialog":true,"expirationDate":"2018-01-10T21:22:24.457Z","uid":"1163XXXXXXX6528","apiName":"Ti.Module","bubbleParent":true,"invocationAPIs":[{"namespace":"Facebook","api":"createActivityWorker"},{"namespace":"Facebook","api":"createLikeButton"},{"namespace":"Facebook","api":"createLoginButton"}],"__propertiesDefined__":true,"_events":{"login":{}}},"data":"{\"id\":\"1163XXXXXXX6528\",\"name\":\"Byte Bbt\"}","uid":"1163XXXXXXX6528","cancelled":false,"bubbles":false,"success":true,"code":0,"cancelBubble":false}
[INFO] :   me?fields=name,email,first_name,last_name
[ERROR] :  TiFacebookModule: (main) [70,325588] requestWithGraphPath callback error: An active access token must be used to query information about the current user.
[INFO] :   results From Graph API: {"error":"An error code 2500 has occured. An active access token must be used to query information about the current user."}
[ERROR] :  TiExceptionHandler: (main) [2,325590] ----- Titanium Javascript Runtime Error -----
[ERROR] :  TiExceptionHandler: (main) [0,325590] - In undefined:1,1
[ERROR] :  TiExceptionHandler: (main) [0,325590] - Message: Uncaught SyntaxError: Unexpected token u in JSON at position 0
[ERROR] :  TiExceptionHandler: (main) [0,325590] - Source: undefined
</code>```

This same code works perfectly on iOS:

```<code>var fb = require('facebook');
$.index.fbProxy = fb.createActivityWorker({lifecycleContainer: $.index});
fb.permissions = ['email'];
fb.initialize();

fb.addEventListener('login', function(e) {
    if (e.success) {
        Ti.App.FBuid   = e.uid;
        Ti.App.FBtoken = e.source.accessToken;
        Ti.App.FBname  = JSON.parse(e.data).name;
        Ti.API.info('Facebook: SUCCESS // ' + JSON.stringify(e));

        // This test didn't work
        // "me?accessToken=" + Ti.App.FBtoken + "&uid=" + Ti.App.FBuid + "&u=" + Ti.App.FBuid + "&fields=name,email,first_name,last_name"

        Ti.API.info("me?fields=name,email,first_name,last_name");
        fb.requestWithGraphPath("me?fields=name,email,first_name,last_name", {}, 'GET', function(result) {
            Ti.API.info('results From Graph API: ' + JSON.stringify(result));
            var data = JSON.parse(result.result);
            Ti.API.info("-- email: " + data.email);
            Ti.App.FBemail = data.email;
            Ti.App.FBfname = data.first_name;
            Ti.App.FBlname = data.last_name;
        });
    } else if (e.cancelled) {
        Ti.API.info('Facebook: FAIL');
    } else {
        $.blackout.hide();
        Ti.API.info('Facebook: ERROR // ' + e.error);
        alert("Oops. Something went wrong.\nPlease try again.");
    }
});

fb.authorize();
</code>```

Any idea how I can get rid of this "active access token" 2500 error? Thanks.

答:
I guess you are using old format of passing fields to requestGraphApi.

Try this, I have formatted your code a bit as following:

```<code>var fb = require('facebook');

// set permissions first
fb.permissions = ['public_profile', 'email'];

// then add event listener
fb.addEventListener('login', facebookLogin);

// finally initialize
fb.initialize();

// attach proxy after initialisation
$.index.fbProxy = fb.createActivityWorker({lifecycleContainer: $.index});

// Pass fields as dictionary to be comaptible with latest graph api.
function facebookLogin(e) {
    if (e.success) {
        Ti.App.FBuid   = e.uid;

        // I think you don't need accessToken to store, Facebook module will use it properly when you call graph api.
        Ti.App.FBtoken = e.source.accessToken;
        Ti.App.FBname  = JSON.parse(e.data).name;

        // pass fields as dictionary
        fb.requestWithGraphPath("me", {fields:'name,email,first_name,last_name,gender', 'GET', function(result) {
            Ti.API.info('results From Graph API: ' + JSON.stringify(result));
            var data = JSON.parse(result.result);
            Ti.API.info("-- email: " + data.email);

            // this is not recommended approach to modify internal api Ti.App
            Ti.App.FBemail = data.email;
            Ti.App.FBfname = data.first_name;
            Ti.App.FBlname = data.last_name;
        });
    } else if (e.cancelled) {
        Ti.API.info('Facebook: FAIL');
    } else {
        $.blackout.hide();
        Ti.API.info('Facebook: ERROR // ' + e.error);
        alert("Oops. Something went wrong.\nPlease try again.");
    }
}

fb.authorize();
</code>```

Body:
Little Appcelerator Facebook login problem with Android API 6.2.0. The Facebook login screen shows. I login with no problem. It says that I've previously given permission to that app with Facebook. I click to "Continue". Then I get this error code 2500. Here's the log:

// I added the X's to the token & uid for this log

[DEBUG] :  TiFacebookModule: (main) [1,298128] authorize called, permissions length: 1
[DEBUG] :  TiFacebookModule: (main) [1,298129] authorizing permission: email
[DEBUG] :  ActivityWorkerProxy: (main) [27137,325266] ActivityWorkerProxy onActivityResult
[DEBUG] :  TiFacebookModule: (main) [251,325517] user is not null
[DEBUG] :  TiFacebookModule: (main) [0,325517] firing login event from module
[WARN] :   TiFacebookModule: (main) [0,325517] The getCanPresentOpenGraphActionDialog property is deprecated. This always returns true.
[DEBUG] :  TiFacebookModule: (main) [1,325518] get accessToken
[WARN] :   TiFacebookModule: (main) [0,325518] The getCanPresentShareDialog property is deprecated. This always returns true.
[INFO] :   Facebook: SUCCESS // {"type":"login","source":{"loggedIn":true,"canPresentOpenGraphActionDialog":true,"permissions":["email","public_profile"],"accessToken":"EAADVQzAhldwBAN3ZCLDyeVF6NiWoIxLV1x8KTeAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXifLwjJPSDE7BFckLwMxJPmTu3BecteHVyutEc2uxbTV4ccG6OciIIOsXpTpewNlZC5hJkV1l0NtsjrFZARKdZBABOcZASPHjs0XZA6o9JRqlwkAX2S40ZCG0AqzsZD","loginBehavior":null,"canPresentShareDialog":true,"expirationDate":"2018-01-10T21:22:24.457Z","uid":"1163XXXXXXX6528","apiName":"Ti.Module","bubbleParent":true,"invocationAPIs":[{"namespace":"Facebook","api":"createActivityWorker"},{"namespace":"Facebook","api":"createLikeButton"},{"namespace":"Facebook","api":"createLoginButton"}],"__propertiesDefined__":true,"_events":{"login":{}}},"data":"{\"id\":\"1163XXXXXXX6528\",\"name\":\"Byte Bbt\"}","uid":"1163XXXXXXX6528","cancelled":false,"bubbles":false,"success":true,"code":0,"cancelBubble":false}
[INFO] :   me?fields=name,email,first_name,last_name
[ERROR] :  TiFacebookModule: (main) [70,325588] requestWithGraphPath callback error: An active access token must be used to query information about the current user.
[INFO] :   results From Graph API: {"error":"An error code 2500 has occured. An active access token must be used to query information about the current user."}
[ERROR] :  TiExceptionHandler: (main) [2,325590] ----- Titanium Javascript Runtime Error -----
[ERROR] :  TiExceptionHandler: (main) [0,325590] - In undefined:1,1
[ERROR] :  TiExceptionHandler: (main) [0,325590] - Message: Uncaught SyntaxError: Unexpected token u in JSON at position 0
[ERROR] :  TiExceptionHandler: (main) [0,325590] - Source: undefined

This same code works perfectly on iOS:

var fb = require('facebook');
$.index.fbProxy = fb.createActivityWorker({lifecycleContainer: $.index});
fb.permissions = ['email'];
fb.initialize();

fb.addEventListener('login', function(e) {
    if (e.success) {
        Ti.App.FBuid   = e.uid;
        Ti.App.FBtoken = e.source.accessToken;
        Ti.App.FBname  = JSON.parse(e.data).name;
        Ti.API.info('Facebook: SUCCESS // ' + JSON.stringify(e));

        // This test didn't work
        // "me?accessToken=" + Ti.App.FBtoken + "&uid=" + Ti.App.FBuid + "&u=" + Ti.App.FBuid + "&fields=name,email,first_name,last_name"

        Ti.API.info("me?fields=name,email,first_name,last_name");
        fb.requestWithGraphPath("me?fields=name,email,first_name,last_name", {}, 'GET', function(result) {
            Ti.API.info('results From Graph API: ' + JSON.stringify(result));
            var data = JSON.parse(result.result);
            Ti.API.info("-- email: " + data.email);
            Ti.App.FBemail = data.email;
            Ti.App.FBfname = data.first_name;
            Ti.App.FBlname = data.last_name;
        });
    } else if (e.cancelled) {
        Ti.API.info('Facebook: FAIL');
    } else {
        $.blackout.hide();
        Ti.API.info('Facebook: ERROR // ' + e.error);
        alert("Oops. Something went wrong.\nPlease try again.");
    }
});

fb.authorize();

Any idea how I can get rid of this "active access token" 2500 error? Thanks.

Body:
I guess you are using old format of passing fields to requestGraphApi.

Try this, I have formatted your code a bit as following:

var fb = require('facebook');

// set permissions first
fb.permissions = ['public_profile', 'email'];

// then add event listener
fb.addEventListener('login', facebookLogin);

// finally initialize
fb.initialize();

// attach proxy after initialisation
$.index.fbProxy = fb.createActivityWorker({lifecycleContainer: $.index});

// Pass fields as dictionary to be comaptible with latest graph api.
function facebookLogin(e) {
    if (e.success) {
        Ti.App.FBuid   = e.uid;

        // I think you don't need accessToken to store, Facebook module will use it properly when you call graph api.
        Ti.App.FBtoken = e.source.accessToken;
        Ti.App.FBname  = JSON.parse(e.data).name;

        // pass fields as dictionary
        fb.requestWithGraphPath("me", {fields:'name,email,first_name,last_name,gender', 'GET', function(result) {
            Ti.API.info('results From Graph API: ' + JSON.stringify(result));
            var data = JSON.parse(result.result);
            Ti.API.info("-- email: " + data.email);

            // this is not recommended approach to modify internal api Ti.App
            Ti.App.FBemail = data.email;
            Ti.App.FBfname = data.first_name;
            Ti.App.FBlname = data.last_name;
        });
    } else if (e.cancelled) {
        Ti.API.info('Facebook: FAIL');
    } else {
        $.blackout.hide();
        Ti.API.info('Facebook: ERROR // ' + e.error);
        alert("Oops. Something went wrong.\nPlease try again.");
    }
}

fb.authorize();


问:
How to call window.location.pathname inline in ternary operator Angularjs
I am trying to write an conditional statement inline in Angularjs. Basically, I want to make it so when a tab is clicked on a page, the page is update to aria-current="page". The way I was going to do this is to check if the tabs anchor href is equal to the current windows pathname. I'm hoping someone can help me figure out the correct syntax or ternary structure to make this work inline. The below code is not working for me.

aria-current="{{ window.location.pathname == 'item.location' && 'page' || 'notpage'}}"

In this case item.location is the value of the anchors href.

答:
Try this

```<code>aria-current= (window.location.pathname == item.location)?'page':'notpage';
</code>```

For angular
do something like this in controller

```<code> $rootScope.location = $location;
</code>```

then add following

```<code>aria-current="{{location.path() ==item.location?'page':'notpage'}}"
</code>```

Body:
Try this

aria-current= (window.location.pathname == item.location)?'page':'notpage';

For angular
do something like this in controller

 $rootScope.location = $location;

then add following

aria-current="{{location.path() ==item.location?'page':'notpage'}}"


问:
TextChangedListener not doing anything
I am trying to use TextChangedListener to implement search functionality on my ListView. But after adding some character in EditText; the ListView goes blank. I have implemented filter method in my ArrayAdapter class.

I am getting my data from JSON.

Here's my code:

UserList.java

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

private ListView listView;
private ArrayList<MyDataModel> list;
private MyArrayAdapter adapter;
private EditText search;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.user_list);

    search = (EditText) findViewById(R.id.search);

    //Array List for Binding Data from JSON to this List
    list = new ArrayList<>();

    //Binding that List to Adapter
    adapter = new MyArrayAdapter(this, list);

    //Getting List and Setting List Adapter
    listView = (ListView) findViewById(R.id.listView);
    listView.setAdapter(adapter);

    listView.setTextFilterEnabled(true);
    search.addTextChangedListener(new TextWatcher() {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

            String text = search.getText().toString().toLowerCase(Locale.getDefault());
            adapter.filter(text);
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    });

    //Checking Internet Connection
    if (InternetConnection.checkConnection(getApplicationContext())) {
        new GetDataTask().execute();
    } else {
        Snackbar.make(findViewById(R.id.parentLayout),"Internet Connection Not Available", Snackbar.LENGTH_LONG).show();
    }
}

//Creating Get Data Task for Getting Data From Web
class GetDataTask extends AsyncTask<Void, Void, Void> {

    ProgressDialog dialog;
    int jIndex;
    int x;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        //Progress Dialog for User Interaction
        x=list.size();

        if(x==0)
            jIndex=0;
        else
            jIndex=x;

        dialog = new ProgressDialog(UserList.this);
        dialog.setTitle("Please Wait..."+x);
        dialog.setMessage("Retrieving Data");
        dialog.show();

    }

    @Nullable
    @Override
    protected Void doInBackground(Void... params) {

        //Getting JSON Object from Web Using okHttp
        JSONObject jsonObject = JSONParser.getDataFromWeb();

        try {

            if (jsonObject != null) {

                if(jsonObject.length() > 0) {

                    JSONArray array = jsonObject.getJSONArray(Keys.KEY_CONTACTS);

                    //Check Length of Array...
                    int lenArray = array.length();
                    if(lenArray > 0) {
                        for( ; jIndex < lenArray; jIndex++) {

                            //Creating Every time New Object and adding to List
                            MyDataModel model = new MyDataModel();

                            JSONObject innerObject = array.getJSONObject(jIndex);
                            String name = innerObject.getString(Keys.KEY_NAME);

                            model.setName(name);
                            list.add(model);
                        }
                    }
                }
            } else {

            }
        } catch (JSONException je) {
            Log.i(JSONParser.TAG, "" + je.getLocalizedMessage());
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        dialog.dismiss();

        //Checking if List size if more than zero then update ListView
        if(list.size() > 0) {
            adapter.notifyDataSetChanged();

        } else {
            Snackbar.make(findViewById(R.id.parentLayout), "No Data Found", Snackbar.LENGTH_LONG).show();
        }

    }
}
}
</code>```

I have implemented the filter method in my ArrayAdapter class.

Here's my ArrayAdapter class:

MyArrayAdapter.java

```<code>public class MyArrayAdapter extends ArrayAdapter<MyDataModel> implements Filterable{

List<MyDataModel> modelList;
Context context;
private LayoutInflater mInflater;
private ArrayList<MyDataModel> arrayList;

public MyArrayAdapter(Context context, List<MyDataModel> objects) {
    super(context, 0, objects);
    this.context = context;
    this.mInflater = LayoutInflater.from(context);
    modelList = objects;

    this.arrayList = new ArrayList<MyDataModel>();
    this.arrayList.addAll(modelList);
}

@Override
public MyDataModel getItem(int position) {
    return modelList.get(position);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    final ViewHolder vh;
    if (convertView == null) {
        View view = mInflater.inflate(R.layout.layout_row_view, parent, false);
        vh = ViewHolder.create((RelativeLayout) view);
        view.setTag(vh);
    } else {
        vh = (ViewHolder) convertView.getTag();
    }

    MyDataModel item = getItem(position);

    vh.textViewName.setText(item.getName());
    return vh.rootView;
}

private static class ViewHolder {
    public final RelativeLayout rootView;

    public final TextView textViewName;

    private ViewHolder(RelativeLayout rootView, TextView textViewName) {
        this.rootView = rootView;
        this.textViewName = textViewName;
    }

    public static ViewHolder create(RelativeLayout rootView) {
        TextView textViewName = (TextView) rootView.findViewById(R.id.textViewName);
        return new ViewHolder(rootView, textViewName);
    }
}

// Filter Class
public void filter(String charText) {
    charText = charText.toLowerCase(Locale.getDefault());
    modelList.clear();
    if (charText.length() == 0) {
        modelList.addAll(arrayList);
    } else {
        for (MyDataModel wp : arrayList) {
            if (wp.getName().toLowerCase(Locale.getDefault()).contains(charText)) {
                modelList.add(wp);
            }
        }
    }
    notifyDataSetChanged();
}
</code>```

答:
You need to create one more arryList to filter data.

```<code>public class MyArrayAdapter extends ArrayAdapter<MyDataModel> implements Filterable{

List<MyDataModel> modelList;
Context context;
private LayoutInflater mInflater;
private ArrayList<MyDataModel> arrayList;

public MyArrayAdapter(Context context, List<MyDataModel> objects) {
super(context, 0, objects);
this.context = context;
this.mInflater = LayoutInflater.from(context);
modelList = objects;
this.arrayList = new ArrayList<MyDataModel>();
    this.arraylist.addAll(modelList);
}
</code>```

Now in Filter method you have to compare on the basis of arrayList

```<code>// Filter Class
 public void filter(String charText) {
 charText = charText.toLowerCase(Locale.getDefault());
 modelList.clear();
if (charText.length() == 0) {
    modelList.addAll(arrayList);
    } else {
    for (MyDataModel wp : arrayList) {
        if
   (wp.getName().toLowerCase(Locale.getDefault()).contains(charText)) {
            modelList.add(wp);
        }
     }
    }
 notifyDataSetChanged();
}
</code>```

Title: TextChangedListener not doing anything

Body:
I am trying to use TextChangedListener to implement search functionality on my ListView. But after adding some character in EditText; the ListView goes blank. I have implemented filter method in my ArrayAdapter class.

I am getting my data from JSON.

Here's my code:

UserList.java

public class UserList extends AppCompatActivity {

private ListView listView;
private ArrayList<MyDataModel> list;
private MyArrayAdapter adapter;
private EditText search;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.user_list);

    search = (EditText) findViewById(R.id.search);

    //Array List for Binding Data from JSON to this List
    list = new ArrayList<>();

    //Binding that List to Adapter
    adapter = new MyArrayAdapter(this, list);

    //Getting List and Setting List Adapter
    listView = (ListView) findViewById(R.id.listView);
    listView.setAdapter(adapter);

    listView.setTextFilterEnabled(true);
    search.addTextChangedListener(new TextWatcher() {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

            String text = search.getText().toString().toLowerCase(Locale.getDefault());
            adapter.filter(text);
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    });

    //Checking Internet Connection
    if (InternetConnection.checkConnection(getApplicationContext())) {
        new GetDataTask().execute();
    } else {
        Snackbar.make(findViewById(R.id.parentLayout),"Internet Connection Not Available", Snackbar.LENGTH_LONG).show();
    }
}

//Creating Get Data Task for Getting Data From Web
class GetDataTask extends AsyncTask<Void, Void, Void> {

    ProgressDialog dialog;
    int jIndex;
    int x;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        //Progress Dialog for User Interaction
        x=list.size();

        if(x==0)
            jIndex=0;
        else
            jIndex=x;

        dialog = new ProgressDialog(UserList.this);
        dialog.setTitle("Please Wait..."+x);
        dialog.setMessage("Retrieving Data");
        dialog.show();

    }

    @Nullable
    @Override
    protected Void doInBackground(Void... params) {

        //Getting JSON Object from Web Using okHttp
        JSONObject jsonObject = JSONParser.getDataFromWeb();

        try {

            if (jsonObject != null) {

                if(jsonObject.length() > 0) {

                    JSONArray array = jsonObject.getJSONArray(Keys.KEY_CONTACTS);

                    //Check Length of Array...
                    int lenArray = array.length();
                    if(lenArray > 0) {
                        for( ; jIndex < lenArray; jIndex++) {

                            //Creating Every time New Object and adding to List
                            MyDataModel model = new MyDataModel();

                            JSONObject innerObject = array.getJSONObject(jIndex);
                            String name = innerObject.getString(Keys.KEY_NAME);

                            model.setName(name);
                            list.add(model);
                        }
                    }
                }
            } else {

            }
        } catch (JSONException je) {
            Log.i(JSONParser.TAG, "" + je.getLocalizedMessage());
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        dialog.dismiss();

        //Checking if List size if more than zero then update ListView
        if(list.size() > 0) {
            adapter.notifyDataSetChanged();

        } else {
            Snackbar.make(findViewById(R.id.parentLayout), "No Data Found", Snackbar.LENGTH_LONG).show();
        }

    }
}
}

I have implemented the filter method in my ArrayAdapter class.

Here's my ArrayAdapter class:

MyArrayAdapter.java

public class MyArrayAdapter extends ArrayAdapter<MyDataModel> implements Filterable{

List<MyDataModel> modelList;
Context context;
private LayoutInflater mInflater;
private ArrayList<MyDataModel> arrayList;

public MyArrayAdapter(Context context, List<MyDataModel> objects) {
    super(context, 0, objects);
    this.context = context;
    this.mInflater = LayoutInflater.from(context);
    modelList = objects;

    this.arrayList = new ArrayList<MyDataModel>();
    this.arrayList.addAll(modelList);
}

@Override
public MyDataModel getItem(int position) {
    return modelList.get(position);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    final ViewHolder vh;
    if (convertView == null) {
        View view = mInflater.inflate(R.layout.layout_row_view, parent, false);
        vh = ViewHolder.create((RelativeLayout) view);
        view.setTag(vh);
    } else {
        vh = (ViewHolder) convertView.getTag();
    }

    MyDataModel item = getItem(position);

    vh.textViewName.setText(item.getName());
    return vh.rootView;
}

private static class ViewHolder {
    public final RelativeLayout rootView;

    public final TextView textViewName;

    private ViewHolder(RelativeLayout rootView, TextView textViewName) {
        this.rootView = rootView;
        this.textViewName = textViewName;
    }

    public static ViewHolder create(RelativeLayout rootView) {
        TextView textViewName = (TextView) rootView.findViewById(R.id.textViewName);
        return new ViewHolder(rootView, textViewName);
    }
}

// Filter Class
public void filter(String charText) {
    charText = charText.toLowerCase(Locale.getDefault());
    modelList.clear();
    if (charText.length() == 0) {
        modelList.addAll(arrayList);
    } else {
        for (MyDataModel wp : arrayList) {
            if (wp.getName().toLowerCase(Locale.getDefault()).contains(charText)) {
                modelList.add(wp);
            }
        }
    }
    notifyDataSetChanged();
}

Body:
You need to create one more arryList to filter data.

public class MyArrayAdapter extends ArrayAdapter<MyDataModel> implements Filterable{

List<MyDataModel> modelList;
Context context;
private LayoutInflater mInflater;
private ArrayList<MyDataModel> arrayList;

public MyArrayAdapter(Context context, List<MyDataModel> objects) {
super(context, 0, objects);
this.context = context;
this.mInflater = LayoutInflater.from(context);
modelList = objects;
this.arrayList = new ArrayList<MyDataModel>();
    this.arraylist.addAll(modelList);
}

Now in Filter method you have to compare on the basis of arrayList

// Filter Class
 public void filter(String charText) {
 charText = charText.toLowerCase(Locale.getDefault());
 modelList.clear();
if (charText.length() == 0) {
    modelList.addAll(arrayList);
    } else {
    for (MyDataModel wp : arrayList) {
        if
   (wp.getName().toLowerCase(Locale.getDefault()).contains(charText)) {
            modelList.add(wp);
        }
     }
    }
 notifyDataSetChanged();
}


问:
Error with functions.php file from a wordpress theme
I don't know anything about php so I cannot figure out if the error is in the code or if it is a matter of update.
When I activate a theme on my new Wordpress, I get this error message :

.

In the functions.php file, the error-related lines of code are (I believe) the following :

```<code>    if (!class_exists('mijnpress_plugin_framework')) {
    include('find_replace/mijnpress_plugin_framework.php');

}
class plugin_findreplace extends mijnpress_plugin_framework {
    function __construct() {
        $this->showcredits               = true;
        $this->showcredits_fordevelopers = true;
        $this->plugin_title              = 'Find and replace';
        $this->plugin_class              = 'plugin_findreplace';
        $this->plugin_filename           = 'find-replace/plugins/find_replace.php';
        $this->plugin_config_url         = 'plugins.php?page=' . $this->plugin_filename;
    }
    function plugin_findreplace() {
        $args = func_get_args();
        call_user_func_array(array(
            &$this,
            '__construct'
        ), $args);
    }
    function addPluginSubMenu() {
        $plugin = new plugin_findreplace();

        add_submenu_page('optionsframework', 'documentation', 'Documentation', 'manage_options', 'documentation', 'documentations_callback');
        add_submenu_page('optionsframework', 'Find & Replace', 'Find & Replace', 'manage_options', 'fine_and_replace', 'findreplace_callback');
    }
    /**
     * Additional links on the plugin page
     */
    function addPluginContent($links, $file) {
        $plugin = new plugin_findreplace();
        $links  = parent::addPluginContent($plugin->plugin_filename, $links, $file, $plugin->plugin_config_url);
        return $links;
    }
</code>```

Any ideas where the error could come from ?

答:
I think the issue might be that the function add_plugin_content() requires it to be declared with 4 parameters to be compatible with the framework.  You have declared it with only 2 parameters but should declare it like I have written below.

```<code>function addPluginContent($filename, $links, $file, $config_url) {
        // insert your code here
}
</code>```

Body:
I don't know anything about php so I cannot figure out if the error is in the code or if it is a matter of update.
When I activate a theme on my new Wordpress, I get this error message :

.

In the functions.php file, the error-related lines of code are (I believe) the following :

    if (!class_exists('mijnpress_plugin_framework')) {
    include('find_replace/mijnpress_plugin_framework.php');

}
class plugin_findreplace extends mijnpress_plugin_framework {
    function __construct() {
        $this->showcredits               = true;
        $this->showcredits_fordevelopers = true;
        $this->plugin_title              = 'Find and replace';
        $this->plugin_class              = 'plugin_findreplace';
        $this->plugin_filename           = 'find-replace/plugins/find_replace.php';
        $this->plugin_config_url         = 'plugins.php?page=' . $this->plugin_filename;
    }
    function plugin_findreplace() {
        $args = func_get_args();
        call_user_func_array(array(
            &$this,
            '__construct'
        ), $args);
    }
    function addPluginSubMenu() {
        $plugin = new plugin_findreplace();

        add_submenu_page('optionsframework', 'documentation', 'Documentation', 'manage_options', 'documentation', 'documentations_callback');
        add_submenu_page('optionsframework', 'Find & Replace', 'Find & Replace', 'manage_options', 'fine_and_replace', 'findreplace_callback');
    }
    /**
     * Additional links on the plugin page
     */
    function addPluginContent($links, $file) {
        $plugin = new plugin_findreplace();
        $links  = parent::addPluginContent($plugin->plugin_filename, $links, $file, $plugin->plugin_config_url);
        return $links;
    }

Any ideas where the error could come from ?

Body:
I think the issue might be that the function add_plugin_content() requires it to be declared with 4 parameters to be compatible with the framework.  You have declared it with only 2 parameters but should declare it like I have written below.

function addPluginContent($filename, $links, $file, $config_url) {
        // insert your code here
}


问:
Producing a more efficient for loop
I have created a function which applies a Cox regression model to test data, creates survival functions based on covariates, and then predicts the survival probability 30 days from current time for each test observation.

The example below uses the lung dataset and works quite well. However, applied to my own data the processing time is tedious. For n = 60000, I just stopped it after an hour as it is not practical for what I intend to use the program for.

Looking at the code structure, is there an obvious way I can speed this up?

```<code>require(dplyr, survival, pec)

cox_model <- coxph(Surv(time, status) ~ sex, data = lung)

surv_preds <- function(model, query) {

  prediction <- vector(mode = "numeric", length = nrow(query))
  time <- 30

  for(i in 1:nrow(query)) {
    prediction[i] <- predictSurvProb(model, newdata = query[i, ], times = query[i, "time"] + time)
  }
  prediction
}

surv_preds(cox_model, lung)
</code>```

答:
An alternate route would be the by_row function from purrrlyr in addition to the packages in the question.

```<code>library(purrrlyr)

prediction <- lung %>%
  mutate(time = time + 30) %>%
  by_row(~predictSurvProb(cox_model, newdata = ., times = .$time)) %>%
  .$.out %>%
  unlist
</code>```

It is more tidy while producing the same result, however, early runs of microbenchmark don't show an improvement in processing time.

microbenchmark

```<code># Unit: seconds
#                        expr      min       lq    mean   median       uq      max neval
# surv_preds(cox_model, lung) 1.531631 1.561518 1.59431 1.574664 1.591117 2.157002   100
# (purrrlyr)                  1.841713 1.887438 1.921371 1.90474 1.92649  2.170205   100
</code>```

This would have both solutions running over 24 hours on the hardware I'm using.
 Given this answer no longer seems to solve your problem and I am unfamiliar with parallel processing options I'm happy to delete this unless anyone finds value in keeping this here.

Title: Producing a more efficient for loop

Body:
I have created a function which applies a Cox regression model to test data, creates survival functions based on covariates, and then predicts the survival probability 30 days from current time for each test observation.

The example below uses the lung dataset and works quite well. However, applied to my own data the processing time is tedious. For n = 60000, I just stopped it after an hour as it is not practical for what I intend to use the program for.

Looking at the code structure, is there an obvious way I can speed this up?

require(dplyr, survival, pec)

cox_model <- coxph(Surv(time, status) ~ sex, data = lung)

surv_preds <- function(model, query) {

  prediction <- vector(mode = "numeric", length = nrow(query))
  time <- 30

  for(i in 1:nrow(query)) {
    prediction[i] <- predictSurvProb(model, newdata = query[i, ], times = query[i, "time"] + time)
  }
  prediction
}

surv_preds(cox_model, lung)

Body:
An alternate route would be the by_row function from purrrlyr in addition to the packages in the question.

library(purrrlyr)

prediction <- lung %>%
  mutate(time = time + 30) %>%
  by_row(~predictSurvProb(cox_model, newdata = ., times = .$time)) %>%
  .$.out %>%
  unlist

It is more tidy while producing the same result, however, early runs of microbenchmark don't show an improvement in processing time.

microbenchmark

# Unit: seconds
#                        expr      min       lq    mean   median       uq      max neval
# surv_preds(cox_model, lung) 1.531631 1.561518 1.59431 1.574664 1.591117 2.157002   100
# (purrrlyr)                  1.841713 1.887438 1.921371 1.90474 1.92649  2.170205   100

This would have both solutions running over 24 hours on the hardware I'm using.
 Given this answer no longer seems to solve your problem and I am unfamiliar with parallel processing options I'm happy to delete this unless anyone finds value in keeping this here.


问:
How to split an string inside a multidimensional array in php
new to the stackoverflow community, so do be forgiving if I've done anything incorrect. As I'm an amateur in coding in php, I'm currently facing a difficulty in multi dimensional arrays.

Currently, I have this array being returned to me.

```<code>Array(
    [trialID] => 1
    [trialMixedArray] => 1,2,3,4,5,6
    [trialStatus] => active
    [trialAddedDate] => 2017-11-13 09:56:03
)
</code>```

How do I split the trialMixedArray and return it to the original array so that it becomes formatted to be like the following result:

```<code>Array(
    [trialID] => 1
    [trialMixedArray] => Array(
                               [0] => 1
                               [1] => 2
                               [2] => 3
                               [3] => 4
                               [4] => 5
                               [5] => 6
    [trialStatus] => active
    [trialAddedDate] => 2017-11-13 09:56:03
)
</code>```

Thanks for the help in advance! Cheers! :)

答:
Use explode function to split any string based on a key.

The syntax is explode('key',string);

Body:
new to the stackoverflow community, so do be forgiving if I've done anything incorrect. As I'm an amateur in coding in php, I'm currently facing a difficulty in multi dimensional arrays.

Currently, I have this array being returned to me.

Array(
    [trialID] => 1
    [trialMixedArray] => 1,2,3,4,5,6
    [trialStatus] => active
    [trialAddedDate] => 2017-11-13 09:56:03
)

How do I split the trialMixedArray and return it to the original array so that it becomes formatted to be like the following result:

Array(
    [trialID] => 1
    [trialMixedArray] => Array(
                               [0] => 1
                               [1] => 2
                               [2] => 3
                               [3] => 4
                               [4] => 5
                               [5] => 6
    [trialStatus] => active
    [trialAddedDate] => 2017-11-13 09:56:03
)

Thanks for the help in advance! Cheers! :)


问:
Twilio record voicemail after waiting
I am trying to implement a voicemail but for some reason it hangs up immediately after 10 seconds and doesn't play the message. So far I have

```<code>[HttpPost]
public ActionResult Connect(string phoneNumber, string called)
{
    var response = new VoiceResponse();

    var dial = new Dial(callerId: _credentials.PhoneNumber, timeout: 10);
    if (phoneNumber != null)
    {
        dial.Number(phoneNumber);
    }
    else
    {
        int agentId = 1;
        dial.Client("support_agent", statusCallback: Url.Action("Status", "Call", new { Area = "PhoneSystem", agentId }, Request.Url.Scheme));
    }
    response.Dial(dial);

    return TwiML(response);
}

[HttpPost]
public ActionResult Status(string agentId, string dialCallStatus, string callStatus)
{
    // Need to pass the agent so we know who is called
    if (dialCallStatus == "completed")
    {
        var emptyResponse = new XDocument(new XElement("Root", ""));
        return new TwiMLResult(emptyResponse);
    }

    var response = new VoiceResponse();

    response.Say(
        body: "We can't answer your call right now, please leave a message"
    );

    // Use <Record> to record the caller's message
    response.Record();

    // End the call with <Hangup>
    response.Hangup();

    return TwiML(response);
}
</code>```

It does get to the Status method I can confirm, but the voice is never played.

Edit. I have changed the code to this

```<code>[HttpPost]
public ActionResult Connect(string phoneNumber, string called)
{
    var response = new VoiceResponse();

    int agentId = 1;
    var action = Url.Action("Status", "Call", new { Area = "PhoneSystem",
      agentId }, Request.Url.Scheme);

    var dial = new Dial(callerId: _credentials.PhoneNumber, timeout: 10, action: new Uri(action));

    if (phoneNumber != null)
    {
        dial.Number(phoneNumber);
    }
    else
    {
        dial.Client("support_agent");
    }
    response.Dial(dial);

    return TwiML(response);
}
</code>```

答:
Twilio developer evangelist here.

The statusCallback on the <Client> is to be used to get asynchronous callbacks about the state of the call. It won't allow you to continue the call.

Instead, you should use an action attribute on the <Dial> to set what the call should do once the dialled call is complete.

Let me know if that helps at all.

Title: Twilio record voicemail after waiting

Body:
I am trying to implement a voicemail but for some reason it hangs up immediately after 10 seconds and doesn't play the message. So far I have

[HttpPost]
public ActionResult Connect(string phoneNumber, string called)
{
    var response = new VoiceResponse();

    var dial = new Dial(callerId: _credentials.PhoneNumber, timeout: 10);
    if (phoneNumber != null)
    {
        dial.Number(phoneNumber);
    }
    else
    {
        int agentId = 1;
        dial.Client("support_agent", statusCallback: Url.Action("Status", "Call", new { Area = "PhoneSystem", agentId }, Request.Url.Scheme));
    }
    response.Dial(dial);

    return TwiML(response);
}

[HttpPost]
public ActionResult Status(string agentId, string dialCallStatus, string callStatus)
{
    // Need to pass the agent so we know who is called
    if (dialCallStatus == "completed")
    {
        var emptyResponse = new XDocument(new XElement("Root", ""));
        return new TwiMLResult(emptyResponse);
    }

    var response = new VoiceResponse();

    response.Say(
        body: "We can't answer your call right now, please leave a message"
    );

    // Use <Record> to record the caller's message
    response.Record();

    // End the call with <Hangup>
    response.Hangup();

    return TwiML(response);
}

It does get to the Status method I can confirm, but the voice is never played.

Edit. I have changed the code to this

[HttpPost]
public ActionResult Connect(string phoneNumber, string called)
{
    var response = new VoiceResponse();

    int agentId = 1;
    var action = Url.Action("Status", "Call", new { Area = "PhoneSystem",
      agentId }, Request.Url.Scheme);

    var dial = new Dial(callerId: _credentials.PhoneNumber, timeout: 10, action: new Uri(action));

    if (phoneNumber != null)
    {
        dial.Number(phoneNumber);
    }
    else
    {
        dial.Client("support_agent");
    }
    response.Dial(dial);

    return TwiML(response);
}


问:
Convert dates to pd.to_datetime where month could be either a number or month name
I have a datatime data, their format is like 29062017 and 01AUG2017.
As you can see, the month is in the middle of data.

I want to convert this data to datetime, when I use pd.to_datetime, but it doesn't work.

Do you know a good way to solve this problem?

答:
I wanted to weigh in with some options

Setup

```<code>m = dict(
    JAN='01', FEB='02', MAR='03', APR='04',
    MAY='05', JUN='06', JUL='07', AUG='08',
    SEP='09', OCT='10', NOV='11', DEC='12'
)

m2 = m.copy()
m2.update({v: v for v in m.values()})

f = lambda x: m.get(x, x)
</code>```

Option 1

list comprehension

```<code>pd.Series(
    pd.to_datetime(
        [x[:2] + f(x[2:5]) + x[5:] for x in s.values.tolist()],
        format='%d%m%Y'),
    s.index)

0   2017-06-29
1   2017-08-01
dtype: datetime64[ns]
</code>```

Option 2

Create a dataframe

```<code>pd.to_datetime(
    pd.DataFrame(dict(
        day=s.str[:2],
        year=s.str[-4:],
        month=s.str[2:-4].map(m2)
    )))

0   2017-06-29
1   2017-08-01
dtype: datetime64[ns]
</code>```

Option 2B

Create a dataframe

```<code>pd.to_datetime(
    pd.DataFrame(dict(
        day=s.str[:2],
        year=s.str[-4:],
        month=s.str[2:-4].map(f)
    )))

0   2017-06-29
1   2017-08-01
dtype: datetime64[ns]
</code>```

Option 2C

Create a dataframe

I estimate this to be the quickest

```<code>pd.to_datetime(
    pd.DataFrame(dict(
        day=s.str[:2].astype(int),
        year=s.str[-4:].astype(int),
        month=s.str[2:-4].map(m2).astype(int)
    )))

0   2017-06-29
1   2017-08-01
dtype: datetime64[ns]
</code>```

Test

```<code>s = pd.Series(["29062017", "01AUG2017"] * 100000)

%timeit pd.to_datetime(s.replace(m, regex=True), format='%d%m%Y')
%timeit pd.to_datetime(s.str[:2] + s.str[2:5].replace(m) + s.str[5:], format='%d%m%Y')
%timeit pd.to_datetime(s.str[:2] + s.str[2:5].map(f) + s.str[5:], format='%d%m%Y')
%timeit pd.to_datetime(s, format='%d%m%Y', errors='coerce').fillna(pd.to_datetime(s, format='%d%b%Y', errors='coerce'))
%timeit pd.Series(pd.to_datetime([x[:2] + f(x[2:5]) + x[5:] for x in s.values.tolist()], format='%d%m%Y'), s.index)
%timeit pd.to_datetime(pd.DataFrame(dict(day=s.str[:2], year=s.str[-4:], month=s.str[2:-4].map(m2))))
%timeit pd.to_datetime(pd.DataFrame(dict(day=s.str[:2], year=s.str[-4:], month=s.str[2:-4].map(f))))
%timeit pd.to_datetime(pd.DataFrame(dict(day=s.str[:2].astype(int), year=s.str[-4:].astype(int), month=s.str[2:-4].map(m2).astype(int))))

1.39 s ± 24 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
690 ms ± 17.2 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
613 ms ± 13.9 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
533 ms ± 14.2 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
529 ms ± 8.04 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
557 ms ± 13 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
607 ms ± 26.7 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
328 ms ± 31.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I wanted to weigh in with some options

Setup

m = dict(
    JAN='01', FEB='02', MAR='03', APR='04',
    MAY='05', JUN='06', JUL='07', AUG='08',
    SEP='09', OCT='10', NOV='11', DEC='12'
)

m2 = m.copy()
m2.update({v: v for v in m.values()})

f = lambda x: m.get(x, x)

Option 1

list comprehension

pd.Series(
    pd.to_datetime(
        [x[:2] + f(x[2:5]) + x[5:] for x in s.values.tolist()],
        format='%d%m%Y'),
    s.index)

0   2017-06-29
1   2017-08-01
dtype: datetime64[ns]

Option 2

Create a dataframe

pd.to_datetime(
    pd.DataFrame(dict(
        day=s.str[:2],
        year=s.str[-4:],
        month=s.str[2:-4].map(m2)
    )))

0   2017-06-29
1   2017-08-01
dtype: datetime64[ns]

Option 2B

Create a dataframe

pd.to_datetime(
    pd.DataFrame(dict(
        day=s.str[:2],
        year=s.str[-4:],
        month=s.str[2:-4].map(f)
    )))

0   2017-06-29
1   2017-08-01
dtype: datetime64[ns]

Option 2C

Create a dataframe

I estimate this to be the quickest

pd.to_datetime(
    pd.DataFrame(dict(
        day=s.str[:2].astype(int),
        year=s.str[-4:].astype(int),
        month=s.str[2:-4].map(m2).astype(int)
    )))

0   2017-06-29
1   2017-08-01
dtype: datetime64[ns]

Test

s = pd.Series(["29062017", "01AUG2017"] * 100000)

%timeit pd.to_datetime(s.replace(m, regex=True), format='%d%m%Y')
%timeit pd.to_datetime(s.str[:2] + s.str[2:5].replace(m) + s.str[5:], format='%d%m%Y')
%timeit pd.to_datetime(s.str[:2] + s.str[2:5].map(f) + s.str[5:], format='%d%m%Y')
%timeit pd.to_datetime(s, format='%d%m%Y', errors='coerce').fillna(pd.to_datetime(s, format='%d%b%Y', errors='coerce'))
%timeit pd.Series(pd.to_datetime([x[:2] + f(x[2:5]) + x[5:] for x in s.values.tolist()], format='%d%m%Y'), s.index)
%timeit pd.to_datetime(pd.DataFrame(dict(day=s.str[:2], year=s.str[-4:], month=s.str[2:-4].map(m2))))
%timeit pd.to_datetime(pd.DataFrame(dict(day=s.str[:2], year=s.str[-4:], month=s.str[2:-4].map(f))))
%timeit pd.to_datetime(pd.DataFrame(dict(day=s.str[:2].astype(int), year=s.str[-4:].astype(int), month=s.str[2:-4].map(m2).astype(int))))

1.39 s ± 24 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
690 ms ± 17.2 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
613 ms ± 13.9 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
533 ms ± 14.2 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
529 ms ± 8.04 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
557 ms ± 13 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
607 ms ± 26.7 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
328 ms ± 31.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)


问:
Git : fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists
I am getting this error -

```<code>D:\Projects\wamp\www\REPO [master]> git pull origin master
Warning: Permanently added 'github.com,192.30.252.128' (RSA) to the list of known hosts.
ERROR: Repository not found.
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.
</code>```

The output of git remote -v

```<code>D:\Projects\wamp\www\REPO [master]> git remote -v
origin  git@github.com:username/repo.git (fetch)
origin  git@github.com:username/repo.git (push)
</code>```

Final message of ssh -Tv git@github.com command -

```<code>Hi [My Username]! You've successfully authenticated, but GitHub does not provide shell access.
</code>```

How can I solve it?

答:
This error can be because of no SSH key on the your local machine. Check the SSH key locally:

```<code>$ cat ~/.ssh/id_rsa.pub
</code>```

If above command do not give any output use below command to create ssh key(Linux/Mac):

```<code>$ ssh-keygen
</code>```

Now again run cat ~/.ssh/id_rsa.pub This is your SSH key. Copy and add this key to your SSH keys in on git.
In gitlab/bitbucket go to

```<code>profile settings -> SSH Keys -> add Key
</code>```

and add the key

Body:
I am getting this error -

D:\Projects\wamp\www\REPO [master]> git pull origin master
Warning: Permanently added 'github.com,192.30.252.128' (RSA) to the list of known hosts.
ERROR: Repository not found.
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

The output of git remote -v

D:\Projects\wamp\www\REPO [master]> git remote -v
origin  git@github.com:username/repo.git (fetch)
origin  git@github.com:username/repo.git (push)

Final message of ssh -Tv git@github.com command -

Hi [My Username]! You've successfully authenticated, but GitHub does not provide shell access.

How can I solve it?

Body:
This error can be because of no SSH key on the your local machine. Check the SSH key locally:

$ cat ~/.ssh/id_rsa.pub

If above command do not give any output use below command to create ssh key(Linux/Mac):

$ ssh-keygen

Now again run cat ~/.ssh/id_rsa.pub This is your SSH key. Copy and add this key to your SSH keys in on git.
In gitlab/bitbucket go to

profile settings -> SSH Keys -> add Key

and add the key


问:
how to delete a consumer group C belonging to topic T when using the new consumer API
the newer versions of apache kafka store the consumer group data internally instead of using zookeeper

which means that the command-line utility kafka-consumer-groups is not useful since the related info is not stored in zookeeper now

could you please advise:

how to delete a consumer group C belonging to topic T when using the new consumer API

?

答:
If none of the members of the consumer group commit offsets for 24 hours (with default settings) it will expire and be deleted automatically.

Alternatively you can reset the offsets or set them to any value you want using the new --reset-offsets option to bin/kafka-consumer-groups

See Kafka 0.11 how to reset offsets


问:
jQuery - some beginner questions
I'm a very beginner to jQuery, and I'm having some basic questions:

Is it advisable to use jQuery whenever it is possible to replace something by using it? For example, is it prudent to bind all events to elements using it, instead of through HTML?

Is it better to host the jQuery .js file and all other relevant files (like JQuery UI) myself, or is it perhaps a better choice to use Google's link (they seem to host it for others too)?

When it comes to executing a script when the page is done loading, what way is preferred?

$(document).ready(function() {})

$(function() {})

$().ready(function() {})

They seem to all do the same thing, but what is the preferred way of scripting?

答:
I personally don't subscribe to the "cleanly separate JS from HTML" philosophy.  I rarely see real world use cases where that has any benefit.  Separating HTML from JS often leads to buttons that say "click here to do X" in the HTML but do nothing unless the appropriate javascript is with them.  Kind of misses the point.
With the case of jQuery and events... I find it much easier to debug an app if I can inspect an HTML button in firebug and see what that button does (by looking at the onclick attribute).

Using the google version can aid with caching, but don't link directly to jquery.com.  We did that here once and they went down, took us with them.

Title: jQuery - some beginner questions


问:
ProcessBuilder prints an empty output after do while loop
I am using ProcessBuilder to open a text file in Notepad window and to open another Notepad window with the processed text according to my code.

What is happening right now is that program opens 1st notepad window
  with a text I put in it but 2nd windows comes up empty.

Would anyone suggest where do I need to make changes to have processed text printed in 2nd notepad window? (I included the output below the code). I have the right result printed in the console but not in the notepad window. I have never used ProcessBuilder  before and could find only simple examples of how to use it. Appreciate your advice.

```<code>Scanner in = new Scanner(System.in);
    System.out.print("Enter the input file: ");
    String inputFileName = in.next();
    System.out.print("Enter the output file: ");
    String outputFileName = in.next();

    String poemFilename = "poem.txt";
    String poemoutFilenamo = "newpoem";
    int lineNum = 1;

    File poemFile = new File(poemFilename);
    Scanner fileIn = new Scanner(poemFile);
    PrintWriter fileout = new PrintWriter(poemoutFilenamo);

    System.out.printf("Read in %s.\nWrote out %s.\n",inputFileName, outputFileName );

    ProcessBuilder Poemin = new ProcessBuilder("Notepad.exe", poemFilename);
    Poemin.start();

    if (fileIn.hasNextLine()) {
        do {
            String line = fileIn.nextLine();
            System.out.printf("/*" + lineNum + "*/ %s\n", line);
            lineNum++;
        } while (fileIn.hasNextLine());;

        ProcessBuilder Poemout = new ProcessBuilder("Notepad.exe", poemoutFilenamo);
        Poemout.start();
    }

    in.close();
    fileIn.close();
    fileout.close();
</code>```

Should print out in Notepad window this:

```<code>/*1*/ Somewhere over the rainbow
/*2*/ Way up high
/*3*/ And the dreams that you dreamed of
/*4*/ Once in a lullaby
</code>```

答:
You never write anything to fileout.  You created the file but it is empty.

I believe you want

```<code>fileout.printf("/*" + lineNum + "*/ %s\n", line);
</code>```

And also you need to close fileout before launching the second process.

Body:
I am using ProcessBuilder to open a text file in Notepad window and to open another Notepad window with the processed text according to my code.

What is happening right now is that program opens 1st notepad window
  with a text I put in it but 2nd windows comes up empty.

Would anyone suggest where do I need to make changes to have processed text printed in 2nd notepad window? (I included the output below the code). I have the right result printed in the console but not in the notepad window. I have never used ProcessBuilder  before and could find only simple examples of how to use it. Appreciate your advice.

Scanner in = new Scanner(System.in);
    System.out.print("Enter the input file: ");
    String inputFileName = in.next();
    System.out.print("Enter the output file: ");
    String outputFileName = in.next();

    String poemFilename = "poem.txt";
    String poemoutFilenamo = "newpoem";
    int lineNum = 1;

    File poemFile = new File(poemFilename);
    Scanner fileIn = new Scanner(poemFile);
    PrintWriter fileout = new PrintWriter(poemoutFilenamo);

    System.out.printf("Read in %s.\nWrote out %s.\n",inputFileName, outputFileName );

    ProcessBuilder Poemin = new ProcessBuilder("Notepad.exe", poemFilename);
    Poemin.start();

    if (fileIn.hasNextLine()) {
        do {
            String line = fileIn.nextLine();
            System.out.printf("/*" + lineNum + "*/ %s\n", line);
            lineNum++;
        } while (fileIn.hasNextLine());;

        ProcessBuilder Poemout = new ProcessBuilder("Notepad.exe", poemoutFilenamo);
        Poemout.start();
    }

    in.close();
    fileIn.close();
    fileout.close();

Should print out in Notepad window this:

/*1*/ Somewhere over the rainbow
/*2*/ Way up high
/*3*/ And the dreams that you dreamed of
/*4*/ Once in a lullaby

Body:
You never write anything to fileout.  You created the file but it is empty.

I believe you want

fileout.printf("/*" + lineNum + "*/ %s\n", line);

And also you need to close fileout before launching the second process.


问:
How to download images from url in xml value using php?
I have to download images from url in an xml code and save it to a folder. Is there a way that I can do that? And, if I updated one of the picture, and I want to download it again, what should I do so that images that I download only the one that get updated (only the newest version is downloaded), if an image is not updated it won't be downloaded again. Thank you for your help!
the xml example is this:</p>

```<code><item>
<g:main_image_url>https://www.dropbox.com/s/3tsncqxysqdyz1v/whitebag.jpg?dl=0</g:main_image_url>
</item>
<item>
<g:main_image_url>https://www.dropbox.com/s/vwks0iatjut2om4/whiteblackbag.jpg?dl=0</g:main_image_url>
</item>
</code>```

答:
I've come up with the answer, and the code is like this</p>

```<code><?php
ini_set('max_execution_time', 300);
$doc = simplexml_load_file('xml_file.xml');
foreach ( $doc->xpath("//item") as $item )  {
    $name = $item->productname;
    $url = $item->thumbnail_url;
    $img = 'path/to/file/'.$name.'.png';
    file_put_contents($img, file_get_contents($url));
}

?>
</code>```

Body:
I have to download images from url in an xml code and save it to a folder. Is there a way that I can do that? And, if I updated one of the picture, and I want to download it again, what should I do so that images that I download only the one that get updated (only the newest version is downloaded), if an image is not updated it won't be downloaded again. Thank you for your help!
the xml example is this:

<item>
<g:main_image_url>https://www.dropbox.com/s/3tsncqxysqdyz1v/whitebag.jpg?dl=0</g:main_image_url>
</item>
<item>
<g:main_image_url>https://www.dropbox.com/s/vwks0iatjut2om4/whiteblackbag.jpg?dl=0</g:main_image_url>
</item>

Body:
I've come up with the answer, and the code is like this

<?php
ini_set('max_execution_time', 300);
$doc = simplexml_load_file('xml_file.xml');
foreach ( $doc->xpath("//item") as $item )  {
    $name = $item->productname;
    $url = $item->thumbnail_url;
    $img = 'path/to/file/'.$name.'.png';
    file_put_contents($img, file_get_contents($url));
}

?>


问:
How do I find the value of a checkbox from a gridview in asp/c#
I have had the most trouble with finding the value of a checkbox. I have searched everywhere and I can't seem to get it to the right value, nothing comes up or I get a NULL reference error. I have checked the other threads/posts and none seem to work.

All I'm trying to do is get the value of a checkbox, but I can't seem to do that.

The information is coming from a database. I can grab the string value but I can't grab the checkbox value.

Anyways, this is the code I used to get ahold of the string value and checkbox value:

```<code>//String grabber
Convert.ToString(gvOrders.SelectedRow.Cells[2].Text);

//Checkbox grabber
Boolean.TryParse(gvOrders.SelectedRow.Cells[11].Text, out bool pep);
</code>```

or

```<code>//Checkbox grabber
Convert.ToBoolean(gvOrders.SelectedRow.Cells[2].Text);
</code>```

Anyways, please no negativity, I've been struggling to find the value and it just isn't working.

Thanks in advance.

EDIT:

ADDED CODE:

```<code>using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Convert.ToString(Session["username"]) != "Scott" || Convert.ToString(Session["perms"]) != "admin")
        {
            Response.Redirect("Default.aspx");
        }
        GuestOrderInfo temp = new GuestOrderInfo();
        gvOrders.DataSource = temp.SearchAll();
        gvOrders.DataBind();
    }

    protected void osicOrders(object sender, EventArgs e)
    {
        Int16 row = Convert.ToInt16(gvOrders.SelectedRow.Cells[1].Text);
        Session["row"] = row;
        //Convert to a session to use in a different function.
        Session["fName"] = Convert.ToString(gvOrders.SelectedRow.Cells[2].Text);
        Session["lName"] = Convert.ToString(gvOrders.SelectedRow.Cells[3].Text);
        Session["street"] = Convert.ToString(gvOrders.SelectedRow.Cells[4].Text);
        Session["street2"] = Convert.ToString(gvOrders.SelectedRow.Cells[5].Text);
        Session["city"] = Convert.ToString(gvOrders.SelectedRow.Cells[6].Text);
        Session["state"] = Convert.ToString(gvOrders.SelectedRow.Cells[7].Text);
        Session["zip"] = Convert.ToString(gvOrders.SelectedRow.Cells[8].Text);
        Session["price"] = Convert.ToDouble(gvOrders.SelectedRow.Cells[9].Text);
        Session["size"] = Convert.ToString(gvOrders.SelectedRow.Cells[10].Text);

        Session["pepperoni"] = Boolean.TryParse(gvOrders.SelectedRow.Cells[11].Text, out bool pep);
        Session["sausage"] = Boolean.TryParse(gvOrders.SelectedRow.Cells[12].Text, out bool sau);
        Session["meatball"] = Boolean.TryParse(gvOrders.SelectedRow.Cells[13].Text, out bool mea);
        Session["ham"] = Boolean.TryParse(gvOrders.SelectedRow.Cells[14].Text, out bool hamm);
        Session["peppers"] = Boolean.TryParse(gvOrders.SelectedRow.Cells[15].Text, out bool pepp);
        Session["onions"] = Boolean.TryParse(gvOrders.SelectedRow.Cells[16].Text, out bool onio);
        Session["spinach"] = Boolean.TryParse(gvOrders.SelectedRow.Cells[17].Text, out bool spin);
        Session["pineapple"] = Boolean.TryParse(gvOrders.SelectedRow.Cells[18].Text, out bool pine);
        Session["bbq"] = Boolean.TryParse(gvOrders.SelectedRow.Cells[19].Text, out bool bbqq);
        Session["xcheese"] = Boolean.TryParse(gvOrders.SelectedRow.Cells[20].Text, out bool xch);

        //
        //
        //FIND OUT HOW TO GET THE VALUE OF A CHECKBOX IN GV AND USE THAT VALUE WITHIN SESSION VARIABLES TO UPDATE DATA IN THE UPDATE PAGE THEN MAKE A SEARCH PAGS
        //
        //
        CheckBox cb = (CheckBox)gvOrders.SelectedRow.Cells[11].FindControl("pepperoni");

        selectedID.Text = "Selected: " + Convert.ToString(row);
        selectedInformation.Text = Session["fName"] + " " + Session["lName"] + " Pepp = " + cb.Checked;
        edit.Visible = true;
        delete.Visible = true;
        selectedInformation.Visible = true;
        cancel.Visible = true;
    }

    protected void delete_OnClick(object sender, EventArgs e)
    {
        string buttonText = (sender as LinkButton).Text;

        if (buttonText == "Delete")
        {
            edit.Visible = false;
            delete.Visible = false;
            yes.Visible = true;
            no.Visible = true;
            sure.Visible = true;

        }
        if (buttonText == "Edit")
        {
            Response.Redirect("editOrders.aspx");
        }
        if (buttonText == "Yes")
        {
            GuestOrderInfo temp = new GuestOrderInfo();

            temp.DeleteARecord(Convert.ToInt16(Session["row"]));
            Session.Remove("row");
            Response.Redirect("viewOrders.aspx");
        }
        if (buttonText == "No")
        {
            edit.Visible = true;
            delete.Visible = true;
            yes.Visible = false;
            no.Visible = false;
            sure.Visible = false;
        }
        if (buttonText == "Cancel")
        {
            Response.Redirect("viewOrders.aspx");

        }

    }
}
</code>```

ORIGINAL HTML:

```<code><%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="viewOrders.aspx.cs" Inherits="Default2" %>

<asp:Content ID="Content1" ContentPlaceHolderID="title" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="BodyContent" Runat="Server">
    <asp:GridView ID="gvOrders" runat="server" OnSelectedIndexChanged="osicOrders" AutoGenerateSelectButton="True" >
    </asp:GridView>
    <asp:Label runat="server" ID="selectedID"></asp:Label>
    <asp:Label runat="server" ID="selectedInformation" Visible="False"/>
    <asp:LinkButton runat="server" ID="edit" Text="Edit" OnClick="delete_OnClick" Visible="False"/>  <asp:LinkButton runat="server" ID="delete" Text="Delete" Visible="False" OnClick="delete_OnClick"/><asp:LinkButton runat="server" ID="cancel" Text="Cancel" Visible="False" OnClick="delete_OnClick"/><br/>
    <asp:Label runat="server" Text="Are you sure you want to do this?" ID="sure" Visible="False"></asp:Label><br/>

    <asp:LinkButton runat="server" Visible="False" ID="no" Text="No" OnClick="delete_OnClick"/> <asp:LinkButton runat="server" Visible="False" ID="yes" Text="Yes" OnClick="delete_OnClick"/>

    <!-- Make the edit button work along with the delete -->
    <!-- Data validation, design and submit  :^) -->
</asp:Content>
</code>```

答:
If you are using a CheckBoxField in your grid view as below, then the code for getting checkbox value is as given in second code snippet.

Checkbox column markup in GridView

```<code> <asp:CheckBoxField DataField="Discontinued" HeaderText="Discontinued"
         SortExpression="Discontinued" />
</code>```

Getting the checkbox value in code-behind

```<code>bool isChecked = (gvOrders.SelectedRow.Cells[11].Controls[0] as CheckBox).Checked;
</code>```

However, if you are using a template column in your gridview, then you need to follow  different approach that is explained below.
In your code-behind,

you need to first get the gridview's data row

and then find the checkbox control using the ID of the checkbox
control you specified in your html markup, which is CheckBox1 in
code sample below ( you don't need to bother about getting the cell containing checkbox in this case)

Templated Checkbox Column

```<code><asp:TemplateField HeaderText="CheckBox Column">
<ItemTemplate>
    <asp:CheckBox ID="CheckBox1" runat="server" Checked='<%# Eval("Discontinued") %>'  />
</ItemTemplate>
</code>```

Getting the checkbox value in code-behind

```<code>bool isChecked = (gvOrders.SelectedRow.FindControl("CheckBox1") as CheckBox).Checked;
</code>```

Body:
I have had the most trouble with finding the value of a checkbox. I have searched everywhere and I can't seem to get it to the right value, nothing comes up or I get a NULL reference error. I have checked the other threads/posts and none seem to work.

All I'm trying to do is get the value of a checkbox, but I can't seem to do that.

The information is coming from a database. I can grab the string value but I can't grab the checkbox value.

Anyways, this is the code I used to get ahold of the string value and checkbox value:

//String grabber
Convert.ToString(gvOrders.SelectedRow.Cells[2].Text);

//Checkbox grabber
Boolean.TryParse(gvOrders.SelectedRow.Cells[11].Text, out bool pep);

or

//Checkbox grabber
Convert.ToBoolean(gvOrders.SelectedRow.Cells[2].Text);

Anyways, please no negativity, I've been struggling to find the value and it just isn't working.

Thanks in advance.

EDIT:

ADDED CODE:

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Convert.ToString(Session["username"]) != "Scott" || Convert.ToString(Session["perms"]) != "admin")
        {
            Response.Redirect("Default.aspx");
        }
        GuestOrderInfo temp = new GuestOrderInfo();
        gvOrders.DataSource = temp.SearchAll();
        gvOrders.DataBind();
    }

    protected void osicOrders(object sender, EventArgs e)
    {
        Int16 row = Convert.ToInt16(gvOrders.SelectedRow.Cells[1].Text);
        Session["row"] = row;
        //Convert to a session to use in a different function.
        Session["fName"] = Convert.ToString(gvOrders.SelectedRow.Cells[2].Text);
        Session["lName"] = Convert.ToString(gvOrders.SelectedRow.Cells[3].Text);
        Session["street"] = Convert.ToString(gvOrders.SelectedRow.Cells[4].Text);
        Session["street2"] = Convert.ToString(gvOrders.SelectedRow.Cells[5].Text);
        Session["city"] = Convert.ToString(gvOrders.SelectedRow.Cells[6].Text);
        Session["state"] = Convert.ToString(gvOrders.SelectedRow.Cells[7].Text);
        Session["zip"] = Convert.ToString(gvOrders.SelectedRow.Cells[8].Text);
        Session["price"] = Convert.ToDouble(gvOrders.SelectedRow.Cells[9].Text);
        Session["size"] = Convert.ToString(gvOrders.SelectedRow.Cells[10].Text);

        Session["pepperoni"] = Boolean.TryParse(gvOrders.SelectedRow.Cells[11].Text, out bool pep);
        Session["sausage"] = Boolean.TryParse(gvOrders.SelectedRow.Cells[12].Text, out bool sau);
        Session["meatball"] = Boolean.TryParse(gvOrders.SelectedRow.Cells[13].Text, out bool mea);
        Session["ham"] = Boolean.TryParse(gvOrders.SelectedRow.Cells[14].Text, out bool hamm);
        Session["peppers"] = Boolean.TryParse(gvOrders.SelectedRow.Cells[15].Text, out bool pepp);
        Session["onions"] = Boolean.TryParse(gvOrders.SelectedRow.Cells[16].Text, out bool onio);
        Session["spinach"] = Boolean.TryParse(gvOrders.SelectedRow.Cells[17].Text, out bool spin);
        Session["pineapple"] = Boolean.TryParse(gvOrders.SelectedRow.Cells[18].Text, out bool pine);
        Session["bbq"] = Boolean.TryParse(gvOrders.SelectedRow.Cells[19].Text, out bool bbqq);
        Session["xcheese"] = Boolean.TryParse(gvOrders.SelectedRow.Cells[20].Text, out bool xch);

        //
        //
        //FIND OUT HOW TO GET THE VALUE OF A CHECKBOX IN GV AND USE THAT VALUE WITHIN SESSION VARIABLES TO UPDATE DATA IN THE UPDATE PAGE THEN MAKE A SEARCH PAGS
        //
        //
        CheckBox cb = (CheckBox)gvOrders.SelectedRow.Cells[11].FindControl("pepperoni");

        selectedID.Text = "Selected: " + Convert.ToString(row);
        selectedInformation.Text = Session["fName"] + " " + Session["lName"] + " Pepp = " + cb.Checked;
        edit.Visible = true;
        delete.Visible = true;
        selectedInformation.Visible = true;
        cancel.Visible = true;
    }

    protected void delete_OnClick(object sender, EventArgs e)
    {
        string buttonText = (sender as LinkButton).Text;

        if (buttonText == "Delete")
        {
            edit.Visible = false;
            delete.Visible = false;
            yes.Visible = true;
            no.Visible = true;
            sure.Visible = true;

        }
        if (buttonText == "Edit")
        {
            Response.Redirect("editOrders.aspx");
        }
        if (buttonText == "Yes")
        {
            GuestOrderInfo temp = new GuestOrderInfo();

            temp.DeleteARecord(Convert.ToInt16(Session["row"]));
            Session.Remove("row");
            Response.Redirect("viewOrders.aspx");
        }
        if (buttonText == "No")
        {
            edit.Visible = true;
            delete.Visible = true;
            yes.Visible = false;
            no.Visible = false;
            sure.Visible = false;
        }
        if (buttonText == "Cancel")
        {
            Response.Redirect("viewOrders.aspx");

        }

    }
}

ORIGINAL HTML:

<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="viewOrders.aspx.cs" Inherits="Default2" %>

<asp:Content ID="Content1" ContentPlaceHolderID="title" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="BodyContent" Runat="Server">
    <asp:GridView ID="gvOrders" runat="server" OnSelectedIndexChanged="osicOrders" AutoGenerateSelectButton="True" >
    </asp:GridView>
    <asp:Label runat="server" ID="selectedID"></asp:Label>
    <asp:Label runat="server" ID="selectedInformation" Visible="False"/>
    <asp:LinkButton runat="server" ID="edit" Text="Edit" OnClick="delete_OnClick" Visible="False"/>  <asp:LinkButton runat="server" ID="delete" Text="Delete" Visible="False" OnClick="delete_OnClick"/><asp:LinkButton runat="server" ID="cancel" Text="Cancel" Visible="False" OnClick="delete_OnClick"/>

    <asp:Label runat="server" Text="Are you sure you want to do this?" ID="sure" Visible="False"></asp:Label>

    <asp:LinkButton runat="server" Visible="False" ID="no" Text="No" OnClick="delete_OnClick"/> <asp:LinkButton runat="server" Visible="False" ID="yes" Text="Yes" OnClick="delete_OnClick"/>

</asp:Content>

Body:
If you are using a CheckBoxField in your grid view as below, then the code for getting checkbox value is as given in second code snippet.

Checkbox column markup in GridView

 <asp:CheckBoxField DataField="Discontinued" HeaderText="Discontinued"
         SortExpression="Discontinued" />

Getting the checkbox value in code-behind

bool isChecked = (gvOrders.SelectedRow.Cells[11].Controls[0] as CheckBox).Checked;

However, if you are using a template column in your gridview, then you need to follow  different approach that is explained below.
In your code-behind,

you need to first get the gridview's data row

and then find the checkbox control using the ID of the checkbox
control you specified in your html markup, which is CheckBox1 in
code sample below ( you don't need to bother about getting the cell containing checkbox in this case)

Templated Checkbox Column

<asp:TemplateField HeaderText="CheckBox Column">
<ItemTemplate>
    <asp:CheckBox ID="CheckBox1" runat="server" Checked='<%# Eval("Discontinued") %>'  />
</ItemTemplate>

Getting the checkbox value in code-behind

bool isChecked = (gvOrders.SelectedRow.FindControl("CheckBox1") as CheckBox).Checked;


问:
C# How to sort int when value is too large
```<code>8
723
77715926535897932384626433832795
</code>```

Usually I will place them into Array and using Sort method to sort them numerically.

However, the above value is too huge to be place into Int64 and if using string array, its gonna give unexpected outcome which 8 comes after 77715926535897932384626433832795. How to sort such large value?

答:
In such cases sorting can be done in two steps.

1.Sort based on length of the string. (Remove any leading Zeros).

2.Sort the strings after that.

```<code>string[] numbers = { "9", "33", "11", "22", "723", "8", "77715926535897932384626433832795" };
Array.Sort(numbers, (x, y) =>
            {
                int val = x.Length - y.Length;
                if (val == 0)
                {
                    val = x.CompareTo(y);
                }
                return val;
            });
</code>```

Output:

```<code>"8"
"9"
"11"
"22"
"33"
"723"
"909"
"77715926535897932384626433832795"
</code>```

Body:
8
723
77715926535897932384626433832795

Usually I will place them into Array and using Sort method to sort them numerically.

However, the above value is too huge to be place into Int64 and if using string array, its gonna give unexpected outcome which 8 comes after 77715926535897932384626433832795. How to sort such large value?

Body:
In such cases sorting can be done in two steps.

1.Sort based on length of the string. (Remove any leading Zeros).

2.Sort the strings after that.

string[] numbers = { "9", "33", "11", "22", "723", "8", "77715926535897932384626433832795" };
Array.Sort(numbers, (x, y) =>
            {
                int val = x.Length - y.Length;
                if (val == 0)
                {
                    val = x.CompareTo(y);
                }
                return val;
            });

Output:

"8"
"9"
"11"
"22"
"33"
"723"
"909"
"77715926535897932384626433832795"


问:
How to get value from RecycleAdapter and set to MainActivity Text?
My Adapter Code looks like :

```<code>    @Override
    public void onBindViewHolder(final ViewHolder holder, final int position) {
        GetSet getSet = allData.get(position);
        holder.tvId.setText(getSet.getId().toString());
        holder.tvName.setText(getSet.getName());

    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

        @BindView(R.id.tvId)
        TextView tvId;

        @BindView(R.id.tvName)
        TextView tvName;
</code>```

I have textview in MainActivity, my question is how to get value/text id and name to set in textview?

答:
One more thing, you can use an api of recycler view to retrieve view holder item:</p>

```<code>findViewHolderForAdapterPosition(position)
</code>```

Body:
My Adapter Code looks like :

    @Override
    public void onBindViewHolder(final ViewHolder holder, final int position) {
        GetSet getSet = allData.get(position);
        holder.tvId.setText(getSet.getId().toString());
        holder.tvName.setText(getSet.getName());

    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

        @BindView(R.id.tvId)
        TextView tvId;

        @BindView(R.id.tvName)
        TextView tvName;

I have textview in MainActivity, my question is how to get value/text id and name to set in textview?

Body:
One more thing, you can use an api of recycler view to retrieve view holder item:

findViewHolderForAdapterPosition(position)


问:
Project Conversion - iPad to iPhone
So I am trying to convert an iPad project to an iPhone project.  This is backwards from what most people are doing, and I was wondering if there was an easy way to do this, or will I have to rebuild/redesign all my views myself.

It wouldn't be that big of a deal to redesign the interface, but naturally, if there was an easier way, I would love to explore it.  Any suggestions?

答: There are lots of guides that explain the opposite (iPhone -> iPad) and they will also help you here since the steps and problems are basically the same. You will end up with files that can be shared and files that you need in an iPhone and iPad version.</p>

Title: Project Conversion - iPad to iPhone


问:
How to Avoid Response.End() "Thread was being aborted" Exception during the Excel file download
I tried to convert my dataset into excel and  download that excel .I got my required excel file.But System.Threading.ThreadAbortException was raised every excel download.
How to resolve this issue ?..
Please help me...

I call this method in my aspx screen.There also same exception has thrown by this method.

I call that public void ExportDataSet(DataSet ds) function in many aspx screens and also I am maintaining  error logger method  for exceptions which are raised at runtime right those  exceptions are write  into  a .txt files. So that same exception  is logged in all the  aspx  screen's txt files.I just want to avoid this exception  throws from method declared class file to aspx. Simply i just want to handle this exception at my method declaration  class file itself.

ASPX File Method call:
 excel.ExportDataSet(dsExcel);

Method Definition:

```<code>public void ExportDataSet(DataSet ds)
{

   try
   {
      string filename = "ExcelFile.xls";
      HttpResponse response = HttpContext.Current.Response;
      response.Clear();
      response.Charset = "";
      response.ContentType = "application/vnd.ms-excel";
      response.AddHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
      using (StringWriter sw = new StringWriter())
      {
         using (HtmlTextWriter htw = new HtmlTextWriter(sw))
         {
             GridView dg = new GridView();
             dg.DataSource = ds.Tables[0];
             dg.DataBind();
             dg.RenderControl(htw);
             // response.Write(style);
             response.Write(sw.ToString());
             response.End();                    // Exception was Raised at here
         }
      }
   }
   catch (Exception ex)
   {
      string Err = ex.Message.ToString();
      EsHelper.EsADLogger("HOQCMgmt.aspx ibtnExcelAll_Click()", ex.Message.ToString());
   }
   finally
   {
   }
}
</code>```

答:
I used all above changes but still I was getting same issue on my web application.

Then I contacted my hosting provide & asked them to check if any software or antivirus blocking our files to transfer via HTTP. or ISP/network is not allowing file to transfer.

They checked server settings & bypass the "Data Center Shared Firewall" for my server & now our application is able to download the file.

Hope this answer will help someone.This is what worked for me

Body:
I tried to convert my dataset into excel and  download that excel .I got my required excel file.But System.Threading.ThreadAbortException was raised every excel download.
How to resolve this issue ?..
Please help me...

I call this method in my aspx screen.There also same exception has thrown by this method.

I call that public void ExportDataSet(DataSet ds) function in many aspx screens and also I am maintaining  error logger method  for exceptions which are raised at runtime right those  exceptions are write  into  a .txt files. So that same exception  is logged in all the  aspx  screen's txt files.I just want to avoid this exception  throws from method declared class file to aspx. Simply i just want to handle this exception at my method declaration  class file itself.

ASPX File Method call:
 excel.ExportDataSet(dsExcel);

Method Definition:

public void ExportDataSet(DataSet ds)
{

   try
   {
      string filename = "ExcelFile.xls";
      HttpResponse response = HttpContext.Current.Response;
      response.Clear();
      response.Charset = "";
      response.ContentType = "application/vnd.ms-excel";
      response.AddHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
      using (StringWriter sw = new StringWriter())
      {
         using (HtmlTextWriter htw = new HtmlTextWriter(sw))
         {
             GridView dg = new GridView();
             dg.DataSource = ds.Tables[0];
             dg.DataBind();
             dg.RenderControl(htw);
             // response.Write(style);
             response.Write(sw.ToString());
             response.End();                    // Exception was Raised at here
         }
      }
   }
   catch (Exception ex)
   {
      string Err = ex.Message.ToString();
      EsHelper.EsADLogger("HOQCMgmt.aspx ibtnExcelAll_Click()", ex.Message.ToString());
   }
   finally
   {
   }
}