问:
iOS: How to get a proper Month name from a number?
I know that the NSDateformatter suite of functionality is a boon for mankind, but at the same time it is very confusing to me. I hope you can help me out.

Somewhere in my code, there is an int representing a month. So: 1 would be January, 2 February, etc.

In my user interface, I would like to display this integer as proper month name. Moreover, it should adhere to the locale of the device.

Thank you for your insights

In the mean time, I have done the following:

```<code>int monthNumber = 11
NSString * dateString = [NSString stringWithFormat: @"%d", monthNumber];

NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MM"];
NSDate* myDate = [dateFormatter dateFromString:dateString];
[dateFormatter release];

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"MMMM"];
NSString *stringFromDate = [formatter stringFromDate:myDate];
[formatter release];
</code>```

is this the way to do it? It seems a bit wordy.

答:
How about:</p>

```<code>NSUInteger i = <your month integer>;
NSDateFormatter *df = [NSDateFormatter new];
// change locale if the standard is not what you want
NSArray *monthNames = [df standaloneMonthSymbols];
NSString *monthName = [monthNames objectAtIndex:(i - 1)];
[df release];
</code>```

Body:
I know that the NSDateformatter suite of functionality is a boon for mankind, but at the same time it is very confusing to me. I hope you can help me out.

Somewhere in my code, there is an int representing a month. So: 1 would be January, 2 February, etc.

In my user interface, I would like to display this integer as proper month name. Moreover, it should adhere to the locale of the device.

Thank you for your insights

In the mean time, I have done the following:

int monthNumber = 11
NSString * dateString = [NSString stringWithFormat: @"%d", monthNumber];

NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MM"];
NSDate* myDate = [dateFormatter dateFromString:dateString];
[dateFormatter release];

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"MMMM"];
NSString *stringFromDate = [formatter stringFromDate:myDate];
[formatter release];

is this the way to do it? It seems a bit wordy.

Body:
How about:

NSUInteger i = <your month integer>;
NSDateFormatter *df = [NSDateFormatter new];
// change locale if the standard is not what you want
NSArray *monthNames = [df standaloneMonthSymbols];
NSString *monthName = [monthNames objectAtIndex:(i - 1)];
[df release];


来源: stackexchange

问:
Selenium with Crome and Maven not works. ClassNotFoundException: org.apache.http.auth.Credentials
I want to run headless Chrome with Selenium, but this code not works:

```<code>    ChromeOptions chromeOptions = new ChromeOptions();
    chromeOptions.addArguments("--headless");
    File file = new File("/usr/bin/chromedriver");
    System.setProperty("webdriver.chrome.driver", file.getAbsolutePath());
    WebDriver driver = new ChromeDriver(chromeOptions);
</code>```

It compiles fine, but at runtime crashes with stacktrace:

```<code>Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/http/auth/Credentials
    at org.openqa.selenium.remote.HttpCommandExecutor.getDefaultClientFactory(HttpCommandExecutor.java:93)
    at org.openqa.selenium.remote.HttpCommandExecutor.<init>(HttpCommandExecutor.java:72)
    at org.openqa.selenium.remote.service.DriverCommandExecutor.<init>(DriverCommandExecutor.java:62)
    at org.openqa.selenium.chrome.ChromeDriverCommandExecutor.<init>(ChromeDriverCommandExecutor.java:39)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:184)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:171)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:158)
    at org.chrome.automation.Starter.main(Starter.java:20)
Caused by: java.lang.ClassNotFoundException: org.apache.http.auth.Credentials
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 8 more
</code>```

The POM contains just two dependencies:

```<code>    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-chrome-driver</artifactId>
        <version>3.4.0</version>
    </dependency>
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>3.4.0</version>
    </dependency>
</code>```

I thought the problem in Selenium dependencies, as they are rely on some apache code but not download dependent components. I tried to add apache dependencies like:

```<code>    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.3</version>
    </dependency>

    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpcore</artifactId>
        <version>4.4.6</version>
    </dependency>
</code>```

But problem persists.

Please help to run selenium with headless Crome.

答:
I was able to resolve by using just one dependency:

```<code>    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-chrome-driver</artifactId>
        <version>2.53.1</version>
    </dependency>
</code>```

Also it works with 3.3.1, 3.2.0. As I see the problem happen in 3.4.0 version only.

ContentLicense: CC BY-SA 3.0

Body:
I want to run headless Chrome with Selenium, but this code not works:

    ChromeOptions chromeOptions = new ChromeOptions();
    chromeOptions.addArguments("--headless");
    File file = new File("/usr/bin/chromedriver");
    System.setProperty("webdriver.chrome.driver", file.getAbsolutePath());
    WebDriver driver = new ChromeDriver(chromeOptions);

It compiles fine, but at runtime crashes with stacktrace:

Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/http/auth/Credentials
    at org.openqa.selenium.remote.HttpCommandExecutor.getDefaultClientFactory(HttpCommandExecutor.java:93)
    at org.openqa.selenium.remote.HttpCommandExecutor.<init>(HttpCommandExecutor.java:72)
    at org.openqa.selenium.remote.service.DriverCommandExecutor.<init>(DriverCommandExecutor.java:62)
    at org.openqa.selenium.chrome.ChromeDriverCommandExecutor.<init>(ChromeDriverCommandExecutor.java:39)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:184)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:171)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:158)
    at org.chrome.automation.Starter.main(Starter.java:20)
Caused by: java.lang.ClassNotFoundException: org.apache.http.auth.Credentials
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 8 more

The POM contains just two dependencies:

    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-chrome-driver</artifactId>
        <version>3.4.0</version>
    </dependency>
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>3.4.0</version>
    </dependency>

I thought the problem in Selenium dependencies, as they are rely on some apache code but not download dependent components. I tried to add apache dependencies like:

    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.3</version>
    </dependency>

    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpcore</artifactId>
        <version>4.4.6</version>
    </dependency>

But problem persists.

Please help to run selenium with headless Crome.

Body:
I was able to resolve by using just one dependency:

    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-chrome-driver</artifactId>
        <version>2.53.1</version>
    </dependency>

Also it works with 3.3.1, 3.2.0. As I see the problem happen in 3.4.0 version only.


问:
Activity not opening after signing in
I'm currently creating an application that allows the user to login using a web api. While checking response of the API , i'm not getting any error.

```<code>{"error":0,"data":[{"id":"2","driver_name":"Test Driver","driver_lat":"","driver_long":"","driver_mobile_no":"9164618545","driver_password":"202cb962ac59075b964b07152d234b70","driver_token":"bef1032495ef4b2c891795fce1fa16c2","driver_image":"","is_active":"1","on_duty":"0","t_drivers":"0","created_at":"2017-07-04 06:38:22","last_activity_at":"2017-07-04 09:19:08"}],"msg":"Login Successfully."}
</code>```

But while using the app, it does not go to the mainActivity.
This is the login class:-

```<code>public class login extends AppCompatActivity {
private Button login1;
Session session;
private ConstraintLayout mRootLayout;
boolean doubleBackToExitPressedOnce = false;
boolean status = false;

EditText mEdtEmail , mEdtPassword ;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Fabric.with(this, new Answers(), new Crashlytics());
    setContentView(R.layout.activity_login);

    login1 = (Button) findViewById(R.id.button);
    mEdtEmail = (EditText) findViewById(R.id.phone_number);
    mEdtPassword = (EditText) findViewById(R.id.password);

    session = new Session(login.this);

    if (session.isLoggedIn()) {
        // User is already logged in. Take him to main activity
        Intent intent = new Intent(login.this, MainActivity.class);
        startActivity(intent);
        finish();
    }

   // sign_in();

    login1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            String mobile = mEdtEmail.getText().toString().trim();
            String password = mEdtPassword.getText().toString().trim();

            status = checkInternetConnection();

            if (status) {

                if (mobile.length() == 0) {
                    mEdtEmail.setError("Required");
                } else if (mobile.length() < 10) {
                    mEdtEmail.setError("Mobile no must be 10 char. long");
                } else if (password.length() == 0) {
                    mEdtPassword.setError("Required");
                } else {

                    new UserLoginTask(mobile, password, login.this).execute();

                }
            }
            else
            {
                Snackbar.make(mRootLayout, "You don't have Internet connection!", Snackbar.LENGTH_LONG).show();
                //  Toast.makeText(getApplicationContext(), "You don't have Internet connection", Toast.LENGTH_LONG).show();
            }
        }
    });
}

private class UserLoginTask extends AsyncTask<String, Void, String> {

    private String mUserName;
    private String mPassword;
    String msg ;
    ProgressDialog progressDialog;

    Boolean loginStatus = false;
    private Activity activity;
    public static final String MyPREFERENCES = "MyPrefs" ;
    SharedPreferences sharedpreferences;

    UserLoginTask(String userName, String password, Activity activity) {
        mUserName = userName;
        mPassword = password;
        this.activity = activity;
    }

    @Override
    protected void onPreExecute() {
        progressDialog= ProgressDialog.show(login.this, "Loading. . .","Please Wait. . .", true);
        Toast.makeText(login.this,"toast 1",Toast.LENGTH_SHORT).show();
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(String... params) {

        try {

            String result= WebService.postHttpResponse(mUserName, mPassword, activity);

            JSONObject jsonObject = new JSONObject(result);
          //  Log.d("Json Array", "doInBackground: "+jsonObject);
           String status = jsonObject.optString("error");
         //   msg = jsonObject.optString("msg");
           // Toast.makeText(login.this,"toast 2",Toast.LENGTH_SHORT).show();
            if(status.equals("0")){

                loginStatus = true ;

                session.setLogin(true);

                JSONArray jsonarray = jsonObject.getJSONArray("data");
                JSONObject jsonObject1=jsonarray.getJSONObject(0);

                status = jsonObject1.getString("msg");
                Log.e("DRIVER NAME -----" ,jsonObject1.getString("driver_name"));

                Driver driver = new Driver();

                driver.setId(jsonObject1.getString("id"));
                driver.setDriver_name(jsonObject1.getString("driver_name"));
                driver.setDriver_lat(jsonObject1.getString("driver_lat"));
                driver.setDriver_long(jsonObject1.getString("driver_long"));
                driver.setDriver_mobile_no(jsonObject1.getString("driver_mobile_no"));
                driver.setDriver_token(jsonObject1.getString("driver_token"));
                driver.setCreated_at(jsonObject1.getString("created_at"));
                driver.setLast_activity_at(jsonObject1.getString("last_activity_at"));

                sharedpreferences = activity.getSharedPreferences("MY" , Context.MODE_PRIVATE);
                SharedPreferences.Editor editor =  sharedpreferences.edit();

                editor.putString("driver_name",jsonObject1.getString("driver_name"));
                editor.putString("driver_mobile_no", jsonObject1.getString("driver_mobile_no"));
                editor.putString("id", jsonObject1.getString("id"));
                editor.putString("driver_token", jsonObject1.getString("driver_token"));
                editor.putString("driver_image", jsonObject1.getString("driver_image"));
                editor.putString("current_order_no", "");

                editor.commit();
                startActivity(intent);
                activity.startActivity(new Intent(activity, MainActivity.class).putExtra("driver_obj" , driver));

                overridePendingTransition(R.anim.right_in, R.anim.left_out);
                finish();

            }

            else {
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();

        } catch (JSONException e) {
            e.printStackTrace();

        }

        return msg ;

    }

    @Override
    protected void onPostExecute(String msg) {
        super.onPostExecute(msg);

        progressDialog.dismiss();
        Toast.makeText(activity , msg , Toast.LENGTH_LONG).show();

    }
}

/*public void sign_in(){
    login1=(Button)findViewById(R.id.button);
    login1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(login.this,"Welcome!", Toast.LENGTH_SHORT).show();

            startActivity(intent);
        }
    });
}*/
@Override
public void onBackPressed() {
    if (doubleBackToExitPressedOnce){
        super.onBackPressed();
        return;
    }

    this.doubleBackToExitPressedOnce = true ;
    Toast.makeText(this , "Please click BACK again to exit" , Toast.LENGTH_SHORT).show();
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            doubleBackToExitPressedOnce = false ;
        }
    }, 2000);

    /*Intent intent = new Intent(Intent.ACTION_MAIN);
    intent.addCategory(Intent.CATEGORY_HOME);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(intent);
    finish();
    System.exit(0);*/

}

public boolean checkInternetConnection()
{

    ConnectivityManager connectivity = (ConnectivityManager)getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);

    if (connectivity != null)
    {
        NetworkInfo[] inf = connectivity.getAllNetworkInfo();
        if (inf != null)
            for (int i = 0; i < inf.length; i++)
                if (inf[i].getState() == NetworkInfo.State.CONNECTED)
                {
                    return true;
                }

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

Please Help!
Thanks!!

EDIT 1: Thanks a lot! I've gotten the solution for this. It was a really small error on my part!

答:
Your jsonObject1.getString("msg"); don't have any msg

```<code> {"error":0,"data":[{"id":"2",.....}],"msg":"Login Successfully."}

  // `                                ^^^^^  part of jsonObject`
                     |_____________|
                            | first json object which has no msg key/value pair
                   |________________|
                            | jsonarray
 |_______________________________________________________________|
                 |
JSONObject jsonObject = new JSONObject(result);
// response object
String status = jsonObject.optString("error");
// response json contains error , so far so good
..
..
JSONArray jsonarray = jsonObject.getJSONArray("data");
// get the jsonarray
JSONObject jsonObject1=jsonarray.getJSONObject(0);
// get first object

status = jsonObject1.getString("msg");
// there is no msg string in jsonObject1 hence error
</code>```

so use

```<code>jsonObject.optString("msg");
</code>```

Note : Apparently you are starting your MainActivity twice so remove one and from doInBackground which works on background thread so don't do this

```<code>Intent intent = new Intent("oodi_design.driver4.Activity.MainActivity");
                startActivity(intent);
                activity.startActivity(new Intent(activity, MainActivity.class).putExtra("driver_obj" , driver));
</code>```

Start your activity from onPostExecute

Title: Activity not opening after signing in

Body:
I'm currently creating an application that allows the user to login using a web api. While checking response of the API , i'm not getting any error.

{"error":0,"data":[{"id":"2","driver_name":"Test Driver","driver_lat":"","driver_long":"","driver_mobile_no":"9164618545","driver_password":"202cb962ac59075b964b07152d234b70","driver_token":"bef1032495ef4b2c891795fce1fa16c2","driver_image":"","is_active":"1","on_duty":"0","t_drivers":"0","created_at":"2017-07-04 06:38:22","last_activity_at":"2017-07-04 09:19:08"}],"msg":"Login Successfully."}

But while using the app, it does not go to the mainActivity.
This is the login class:-

public class login extends AppCompatActivity {
private Button login1;
Session session;
private ConstraintLayout mRootLayout;
boolean doubleBackToExitPressedOnce = false;
boolean status = false;

EditText mEdtEmail , mEdtPassword ;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Fabric.with(this, new Answers(), new Crashlytics());
    setContentView(R.layout.activity_login);

    login1 = (Button) findViewById(R.id.button);
    mEdtEmail = (EditText) findViewById(R.id.phone_number);
    mEdtPassword = (EditText) findViewById(R.id.password);

    session = new Session(login.this);

    if (session.isLoggedIn()) {
        // User is already logged in. Take him to main activity
        Intent intent = new Intent(login.this, MainActivity.class);
        startActivity(intent);
        finish();
    }

   // sign_in();

    login1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            String mobile = mEdtEmail.getText().toString().trim();
            String password = mEdtPassword.getText().toString().trim();

            status = checkInternetConnection();

            if (status) {

                if (mobile.length() == 0) {
                    mEdtEmail.setError("Required");
                } else if (mobile.length() < 10) {
                    mEdtEmail.setError("Mobile no must be 10 char. long");
                } else if (password.length() == 0) {
                    mEdtPassword.setError("Required");
                } else {

                    new UserLoginTask(mobile, password, login.this).execute();

                }
            }
            else
            {
                Snackbar.make(mRootLayout, "You don't have Internet connection!", Snackbar.LENGTH_LONG).show();
                //  Toast.makeText(getApplicationContext(), "You don't have Internet connection", Toast.LENGTH_LONG).show();
            }
        }
    });
}

private class UserLoginTask extends AsyncTask<String, Void, String> {

    private String mUserName;
    private String mPassword;
    String msg ;
    ProgressDialog progressDialog;

    Boolean loginStatus = false;
    private Activity activity;
    public static final String MyPREFERENCES = "MyPrefs" ;
    SharedPreferences sharedpreferences;

    UserLoginTask(String userName, String password, Activity activity) {
        mUserName = userName;
        mPassword = password;
        this.activity = activity;
    }

    @Override
    protected void onPreExecute() {
        progressDialog= ProgressDialog.show(login.this, "Loading. . .","Please Wait. . .", true);
        Toast.makeText(login.this,"toast 1",Toast.LENGTH_SHORT).show();
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(String... params) {

        try {

            String result= WebService.postHttpResponse(mUserName, mPassword, activity);

            JSONObject jsonObject = new JSONObject(result);
          //  Log.d("Json Array", "doInBackground: "+jsonObject);
           String status = jsonObject.optString("error");
         //   msg = jsonObject.optString("msg");
           // Toast.makeText(login.this,"toast 2",Toast.LENGTH_SHORT).show();
            if(status.equals("0")){

                loginStatus = true ;

                session.setLogin(true);

                JSONArray jsonarray = jsonObject.getJSONArray("data");
                JSONObject jsonObject1=jsonarray.getJSONObject(0);

                status = jsonObject1.getString("msg");
                Log.e("DRIVER NAME -----" ,jsonObject1.getString("driver_name"));

                Driver driver = new Driver();

                driver.setId(jsonObject1.getString("id"));
                driver.setDriver_name(jsonObject1.getString("driver_name"));
                driver.setDriver_lat(jsonObject1.getString("driver_lat"));
                driver.setDriver_long(jsonObject1.getString("driver_long"));
                driver.setDriver_mobile_no(jsonObject1.getString("driver_mobile_no"));
                driver.setDriver_token(jsonObject1.getString("driver_token"));
                driver.setCreated_at(jsonObject1.getString("created_at"));
                driver.setLast_activity_at(jsonObject1.getString("last_activity_at"));

                sharedpreferences = activity.getSharedPreferences("MY" , Context.MODE_PRIVATE);
                SharedPreferences.Editor editor =  sharedpreferences.edit();

                editor.putString("driver_name",jsonObject1.getString("driver_name"));
                editor.putString("driver_mobile_no", jsonObject1.getString("driver_mobile_no"));
                editor.putString("id", jsonObject1.getString("id"));
                editor.putString("driver_token", jsonObject1.getString("driver_token"));
                editor.putString("driver_image", jsonObject1.getString("driver_image"));
                editor.putString("current_order_no", "");

                editor.commit();
                startActivity(intent);
                activity.startActivity(new Intent(activity, MainActivity.class).putExtra("driver_obj" , driver));

                overridePendingTransition(R.anim.right_in, R.anim.left_out);
                finish();

            }

            else {
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();

        } catch (JSONException e) {
            e.printStackTrace();

        }

        return msg ;

    }

    @Override
    protected void onPostExecute(String msg) {
        super.onPostExecute(msg);

        progressDialog.dismiss();
        Toast.makeText(activity , msg , Toast.LENGTH_LONG).show();

    }
}

/*public void sign_in(){
    login1=(Button)findViewById(R.id.button);
    login1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(login.this,"Welcome!", Toast.LENGTH_SHORT).show();

            startActivity(intent);
        }
    });
}*/
@Override
public void onBackPressed() {
    if (doubleBackToExitPressedOnce){
        super.onBackPressed();
        return;
    }

    this.doubleBackToExitPressedOnce = true ;
    Toast.makeText(this , "Please click BACK again to exit" , Toast.LENGTH_SHORT).show();
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            doubleBackToExitPressedOnce = false ;
        }
    }, 2000);

    /*Intent intent = new Intent(Intent.ACTION_MAIN);
    intent.addCategory(Intent.CATEGORY_HOME);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(intent);
    finish();
    System.exit(0);*/

}

public boolean checkInternetConnection()
{

    ConnectivityManager connectivity = (ConnectivityManager)getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);

    if (connectivity != null)
    {
        NetworkInfo[] inf = connectivity.getAllNetworkInfo();
        if (inf != null)
            for (int i = 0; i < inf.length; i++)
                if (inf[i].getState() == NetworkInfo.State.CONNECTED)
                {
                    return true;
                }

    }
    return false;
}
}

Please Help!
Thanks!!

EDIT 1: Thanks a lot! I've gotten the solution for this. It was a really small error on my part!

Body:
Your jsonObject1.getString("msg"); don't have any msg

 {"error":0,"data":[{"id":"2",.....}],"msg":"Login Successfully."}

  // `                                ^^^^^  part of jsonObject`
                     |_____________|
                            | first json object which has no msg key/value pair
                   |________________|
                            | jsonarray
 |_______________________________________________________________|
                 |
JSONObject jsonObject = new JSONObject(result);
// response object
String status = jsonObject.optString("error");
// response json contains error , so far so good
..
..
JSONArray jsonarray = jsonObject.getJSONArray("data");
// get the jsonarray
JSONObject jsonObject1=jsonarray.getJSONObject(0);
// get first object

status = jsonObject1.getString("msg");
// there is no msg string in jsonObject1 hence error

so use

jsonObject.optString("msg");

Note : Apparently you are starting your MainActivity twice so remove one and from doInBackground which works on background thread so don't do this

Intent intent = new Intent("oodi_design.driver4.Activity.MainActivity");
                startActivity(intent);
                activity.startActivity(new Intent(activity, MainActivity.class).putExtra("driver_obj" , driver));

Start your activity from onPostExecute


问:
Umbraco cannot start. A connection string is configured -running correctly in local but error on hosted one
My project is working perfectly on local host but I am trying to host it on iis and following error is showing

Steps which I have tried so far:

1.checked my connection string which is

```<code><connectionStrings>
    <remove name="umbracoDbDSN" />
    <add name="umbracoDbDSN" connectionString="Server=EIL-IT-360-39\SQLEXPRESS;Database=umbraco_16_6;Integrated Security=true" providerName="System.Data.SqlClient" />
  </connectionStrings>
</code>```

2.Using window authentication to login into my DB.

I have also refrered given sites but could not found desired solution:

Umbraco cannot start. A connection string is configured but the Umbraco cannot connect to the database

Umbraco cannot start after switching to local SQL database

答:
It looks like a permissions/connection issue. Usually this is because either the IIS server can't see the machine "EIL-IT-360-39" (try using the machine's IP address instead). Or the windows authentication isn't working.

If you're using integrated authentication, the site will be connecting as your application pool identity account. You need to make sure that the application pool account has access to read and write to your database. There is a tutorial here on how to do this: https://msdn.microsoft.com/en-us/library/bsz5788z.aspx

Body:
My project is working perfectly on local host but I am trying to host it on iis and following error is showing

Steps which I have tried so far:

1.checked my connection string which is

<connectionStrings>
    <remove name="umbracoDbDSN" />
    <add name="umbracoDbDSN" connectionString="Server=EIL-IT-360-39\SQLEXPRESS;Database=umbraco_16_6;Integrated Security=true" providerName="System.Data.SqlClient" />
  </connectionStrings>

2.Using window authentication to login into my DB.

I have also refrered given sites but could not found desired solution:

Umbraco cannot start. A connection string is configured but the Umbraco cannot connect to the database

Umbraco cannot start after switching to local SQL database


问:
Loop over columns in DF and calculate sum based on condition for every appended column in R or Python
```<code>A B C
1 0 0
0 0 1
0 1 0
1 1 1
</code>```

Here I have 4*3 dataframe (columns A,B,C). I`d like to calculate sum in a combination of columns based on a condition that both rows are 1. In other words, in the output I want to have 1*3 dataframe with A 2 B 1 C 1. So, first I look at column A, it has 2 rows with ones, so the sum is 2, then I look at combination of A and B, there is just one row with BOTH 1, so I get 1. Finally, I get combination of A,B,C and it has one row with all ones, so I get 1 as well. Could you pls help with the best way to do it in R or Python.

答:
If you want the results in a Series, you can do something like this. a dict or OrderedDict would be easy too

```<code>results = pd.Series(index=df.columns)
for i, idx in enumerate(df.columns, 1):
    results[idx] = df.iloc[:,:i].all(axis=1).sum()
</code>```

results

```<code>A    2.0
B    1.0
C    1.0
</code>```

Body:
A B C
1 0 0
0 0 1
0 1 0
1 1 1

Here I have 4*3 dataframe (columns A,B,C). I`d like to calculate sum in a combination of columns based on a condition that both rows are 1. In other words, in the output I want to have 1*3 dataframe with A 2 B 1 C 1. So, first I look at column A, it has 2 rows with ones, so the sum is 2, then I look at combination of A and B, there is just one row with BOTH 1, so I get 1. Finally, I get combination of A,B,C and it has one row with all ones, so I get 1 as well. Could you pls help with the best way to do it in R or Python.

Body:
If you want the results in a Series, you can do something like this. a dict or OrderedDict would be easy too

results = pd.Series(index=df.columns)
for i, idx in enumerate(df.columns, 1):
    results[idx] = df.iloc[:,:i].all(axis=1).sum()

results

A    2.0
B    1.0
C    1.0


问:
RelativeLayout.LayoutParams causing app crash in android
I had a recycler view for which I have a linear layout as parent and a relative layout as child. I'm changing the layout params to these dynamically. My code is working pretty well for linear layout but when it comes to relative layout it is crashing.

It is not even showing the line number which is causing crash and after so many runs I figured out the line which is causing crash. This is the recycler view adapter class.

```<code>    @Override
    public void onBindViewHolder(Holder holder, int position) {
        ChatListItem listItem = listdata.get(position);
        LinearLayout parent=holder.parent;
        RelativeLayout chatView=holder.relLayout;
        holder.time.setText(listItem.time);
        holder.message.setText(listItem.message);
        if (!listItem.sentByCustomer) {
            int match_parent= LinearLayout.LayoutParams.MATCH_PARENT;
            int wrap_content= LinearLayout.LayoutParams.WRAP_CONTENT;
            chatView.setBackground(context.getResources().getDrawable(R.drawable.incoming_normal));

            LinearLayout.LayoutParams parentParams=new LinearLayout.LayoutParams(match_parent,wrap_content);
            parentParams.setMarginStart(5);
            parent.setLayoutParams(parentParams);

            int rel_wrap_content=RelativeLayout.LayoutParams.WRAP_CONTENT;
            RelativeLayout.LayoutParams relParams=new RelativeLayout.LayoutParams(rel_wrap_content,rel_wrap_content);
            relParams.setMarginEnd(50);

            chatView.setLayoutParams(relParams); // This line is  causing crash

        }
    }

    class Holder extends RecyclerView.ViewHolder  {
        LinearLayout parent;
        RelativeLayout relLayout;
        TextView message, time;

        public Holder(View itemView) {
            super(itemView);
            parent=(LinearLayout)itemView.findViewById(R.id.chat_view_parent);
            relLayout = (RelativeLayout) itemView.findViewById(R.id.customer_chat_view);
            message = (TextView) itemView.findViewById(R.id.customer_chat_message);
            time = (TextView) itemView.findViewById(R.id.chat_time);
        }
    }
}
</code>```

Everything is fine the layout params belong to relative layout params and I'm setting them to a relative layout and I've also cross checked the xml file and that one is also a relative layout. Still the error log is saying it can't cast the linear layout params to relative layout params. Even the debugger is saying it as relative layout but why am I getting the error ? Here is the error log

```<code>07-04 15:09:13.609 5441-5441/com.motowala E/UncaughtException: java.lang.ClassCastException: android.widget.RelativeLayout$LayoutParams cannot be cast to android.widget.LinearLayout$LayoutParams
                                                                   at android.widget.LinearLayout.measureHorizontal(LinearLayout.java:1071)
                                                                   at android.widget.LinearLayout.onMeasure(LinearLayout.java:642)
                                                                   at android.view.View.measure(View.java:19861)
                                                                   at android.support.v7.widget.RecyclerView$LayoutManager.measureChildWithMargins(RecyclerView.java:8636)
                                                                   at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1577)
                                                                   at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1511)
                                                                   at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:570)
                                                                   at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3583)
                                                                   at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3312)
                                                                   at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3844)
                                                                   at android.view.View.layout(View.java:17641)
                                                                   at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                   at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1079)
                                                                   at android.view.View.layout(View.java:17641)
                                                                   at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                   at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
                                                                   at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
                                                                   at android.view.View.layout(View.java:17641)
                                                                   at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                   at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1741)
                                                                   at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1585)
                                                                   at android.widget.LinearLayout.onLayout(LinearLayout.java:1494)
                                                                   at android.view.View.layout(View.java:17641)
                                                                   at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                   at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
                                                                   at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
                                                                   at android.view.View.layout(View.java:17641)
                                                                   at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                   at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1741)
                                                                   at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1585)
                                                                   at android.widget.LinearLayout.onLayout(LinearLayout.java:1494)
                                                                   at android.view.View.layout(View.java:17641)
                                                                   at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                   at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
                                                                   at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
                                                                   at com.android.internal.policy.DecorView.onLayout(DecorView.java:728)
                                                                   at android.view.View.layout(View.java:17641)
                                                                   at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                   at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2346)
                                                                   at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2068)
                                                                   at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1254)
                                                                   at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6343)
                                                                   at android.view.Choreographer$CallbackRecord.run(Choreographer.java:874)
                                                                   at android.view.Choreographer.doCallbacks(Choreographer.java:686)
                                                                   at android.view.Choreographer.doFrame(Choreographer.java:621)
                                                                   at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:860)
                                                                   at android.os.Handler.handleCallback(Handler.java:751)
                                                                   at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                   at android.os.Looper.loop(Looper.java:154)
                                                                   at android.app.ActivityThread.main(ActivityThread.java:6176)
                                                                   at java.lang.reflect.Method.invoke(Native Method)
                                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:888)
                                                                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:778)
07-04 15:09:13.613 5441-5502/com.motowala D/FA: Logging event (FE): _ae, Bundle[{_o=crash, _sc=CustomerChatActivity, _si=6120152536016377641, timestamp=1499161153609, fatal=1}]
07-04 15:09:13.906 5441-5441/com.motowala E/AndroidRuntime: FATAL EXCEPTION: main
                                                            Process: com.motowala, PID: 5441
                                                            java.lang.ClassCastException: android.widget.RelativeLayout$LayoutParams cannot be cast to android.widget.LinearLayout$LayoutParams
                                                                at android.widget.LinearLayout.measureHorizontal(LinearLayout.java:1071)
                                                                at android.widget.LinearLayout.onMeasure(LinearLayout.java:642)
                                                                at android.view.View.measure(View.java:19861)
                                                                at android.support.v7.widget.RecyclerView$LayoutManager.measureChildWithMargins(RecyclerView.java:8636)
                                                                at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1577)
                                                                at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1511)
                                                                at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:570)
                                                                at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3583)
                                                                at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3312)
                                                                at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3844)
                                                                at android.view.View.layout(View.java:17641)
                                                                at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1079)
                                                                at android.view.View.layout(View.java:17641)
                                                                at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
                                                                at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
                                                                at android.view.View.layout(View.java:17641)
                                                                at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1741)
                                                                at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1585)
                                                                at android.widget.LinearLayout.onLayout(LinearLayout.java:1494)
                                                                at android.view.View.layout(View.java:17641)
                                                                at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
                                                                at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
                                                                at android.view.View.layout(View.java:17641)
                                                                at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1741)
                                                                at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1585)
                                                                at android.widget.LinearLayout.onLayout(LinearLayout.java:1494)
                                                                at android.view.View.layout(View.java:17641)
                                                                at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
                                                                at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
                                                                at com.android.internal.policy.DecorView.onLayout(DecorView.java:728)
                                                                at android.view.View.layout(View.java:17641)
                                                                at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2346)
                                                                at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2068)
                                                                at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1254)
                                                                at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6343)
                                                                at android.view.Choreographer$CallbackRecord.run(Choreographer.java:874)
                                                                at android.view.Choreographer.doCallbacks(Choreographer.java:686)
                                                                at android.view.Choreographer.doFrame(Choreographer.java:621)
                                                                at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:860)
                                                                at android.os.Handler.handleCallback(Handler.java:751)
                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                at android.os.Looper.loop(Looper.java:154)
                                                                at android.app.ActivityThread.main(ActivityThread.java:6176)
                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:888)
                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:778)
</code>```

Thanks a lot in advance....

答: I resolved my issue by removing the root linear layout and making the relative layout as root. But still I'm clueless of the reason why the error has occured :(</p>

Body:
I had a recycler view for which I have a linear layout as parent and a relative layout as child. I'm changing the layout params to these dynamically. My code is working pretty well for linear layout but when it comes to relative layout it is crashing.

It is not even showing the line number which is causing crash and after so many runs I figured out the line which is causing crash. This is the recycler view adapter class.

    @Override
    public void onBindViewHolder(Holder holder, int position) {
        ChatListItem listItem = listdata.get(position);
        LinearLayout parent=holder.parent;
        RelativeLayout chatView=holder.relLayout;
        holder.time.setText(listItem.time);
        holder.message.setText(listItem.message);
        if (!listItem.sentByCustomer) {
            int match_parent= LinearLayout.LayoutParams.MATCH_PARENT;
            int wrap_content= LinearLayout.LayoutParams.WRAP_CONTENT;
            chatView.setBackground(context.getResources().getDrawable(R.drawable.incoming_normal));

            LinearLayout.LayoutParams parentParams=new LinearLayout.LayoutParams(match_parent,wrap_content);
            parentParams.setMarginStart(5);
            parent.setLayoutParams(parentParams);

            int rel_wrap_content=RelativeLayout.LayoutParams.WRAP_CONTENT;
            RelativeLayout.LayoutParams relParams=new RelativeLayout.LayoutParams(rel_wrap_content,rel_wrap_content);
            relParams.setMarginEnd(50);

            chatView.setLayoutParams(relParams); // This line is  causing crash

        }
    }

    class Holder extends RecyclerView.ViewHolder  {
        LinearLayout parent;
        RelativeLayout relLayout;
        TextView message, time;

        public Holder(View itemView) {
            super(itemView);
            parent=(LinearLayout)itemView.findViewById(R.id.chat_view_parent);
            relLayout = (RelativeLayout) itemView.findViewById(R.id.customer_chat_view);
            message = (TextView) itemView.findViewById(R.id.customer_chat_message);
            time = (TextView) itemView.findViewById(R.id.chat_time);
        }
    }
}

Everything is fine the layout params belong to relative layout params and I'm setting them to a relative layout and I've also cross checked the xml file and that one is also a relative layout. Still the error log is saying it can't cast the linear layout params to relative layout params. Even the debugger is saying it as relative layout but why am I getting the error ? Here is the error log

07-04 15:09:13.609 5441-5441/com.motowala E/UncaughtException: java.lang.ClassCastException: android.widget.RelativeLayout$LayoutParams cannot be cast to android.widget.LinearLayout$LayoutParams
                                                                   at android.widget.LinearLayout.measureHorizontal(LinearLayout.java:1071)
                                                                   at android.widget.LinearLayout.onMeasure(LinearLayout.java:642)
                                                                   at android.view.View.measure(View.java:19861)
                                                                   at android.support.v7.widget.RecyclerView$LayoutManager.measureChildWithMargins(RecyclerView.java:8636)
                                                                   at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1577)
                                                                   at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1511)
                                                                   at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:570)
                                                                   at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3583)
                                                                   at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3312)
                                                                   at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3844)
                                                                   at android.view.View.layout(View.java:17641)
                                                                   at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                   at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1079)
                                                                   at android.view.View.layout(View.java:17641)
                                                                   at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                   at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
                                                                   at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
                                                                   at android.view.View.layout(View.java:17641)
                                                                   at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                   at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1741)
                                                                   at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1585)
                                                                   at android.widget.LinearLayout.onLayout(LinearLayout.java:1494)
                                                                   at android.view.View.layout(View.java:17641)
                                                                   at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                   at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
                                                                   at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
                                                                   at android.view.View.layout(View.java:17641)
                                                                   at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                   at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1741)
                                                                   at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1585)
                                                                   at android.widget.LinearLayout.onLayout(LinearLayout.java:1494)
                                                                   at android.view.View.layout(View.java:17641)
                                                                   at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                   at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
                                                                   at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
                                                                   at com.android.internal.policy.DecorView.onLayout(DecorView.java:728)
                                                                   at android.view.View.layout(View.java:17641)
                                                                   at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                   at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2346)
                                                                   at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2068)
                                                                   at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1254)
                                                                   at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6343)
                                                                   at android.view.Choreographer$CallbackRecord.run(Choreographer.java:874)
                                                                   at android.view.Choreographer.doCallbacks(Choreographer.java:686)
                                                                   at android.view.Choreographer.doFrame(Choreographer.java:621)
                                                                   at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:860)
                                                                   at android.os.Handler.handleCallback(Handler.java:751)
                                                                   at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                   at android.os.Looper.loop(Looper.java:154)
                                                                   at android.app.ActivityThread.main(ActivityThread.java:6176)
                                                                   at java.lang.reflect.Method.invoke(Native Method)
                                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:888)
                                                                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:778)
07-04 15:09:13.613 5441-5502/com.motowala D/FA: Logging event (FE): _ae, Bundle[{_o=crash, _sc=CustomerChatActivity, _si=6120152536016377641, timestamp=1499161153609, fatal=1}]
07-04 15:09:13.906 5441-5441/com.motowala E/AndroidRuntime: FATAL EXCEPTION: main
                                                            Process: com.motowala, PID: 5441
                                                            java.lang.ClassCastException: android.widget.RelativeLayout$LayoutParams cannot be cast to android.widget.LinearLayout$LayoutParams
                                                                at android.widget.LinearLayout.measureHorizontal(LinearLayout.java:1071)
                                                                at android.widget.LinearLayout.onMeasure(LinearLayout.java:642)
                                                                at android.view.View.measure(View.java:19861)
                                                                at android.support.v7.widget.RecyclerView$LayoutManager.measureChildWithMargins(RecyclerView.java:8636)
                                                                at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1577)
                                                                at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1511)
                                                                at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:570)
                                                                at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3583)
                                                                at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3312)
                                                                at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3844)
                                                                at android.view.View.layout(View.java:17641)
                                                                at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1079)
                                                                at android.view.View.layout(View.java:17641)
                                                                at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
                                                                at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
                                                                at android.view.View.layout(View.java:17641)
                                                                at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1741)
                                                                at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1585)
                                                                at android.widget.LinearLayout.onLayout(LinearLayout.java:1494)
                                                                at android.view.View.layout(View.java:17641)
                                                                at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
                                                                at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
                                                                at android.view.View.layout(View.java:17641)
                                                                at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1741)
                                                                at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1585)
                                                                at android.widget.LinearLayout.onLayout(LinearLayout.java:1494)
                                                                at android.view.View.layout(View.java:17641)
                                                                at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
                                                                at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
                                                                at com.android.internal.policy.DecorView.onLayout(DecorView.java:728)
                                                                at android.view.View.layout(View.java:17641)
                                                                at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2346)
                                                                at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2068)
                                                                at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1254)
                                                                at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6343)
                                                                at android.view.Choreographer$CallbackRecord.run(Choreographer.java:874)
                                                                at android.view.Choreographer.doCallbacks(Choreographer.java:686)
                                                                at android.view.Choreographer.doFrame(Choreographer.java:621)
                                                                at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:860)
                                                                at android.os.Handler.handleCallback(Handler.java:751)
                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                at android.os.Looper.loop(Looper.java:154)
                                                                at android.app.ActivityThread.main(ActivityThread.java:6176)
                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:888)
                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:778)

Thanks a lot in advance....


问:
Why overloaded operator== for std::weak_ptr instantiated with type defined in namespace can't be found?
I'm using Visual Studio 2015.

Any idea why this code compiles:

```<code>#include <memory>

class Foo;
class Bar;
typedef std::pair<Foo*,std::weak_ptr<Bar>> Object;
typedef std::vector<Object> ObjectVect;

bool operator==( std::weak_ptr<Bar> left,
                 std::weak_ptr<Bar> right )
{
    return left.lock() == right.lock();
}

int main( int argc, char* argv[] )
{
    ObjectVect vect;
    Object obj;
    auto foundIter = std::find( vect.begin(), vect.end(), obj );
    return 0;
}
</code>```

while this one gives me error:

```<code>#include <memory>

class Foo;
namespace MyNamespace
{
    class Bar;
}
typedef std::pair<Foo*,std::weak_ptr<MyNamespace::Bar>> Object;
typedef std::vector<Object> ObjectVect;

bool operator==( std::weak_ptr<MyNamespace::Bar> left,
                 std::weak_ptr<MyNamespace::Bar> right )
{
    return left.lock() == right.lock();
}

int main( int argc, char* argv[] )
{
    ObjectVect vect;
    Object obj;
    auto foundIter = std::find( vect.begin(), vect.end(), obj );
    return 0;
}
</code>```

Error C2678   binary '==': no operator found which takes a left-hand
  operand of type 'const std::weak_ptr' (or there is
  no acceptable
  conversion)   test_cppunit_interpreter_base_multi_output  c:\program
  files (x86)\microsoft visual studio 14.0\vc\include\utility   216

Looks like it failes to find the comparator when Bar is located in a namespace...

Am I doing something wrong? Or could this be a compiler bug?

答:
You should move operator== into the namespace to make ADL take effect; ADL will also examine the types used as the template arguments (i.e. MyNamespace::Bar) and add the associated namespaces (i.e MyNamespace) to the set of name lookup.
i.e.

```<code>namespace MyNamespace
{
    class Bar;
    bool operator==( std::weak_ptr<Bar> left,
                     std::weak_ptr<Bar> right )
    {
        return left.lock() == right.lock();
    }

}
</code>```

Why the 1st case works fine?

Because ADL works for global namespace too. For the 1st case both Bar and operator== is defined in the same namespace (i.e. the global namespace).

Why the 2nd case doesn't work?

Firstly note that std::find is defined in the namespace std, and there're many operator==s defined in it (with different parameter types). Then according to the rule of unqualified name lookup, when operator== is found at the namespace std, the name lookup stops. That means without the help of ADL, the operator== defined in the global namespace won't be found at all.

Body:
I'm using Visual Studio 2015.

Any idea why this code compiles:

#include <memory>

class Foo;
class Bar;
typedef std::pair<Foo*,std::weak_ptr<Bar>> Object;
typedef std::vector<Object> ObjectVect;

bool operator==( std::weak_ptr<Bar> left,
                 std::weak_ptr<Bar> right )
{
    return left.lock() == right.lock();
}

int main( int argc, char* argv[] )
{
    ObjectVect vect;
    Object obj;
    auto foundIter = std::find( vect.begin(), vect.end(), obj );
    return 0;
}

while this one gives me error:

#include <memory>

class Foo;
namespace MyNamespace
{
    class Bar;
}
typedef std::pair<Foo*,std::weak_ptr<MyNamespace::Bar>> Object;
typedef std::vector<Object> ObjectVect;

bool operator==( std::weak_ptr<MyNamespace::Bar> left,
                 std::weak_ptr<MyNamespace::Bar> right )
{
    return left.lock() == right.lock();
}

int main( int argc, char* argv[] )
{
    ObjectVect vect;
    Object obj;
    auto foundIter = std::find( vect.begin(), vect.end(), obj );
    return 0;
}

Error C2678   binary '==': no operator found which takes a left-hand
  operand of type 'const std::weak_ptr' (or there is
  no acceptable
  conversion)   test_cppunit_interpreter_base_multi_output  c:\program
  files (x86)\microsoft visual studio 14.0\vc\include\utility   216

Looks like it failes to find the comparator when Bar is located in a namespace...

Am I doing something wrong? Or could this be a compiler bug?

Body:
You should move operator== into the namespace to make ADL take effect; ADL will also examine the types used as the template arguments (i.e. MyNamespace::Bar) and add the associated namespaces (i.e MyNamespace) to the set of name lookup.
i.e.

namespace MyNamespace
{
    class Bar;
    bool operator==( std::weak_ptr<Bar> left,
                     std::weak_ptr<Bar> right )
    {
        return left.lock() == right.lock();
    }

}

Why the 1st case works fine?

Because ADL works for global namespace too. For the 1st case both Bar and operator== is defined in the same namespace (i.e. the global namespace).

Why the 2nd case doesn't work?

Firstly note that std::find is defined in the namespace std, and there're many operator==s defined in it (with different parameter types). Then according to the rule of unqualified name lookup, when operator== is found at the namespace std, the name lookup stops. That means without the help of ADL, the operator== defined in the global namespace won't be found at all.


问:
How do I highlight specific Label when selected from the comboBox?
So I have a database of users in my JComboBox and on the left side is a list of these users as well. What I want to do is write a program when this user is selected from the JComboBox, highlight him in the list(JLabel) on the left side. I hope I was specific enough.

答:
```<code>public class Test2 extends JFrame {

    private static final long serialVersionUID = 1L;
    private JPanel panel;
    private JComboBox<String> comboBox;
    private JList<String> list;

    public Test2() {
        panel = new JPanel();
        getContentPane().add(panel, BorderLayout.NORTH);
        GridBagLayout gbl_panel = new GridBagLayout();
        panel.setLayout(gbl_panel);

        comboBox = new JComboBox<String>();
        comboBox.addItem("User1");
        comboBox.addItem("User2");
        GridBagConstraints gbc_comboBox = new GridBagConstraints();
        gbc_comboBox.weightx = 1.0;
        gbc_comboBox.insets = new Insets(0, 0, 5, 0);
        gbc_comboBox.fill = GridBagConstraints.HORIZONTAL;
        gbc_comboBox.gridx = 0;
        gbc_comboBox.gridy = 0;
        panel.add(comboBox, gbc_comboBox);

        DefaultListModel<String> listModel = new DefaultListModel<>();
        listModel.addElement("User1");
        listModel.addElement("User2");

        list = new JList<String>(listModel);

        GridBagConstraints gbc_lblNewLabel = new GridBagConstraints();
        gbc_lblNewLabel.weightx = 1.0;
        gbc_lblNewLabel.gridx = 1;
        gbc_lblNewLabel.gridy = 0;

        panel.add(list, gbc_lblNewLabel);

        comboBox.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String selectedItem = String.valueOf(comboBox.getSelectedItem());

                if (selectedItem.equals("User1"))
                    list.setSelectedValue("User1", true);
                else if (selectedItem.equals("User2"))
                    list.setSelectedValue("User2", true);
            }
        });
    }

    public static void main(String[] args) {
        Test2 myFrame = new Test2();
        myFrame.setVisible(true);
        myFrame.setSize(new Dimension(400, 500));
        myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}
</code>```

Will this work for you?. I don't know why you are using JLabel inside JList. So i have changed the list from JList<JLabel> to JList<String>

Body:
public class Test2 extends JFrame {

    private static final long serialVersionUID = 1L;
    private JPanel panel;
    private JComboBox<String> comboBox;
    private JList<String> list;

    public Test2() {
        panel = new JPanel();
        getContentPane().add(panel, BorderLayout.NORTH);
        GridBagLayout gbl_panel = new GridBagLayout();
        panel.setLayout(gbl_panel);

        comboBox = new JComboBox<String>();
        comboBox.addItem("User1");
        comboBox.addItem("User2");
        GridBagConstraints gbc_comboBox = new GridBagConstraints();
        gbc_comboBox.weightx = 1.0;
        gbc_comboBox.insets = new Insets(0, 0, 5, 0);
        gbc_comboBox.fill = GridBagConstraints.HORIZONTAL;
        gbc_comboBox.gridx = 0;
        gbc_comboBox.gridy = 0;
        panel.add(comboBox, gbc_comboBox);

        DefaultListModel<String> listModel = new DefaultListModel<>();
        listModel.addElement("User1");
        listModel.addElement("User2");

        list = new JList<String>(listModel);

        GridBagConstraints gbc_lblNewLabel = new GridBagConstraints();
        gbc_lblNewLabel.weightx = 1.0;
        gbc_lblNewLabel.gridx = 1;
        gbc_lblNewLabel.gridy = 0;

        panel.add(list, gbc_lblNewLabel);

        comboBox.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String selectedItem = String.valueOf(comboBox.getSelectedItem());

                if (selectedItem.equals("User1"))
                    list.setSelectedValue("User1", true);
                else if (selectedItem.equals("User2"))
                    list.setSelectedValue("User2", true);
            }
        });
    }

    public static void main(String[] args) {
        Test2 myFrame = new Test2();
        myFrame.setVisible(true);
        myFrame.setSize(new Dimension(400, 500));
        myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

Will this work for you?. I don't know why you are using JLabel inside JList. So i have changed the list from JList<JLabel> to JList<String>


问:
CMAKE_BUILD_TYPE Release: strange results
We are creating an Android app to compare execution time between ART and native code. We are using Android Studio and CMake for compiling C/C++.

When in CMakeList.txt we set the flag

```<code>set(CMAKE_BUILD_TYPE Release)
</code>```

in some algorithms (Primality Test and Fibonacci) the execution time drastically drop to 0ms for all different input.

Here the native lib

```<code>bool flag = false;

extern "C" JNIEXPORT void JNICALL Java_javacpp_cmr_com_sdkvsndk_MainActivity_cancel(JNIEnv *env, jobject obj) {
        flag = true;
    }

extern "C" JNIEXPORT jlong JNICALL Java_javacpp_cmr_com_sdkvsndk_MainActivity_primalityTest(JNIEnv *env, jobject obj, jlong r) {
    if(r < 0) return -1L;
    timeval start, stop;
    long long t;
    gettimeofday(&start, NULL);

    bool prime = true;

    unsigned long long sr = (unsigned long long) sqrt(r);
    for (unsigned long long i = 2; (i <   sr) && prime; i++) {
        if (flag) return -1;
        if (r % i == 0) prime = false;
    }

    gettimeofday(&stop, NULL);
    t = (stop.tv_sec - start.tv_sec) * 1000;
    t += (long long) ((stop.tv_usec - start.tv_usec) / 1000)
    return (jlong) t;
    }
</code>```

flag is a flag that is set true when we terminate the asyncTask that execute the algorithm.

I can not figure how this is possible. Any suggestion? Thank you.

答:
You can dump the compilation commands used to build the C/C++ source files using:
 set(CMAKE_EXPORT_COMPILE_COMMANDS ON) in the CMakeLists.txt which will create a compile_commands.json in the build directory.

You can try different combination of the "CMAKE_BUILD_TYPE" and save the generated compile_commands.json for different build types for different compiler flags for optimizations, debugging etc.

Body:
We are creating an Android app to compare execution time between ART and native code. We are using Android Studio and CMake for compiling C/C++.

When in CMakeList.txt we set the flag

set(CMAKE_BUILD_TYPE Release)

in some algorithms (Primality Test and Fibonacci) the execution time drastically drop to 0ms for all different input.

Here the native lib

bool flag = false;

extern "C" JNIEXPORT void JNICALL Java_javacpp_cmr_com_sdkvsndk_MainActivity_cancel(JNIEnv *env, jobject obj) {
        flag = true;
    }

extern "C" JNIEXPORT jlong JNICALL Java_javacpp_cmr_com_sdkvsndk_MainActivity_primalityTest(JNIEnv *env, jobject obj, jlong r) {
    if(r < 0) return -1L;
    timeval start, stop;
    long long t;
    gettimeofday(&start, NULL);

    bool prime = true;

    unsigned long long sr = (unsigned long long) sqrt(r);
    for (unsigned long long i = 2; (i <   sr) && prime; i++) {
        if (flag) return -1;
        if (r % i == 0) prime = false;
    }

    gettimeofday(&stop, NULL);
    t = (stop.tv_sec - start.tv_sec) * 1000;
    t += (long long) ((stop.tv_usec - start.tv_usec) / 1000)
    return (jlong) t;
    }

flag is a flag that is set true when we terminate the asyncTask that execute the algorithm.

I can not figure how this is possible. Any suggestion? Thank you.


问:
Delete all in a Many to Many secondary table association in sqlalchemy
I have following models and associations:

```<code>class CartProductsAssociation(db.Model):
    __tablename__ = 'cart_products_association'
    cart_id = db.Column(db.Integer, db.ForeignKey('carts.id',ondelete='CASCADE'),primary_key=True)
    product_id = db.Column(db.Integer, db.ForeignKey('products.id',ondelete='CASCADE'), primary_key=True)
    quantity = db.Column(db.Integer)

    product = db.relationship("Product", backref="cart_associations", cascade="all,delete",passive_deletes=True)
    cart = db.relationship("Cart", backref="product_associations",cascade="all,delete",passive_deletes=True)

class Product(db.Model):
    __tablename__ = 'products'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String)
    img_path = db.Column(db.String)

    price = db.Column(db.Float, default=0.0)

    product_categories = db.relationship(
        "ProductCategory",
        secondary=product_product_categories,
        back_populates="products")

    carts = db.relationship("Product", secondary="cart_products_association",passive_deletes=True,cascade="all,delete" )

class Cart(db.Model):
    __tablename__ = 'carts'
    id = db.Column(db.Integer, primary_key=True)

    branch_id = db.Column(db.Integer, db.ForeignKey('branch.id'))
    branch = db.relationship("Branch", back_populates="carts")

    page_id = db.Column(db.Integer, db.ForeignKey('pages.id'))
    page = db.relationship("Page", back_populates="carts")

    shopper_id = db.Column(db.String, db.ForeignKey('shoppers.fb_user_id'))
    shopper = db.relationship(
        "Shopper",
        back_populates="carts")

    products = db.relationship("Product", secondary="cart_products_association")
    cart_status = db.Column(db.Enum('user_unconfirmed','user_confirmed','client_unconfirmed','client_confirmed', name='cart_status'), default='user_unconfirmed')
</code>```

When I am trying to delete a product I am getting following error:
AssertionError

```<code>AssertionError: Dependency rule tried to blank-out primary key column 'cart_products_association.cart_id' on instance '<CartProductsAssociation at 0x7f5fd41721d0>'
</code>```

How can I solve it?

答:
it solved the problem:</p>

```<code> product = models.Product.query.get(product_id)

 for ass in product.cart_associations:

    db.session.delete(ass)

db.session.delete(product)
db.session.commit()
</code>```

Body:
I have following models and associations:

class CartProductsAssociation(db.Model):
    __tablename__ = 'cart_products_association'
    cart_id = db.Column(db.Integer, db.ForeignKey('carts.id',ondelete='CASCADE'),primary_key=True)
    product_id = db.Column(db.Integer, db.ForeignKey('products.id',ondelete='CASCADE'), primary_key=True)
    quantity = db.Column(db.Integer)

    product = db.relationship("Product", backref="cart_associations", cascade="all,delete",passive_deletes=True)
    cart = db.relationship("Cart", backref="product_associations",cascade="all,delete",passive_deletes=True)

class Product(db.Model):
    __tablename__ = 'products'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String)
    img_path = db.Column(db.String)

    price = db.Column(db.Float, default=0.0)

    product_categories = db.relationship(
        "ProductCategory",
        secondary=product_product_categories,
        back_populates="products")

    carts = db.relationship("Product", secondary="cart_products_association",passive_deletes=True,cascade="all,delete" )

class Cart(db.Model):
    __tablename__ = 'carts'
    id = db.Column(db.Integer, primary_key=True)

    branch_id = db.Column(db.Integer, db.ForeignKey('branch.id'))
    branch = db.relationship("Branch", back_populates="carts")

    page_id = db.Column(db.Integer, db.ForeignKey('pages.id'))
    page = db.relationship("Page", back_populates="carts")

    shopper_id = db.Column(db.String, db.ForeignKey('shoppers.fb_user_id'))
    shopper = db.relationship(
        "Shopper",
        back_populates="carts")

    products = db.relationship("Product", secondary="cart_products_association")
    cart_status = db.Column(db.Enum('user_unconfirmed','user_confirmed','client_unconfirmed','client_confirmed', name='cart_status'), default='user_unconfirmed')

When I am trying to delete a product I am getting following error:
AssertionError

AssertionError: Dependency rule tried to blank-out primary key column 'cart_products_association.cart_id' on instance '<CartProductsAssociation at 0x7f5fd41721d0>'

How can I solve it?

Body:
it solved the problem:

 product = models.Product.query.get(product_id)

 for ass in product.cart_associations:

    db.session.delete(ass)

db.session.delete(product)
db.session.commit()


问:
How to add a collections of parameters to an SqlCommand before query execution in C#?
I have this code where I want to add a collections of Parameters to an SqlCommand.

```<code>public void AddParameters(Dictionary<string, object> parameters)
{
    if (parameters == null)
        return;

    foreach(KeyValuePair<string, object> keyValue in parameters)
    {
        sqlCommand.Parameters.AddWithValue(keyValue.Key, keyValue.Value);
    }
}
</code>```

I want to make it more efficienty without using a loop because I can have a very large collection of parameters. Is there any way to add the entire collection with a single function?

答:
You can use AddRange method to improve the performance slightly:</p>

```<code> public void AddParameters(SqlParameter[]  parameters)
    {
        if (parameters == null)
            return;
        sqlCommand.Parameters.AddRange(parameters);

    }
</code>```

Body:
I have this code where I want to add a collections of Parameters to an SqlCommand.

public void AddParameters(Dictionary<string, object> parameters)
{
    if (parameters == null)
        return;

    foreach(KeyValuePair<string, object> keyValue in parameters)
    {
        sqlCommand.Parameters.AddWithValue(keyValue.Key, keyValue.Value);
    }
}

I want to make it more efficienty without using a loop because I can have a very large collection of parameters. Is there any way to add the entire collection with a single function?

Body:
You can use AddRange method to improve the performance slightly:

 public void AddParameters(SqlParameter[]  parameters)
    {
        if (parameters == null)
            return;
        sqlCommand.Parameters.AddRange(parameters);

    }


问:
Js remove all classes from element
I have a button and when I click on it I want to remove all the classes. That's what I've tried so far:

```<code>button.style.className = ''
</code>```

document.querySelector('button').onclick = function() {
  this.style.className = '';
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.myClass {

  color:red;

}

.second {

  color:green;
}</code>```

<button class="myClass second">click me</button>```

Now I can't use classList.remove because I doen't know the class names, they are dynamic.

How can I remove all the classes from an element?

答:
HTML DOM removeAttribute() Method:

document.querySelector('button').onclick = function() {
  this.removeAttribute("class");
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.myClass {
  background-color:red;
}

.second {
  box-shadow: 0px 0px 10px 10px;
}</code>```

<button id="button" class="myClass second">click me</button>```

Title: Js remove all classes from element

Body:
I have a button and when I click on it I want to remove all the classes. That's what I've tried so far:

button.style.className = ''

document.querySelector('button').onclick = function() {
  this.style.className = '';
}

.myClass {

  color:red;

}

.second {

  color:green;
}

<button class="myClass second">click me</button>

Now I can't use classList.remove because I doen't know the class names, they are dynamic.

How can I remove all the classes from an element?

Body:
HTML DOM removeAttribute() Method:

document.querySelector('button').onclick = function() {
  this.removeAttribute("class");
}

.myClass {
  background-color:red;
}

.second {
  box-shadow: 0px 0px 10px 10px;
}

<button id="button" class="myClass second">click me</button>


问:
Change datetime format in jQuery
I have using following jquery code snippet in an input field to pick date and time in my page

```<code>$('.timePicker').datetimepicker({
    format:'yyyy/mm/dd HH:mm:ss',
    minDate: getFormattedDate(new Date())
});
</code>```

Current output is : 2017/07/05 06:07:04

While in need the date and time format in following format

Expected output : 07/05/2017 06:07AM

Ho can i change this code for this purpose ?

答:
Already there are similar questions available. Please refer the following links to find them. They will solve your problem.

DateTimePicker AM/PM 01

DateTimePicker AM/PM 02

Title: Change datetime format in jQuery

Body:
I have using following jquery code snippet in an input field to pick date and time in my page

$('.timePicker').datetimepicker({
    format:'yyyy/mm/dd HH:mm:ss',
    minDate: getFormattedDate(new Date())
});

Current output is : 2017/07/05 06:07:04

While in need the date and time format in following format

Expected output : 07/05/2017 06:07AM

Ho can i change this code for this purpose ?


问:
Tool which monitors file changes and uploads only changed files over ftp to webserver
Is there a tool(for Windows) which can monitor file changes and can upload only modified files over ftp to a webserver directory.  </p>

答: SmartFTP is one such tool which has synchronization feature... http://www.smartftp.com/features/</p>

ContentLicense: CC BY-SA 2.5


问:
Changing the format of an AS column from text to datetime
I am using this code to pull out a date and time from a text field.

```<code>    SELECT
    LEFT(SUBSTRING(eventcomments,
    CHARINDEX('Off-Site:', eventcomments) + 9, 17),
    CHARINDEX('Off-Site:', eventcomments)) AS Departed
</code>```

which creates a Departed column  dd/mm/yyyy hh:mm

I wanted to convert this from text to a datetime format so I added the following code.

```<code>    SELECT
    CONVERT(datetime,LEFT(SUBSTRING(eventcomments,
    CHARINDEX('Off-Site:', eventcomments) + 9, 17),
    CHARINDEX('Off-Site:', eventcomments))) AS Departed
</code>```

but I got the following error message,

```<code>The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
</code>```

My question is,

How can I change the format of the Departed column from text to a datetime format.

答:
Just use the CAST function:

```<code>SELECT CAST(LEFT(SUBSTRING(eventcomments,
            CHARINDEX('Off-Site:', eventcomments) + 9, 17),
            CHARINDEX('Off-Site:', eventcomments))
          AS DATETIME) AS Departed
</code>```

Like SELECT CAST('05/10/1983 19:00' as datetime)

Body:
I am using this code to pull out a date and time from a text field.

    SELECT
    LEFT(SUBSTRING(eventcomments,
    CHARINDEX('Off-Site:', eventcomments) + 9, 17),
    CHARINDEX('Off-Site:', eventcomments)) AS Departed

which creates a Departed column  dd/mm/yyyy hh:mm

I wanted to convert this from text to a datetime format so I added the following code.

    SELECT
    CONVERT(datetime,LEFT(SUBSTRING(eventcomments,
    CHARINDEX('Off-Site:', eventcomments) + 9, 17),
    CHARINDEX('Off-Site:', eventcomments))) AS Departed

but I got the following error message,

The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.

My question is,

How can I change the format of the Departed column from text to a datetime format.

Body:
Just use the CAST function:

SELECT CAST(LEFT(SUBSTRING(eventcomments,
            CHARINDEX('Off-Site:', eventcomments) + 9, 17),
            CHARINDEX('Off-Site:', eventcomments))
          AS DATETIME) AS Departed

Like SELECT CAST('05/10/1983 19:00' as datetime)