问:
Google Sign IN in android application
How can I do google sign in my android application without using google plus .
I need sign in of google in my app is like we sign in like facebook that a screen is appeared that ask you to fill username and password and then click on sign in button.

I had sign directly by using google play library and but I want that prompt comes and ask for the username and password .

I got a problem using google plus is that if any body had a google account but not activated its google plus account then what can I do in that case?

I want google sign in that way is there any way please give me solutions as soon as possible .

答:
Dependency
    Need Internet Permission

Working Code   see Link on  play Store
https://play.google.com/store/search?q=com.codecube.airbucks

```<code>compile 'com.google.android.gms:play-services:8.3.0'

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <com.google.android.gms.common.SignInButton
        android:id="@+id/sign_in_button"
        android:layout_width="200dp"
        android:layout_marginTop="20dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal" />
    <Button
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:layout_gravity="center_horizontal"
        android:text="Logout"
        android:id="@+id/btn"/>
</LinearLayout>

package com.keshav.geofencing;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.OptionalPendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Arrays;

import utilities.CommonMethod;
import utilities.LoginPreferences;

public class LoginWithGmail extends AppCompatActivity
        implements GoogleApiClient.OnConnectionFailedListener {

    private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
    private static final String TAG = "LoginActivity";
    private static final int RC_SIGN_IN = 9001;
    Button loginSub;
    LinearLayout signInButton;

    String gmailId;
    String gmailName;
    String gmailUserEmailId;
    Uri gmailUserPhoto;
    String savePassword;
    LinearLayout btnlogin;
    TextView btnsigning;
    ProgressDialog prgDialog;

    private CallbackManager callbackManager;

    private BroadcastReceiver mRegistrationBroadcastReceiver;
    private LinearLayout fbloginButton;
//    private CallbackManager callbackManager;
    private ProgressDialog mProgressDialog;
    private GoogleApiClient mGoogleApiClient;

    EditText edtEmail;

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

        checkPermission();

        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestEmail()
            .build();

        mGoogleApiClient = new GoogleApiClient.Builder(this)
            .enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
            .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
            .addApi(AppIndex.API).build();

        // Google Sign up Button
        signInButton = (LinearLayout) findViewById(R.id.sign_in_button);

        signInButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    int permissionCheck = ContextCompat.checkSelfPermission(LoginWithGmail.this, Manifest.permission.CAMERA);
                    if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
                        //showing dialog to select image

                        Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
                        signInIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                        startActivityForResult(signInIntent, RC_SIGN_IN);
                        Log.e("permission", "granted");
                    } else {
                        ActivityCompat.requestPermissions(LoginWithGmail.this,
                                new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
                                        Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA}, 1);
                    }
                } else {
                    Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
                    signInIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                    startActivityForResult(signInIntent, RC_SIGN_IN);
                }

            }
        });

    }

    public void checkPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int permissionCheck = ContextCompat.checkSelfPermission(LoginWithGmail.this,
                    Manifest.permission.CAMERA);

            if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
                //showing dialog to select image
                if (CommonMethod.isNetworkAvailable(LoginWithGmail.this)) {
                    Log.e("keshav", "Permission if part marsh");
                } else {
                    CommonMethod.showAlert("Internet Connectivity Failure", LoginWithGmail.this);
                }

                Log.e("keshav", "permission granted");
            } else {
                ActivityCompat.requestPermissions(LoginWithGmail.this,
                        new String[]{Manifest.permission.CAMERA,
                                Manifest.permission.ACCESS_FINE_LOCATION,
                                Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
//        LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
//                new IntentFilter(QuickstartPreferences.REGISTRATION_COMPLETE));
    }

    @Override
    protected void onPause() {
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReceiver);
        super.onPause();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == RC_SIGN_IN) {
            GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
            handleSignInResult(result);
        }
    }

    // TODO ADD ME

    @Override
    public void onStart() {
        super.onStart();

        OptionalPendingResult<GoogleSignInResult> opr = Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient);
        if (opr.isDone()) {
            // If the user's cached credentials are valid, the OptionalPendingResult will be "done"
            // and the GoogleSignInResult will be available instantly.
            Log.e(TAG, "Got cached sign-in");
            GoogleSignInResult result = opr.get();
            handleSignInResult(result);
        } else {
            // If the user has not previously signed in on this device or the sign-in has expired,
            // this asynchronous branch will attempt to sign in the user silently.  Cross-device
            // single sign-on will occur in this branch.
            showProgressDialog();
            opr.setResultCallback(new ResultCallback<GoogleSignInResult>() {
                @Override
                public void onResult(GoogleSignInResult googleSignInResult) {
                    hideProgressDialog();
                    handleSignInResult(googleSignInResult);
                }
            });
        }
    }

    // [START signOut]
    private void signOut() {
        Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
                new ResultCallback<Status>() {
                    @Override
                    public void onResult(Status status) {
                        // [START_EXCLUDE]
//                        updateUI(false);
                        // [END_EXCLUDE]
                    }
                });
    }
    // [END signOut]

    // [START revokeAccess]
    private void revokeAccess() {
        Auth.GoogleSignInApi.revokeAccess(mGoogleApiClient).setResultCallback(
                new ResultCallback<Status>() {
                    @Override
                    public void onResult(Status status) {
                        // [START_EXCLUDE]
//                        updateUI(false);
                        // [END_EXCLUDE]
                    }
                });
    }
    // [END revokeAccess]

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        // An unresolvable error has occurred and Google APIs (including Sign-In) will not
        // be available.
        Log.e(TAG, "onConnectionFailed:" + connectionResult);
    }

    private void showProgressDialog() {
        if (mProgressDialog == null) {
            mProgressDialog = new ProgressDialog(this);
            mProgressDialog.setMessage("Loading...");
            mProgressDialog.setIndeterminate(true);
        }
        if (LoginWithGmail.this != null && mProgressDialog != null && !mProgressDialog.equals("null"))
            mProgressDialog.show();
    }

    private void hideProgressDialog() {
        if (mProgressDialog != null && mProgressDialog.isShowing()&& !mProgressDialog.equals("null")) {
            mProgressDialog.hide();
        }
    }

    // TODO ADD ME ENd

    private void handleSignInResult(GoogleSignInResult result) {
        Log.e("&&&s", "handleSignInResult:" + result.isSuccess());
        if (result.isSuccess()) {
            // Signed in successfully, show authenticated UI.
            GoogleSignInAccount acct = result.getSignInAccount();

            gmailId = acct.getId();
            gmailName = acct.getDisplayName();
            gmailUserEmailId = acct.getEmail();
            gmailUserPhoto = acct.getPhotoUrl();

            Log.e("gmailId", "is -->" + gmailId);
            Log.e("gmailName", "is -->" + gmailName);
            Log.e("gmailUserEmailId", "is -->" + gmailUserEmailId);
            Log.e("gmailUserPhoto", "is -->" + gmailUserPhoto);

            LoginPreferences.getActiveInstance(LoginWithGmail.this).setUserName(gmailName);
            LoginPreferences.getActiveInstance(LoginWithGmail.this).setProfileImage(""+gmailUserPhoto);

            Log.e("information", "using Gmail is > " + gmailId + " " + gmailName + "" + gmailUserEmailId + "" + gmailUserPhoto);

            if (CommonMethod.isNetworkAvailable(LoginWithGmail.this)) {
                Log.e("SignUp gmail", "Hit API..........................");
                Intent i=new Intent(LoginWithGmail.this,DrawerActivity.class);
                LoginPreferences.getActiveInstance(LoginWithGmail.this).setIsLoggedIn(true);
                startActivity(i);
                finish();

                // TODO Here Registered User in own Database call Volley Retrofit2 Api ....
                new SignUpSocialFacebookAsyncTask().execute();
            } else {
                CommonMethod.showAlert("Intenet Connectivity Failure", LoginWithGmail.this);
            }

        } else {

        }
        // TODO ADD ME KESHAV Google GMail Logout
        Auth.GoogleSignInApi.signOut(mGoogleApiClient);
    }

    @Override
    public void onStop() {
        super.onStop();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        Action viewAction = Action.newAction(
                Action.TYPE_VIEW, // TODO: choose an action type.
                "Login Page", // TODO: Define a title for the content shown.
                // TODO: If you have web page content that matches this app activity's content,
                // make sure this auto-generated web page URL is correct.
                // Otherwise, set the URL to null.
                Uri.parse("http://host/path"),
                // TODO: Make sure this auto-generated app deep link URI is correct.
                Uri.parse("android-app://com.keshav.geofencing/http/host/path")
        );
        AppIndex.AppIndexApi.end(mGoogleApiClient, viewAction);
        mGoogleApiClient.disconnect();
    }

    //Todo  add new method for permission
    @TargetApi(Build.VERSION_CODES.M)
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == RC_SIGN_IN) {
            Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
            signInIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            startActivityForResult(signInIntent, RC_SIGN_IN);

        }
    }

}

**Dependency**
**Need Internet Permission**
</code>```

Working Code   see Link on  play Store
https://play.google.com/store/search?q=com.codecube.airbucks

Please Like this post if it is helpful

Title: Google Sign IN in android application

Body:
Dependency
    Need Internet Permission

Working Code   see Link on  play Store
https://play.google.com/store/search?q=com.codecube.airbucks

compile 'com.google.android.gms:play-services:8.3.0'

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <com.google.android.gms.common.SignInButton
        android:id="@+id/sign_in_button"
        android:layout_width="200dp"
        android:layout_marginTop="20dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal" />
    <Button
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:layout_gravity="center_horizontal"
        android:text="Logout"
        android:id="@+id/btn"/>
</LinearLayout>

package com.keshav.geofencing;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.OptionalPendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Arrays;

import utilities.CommonMethod;
import utilities.LoginPreferences;

public class LoginWithGmail extends AppCompatActivity
        implements GoogleApiClient.OnConnectionFailedListener {

    private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
    private static final String TAG = "LoginActivity";
    private static final int RC_SIGN_IN = 9001;
    Button loginSub;
    LinearLayout signInButton;

    String gmailId;
    String gmailName;
    String gmailUserEmailId;
    Uri gmailUserPhoto;
    String savePassword;
    LinearLayout btnlogin;
    TextView btnsigning;
    ProgressDialog prgDialog;

    private CallbackManager callbackManager;

    private BroadcastReceiver mRegistrationBroadcastReceiver;
    private LinearLayout fbloginButton;
//    private CallbackManager callbackManager;
    private ProgressDialog mProgressDialog;
    private GoogleApiClient mGoogleApiClient;

    EditText edtEmail;

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

        checkPermission();

        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestEmail()
            .build();

        mGoogleApiClient = new GoogleApiClient.Builder(this)
            .enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
            .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
            .addApi(AppIndex.API).build();

        // Google Sign up Button
        signInButton = (LinearLayout) findViewById(R.id.sign_in_button);

        signInButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    int permissionCheck = ContextCompat.checkSelfPermission(LoginWithGmail.this, Manifest.permission.CAMERA);
                    if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
                        //showing dialog to select image

                        Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
                        signInIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                        startActivityForResult(signInIntent, RC_SIGN_IN);
                        Log.e("permission", "granted");
                    } else {
                        ActivityCompat.requestPermissions(LoginWithGmail.this,
                                new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
                                        Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA}, 1);
                    }
                } else {
                    Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
                    signInIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                    startActivityForResult(signInIntent, RC_SIGN_IN);
                }

            }
        });

    }

    public void checkPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int permissionCheck = ContextCompat.checkSelfPermission(LoginWithGmail.this,
                    Manifest.permission.CAMERA);

            if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
                //showing dialog to select image
                if (CommonMethod.isNetworkAvailable(LoginWithGmail.this)) {
                    Log.e("keshav", "Permission if part marsh");
                } else {
                    CommonMethod.showAlert("Internet Connectivity Failure", LoginWithGmail.this);
                }

                Log.e("keshav", "permission granted");
            } else {
                ActivityCompat.requestPermissions(LoginWithGmail.this,
                        new String[]{Manifest.permission.CAMERA,
                                Manifest.permission.ACCESS_FINE_LOCATION,
                                Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
//        LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
//                new IntentFilter(QuickstartPreferences.REGISTRATION_COMPLETE));
    }

    @Override
    protected void onPause() {
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReceiver);
        super.onPause();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == RC_SIGN_IN) {
            GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
            handleSignInResult(result);
        }
    }

    // TODO ADD ME

    @Override
    public void onStart() {
        super.onStart();

        OptionalPendingResult<GoogleSignInResult> opr = Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient);
        if (opr.isDone()) {
            // If the user's cached credentials are valid, the OptionalPendingResult will be "done"
            // and the GoogleSignInResult will be available instantly.
            Log.e(TAG, "Got cached sign-in");
            GoogleSignInResult result = opr.get();
            handleSignInResult(result);
        } else {
            // If the user has not previously signed in on this device or the sign-in has expired,
            // this asynchronous branch will attempt to sign in the user silently.  Cross-device
            // single sign-on will occur in this branch.
            showProgressDialog();
            opr.setResultCallback(new ResultCallback<GoogleSignInResult>() {
                @Override
                public void onResult(GoogleSignInResult googleSignInResult) {
                    hideProgressDialog();
                    handleSignInResult(googleSignInResult);
                }
            });
        }
    }

    // [START signOut]
    private void signOut() {
        Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
                new ResultCallback<Status>() {
                    @Override
                    public void onResult(Status status) {
                        // [START_EXCLUDE]
//                        updateUI(false);
                        // [END_EXCLUDE]
                    }
                });
    }
    // [END signOut]

    // [START revokeAccess]
    private void revokeAccess() {
        Auth.GoogleSignInApi.revokeAccess(mGoogleApiClient).setResultCallback(
                new ResultCallback<Status>() {
                    @Override
                    public void onResult(Status status) {
                        // [START_EXCLUDE]
//                        updateUI(false);
                        // [END_EXCLUDE]
                    }
                });
    }
    // [END revokeAccess]

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        // An unresolvable error has occurred and Google APIs (including Sign-In) will not
        // be available.
        Log.e(TAG, "onConnectionFailed:" + connectionResult);
    }

    private void showProgressDialog() {
        if (mProgressDialog == null) {
            mProgressDialog = new ProgressDialog(this);
            mProgressDialog.setMessage("Loading...");
            mProgressDialog.setIndeterminate(true);
        }
        if (LoginWithGmail.this != null && mProgressDialog != null && !mProgressDialog.equals("null"))
            mProgressDialog.show();
    }

    private void hideProgressDialog() {
        if (mProgressDialog != null && mProgressDialog.isShowing()&& !mProgressDialog.equals("null")) {
            mProgressDialog.hide();
        }
    }

    // TODO ADD ME ENd

    private void handleSignInResult(GoogleSignInResult result) {
        Log.e("&&&s", "handleSignInResult:" + result.isSuccess());
        if (result.isSuccess()) {
            // Signed in successfully, show authenticated UI.
            GoogleSignInAccount acct = result.getSignInAccount();

            gmailId = acct.getId();
            gmailName = acct.getDisplayName();
            gmailUserEmailId = acct.getEmail();
            gmailUserPhoto = acct.getPhotoUrl();

            Log.e("gmailId", "is -->" + gmailId);
            Log.e("gmailName", "is -->" + gmailName);
            Log.e("gmailUserEmailId", "is -->" + gmailUserEmailId);
            Log.e("gmailUserPhoto", "is -->" + gmailUserPhoto);

            LoginPreferences.getActiveInstance(LoginWithGmail.this).setUserName(gmailName);
            LoginPreferences.getActiveInstance(LoginWithGmail.this).setProfileImage(""+gmailUserPhoto);

            Log.e("information", "using Gmail is > " + gmailId + " " + gmailName + "" + gmailUserEmailId + "" + gmailUserPhoto);

            if (CommonMethod.isNetworkAvailable(LoginWithGmail.this)) {
                Log.e("SignUp gmail", "Hit API..........................");
                Intent i=new Intent(LoginWithGmail.this,DrawerActivity.class);
                LoginPreferences.getActiveInstance(LoginWithGmail.this).setIsLoggedIn(true);
                startActivity(i);
                finish();

                // TODO Here Registered User in own Database call Volley Retrofit2 Api ....
                new SignUpSocialFacebookAsyncTask().execute();
            } else {
                CommonMethod.showAlert("Intenet Connectivity Failure", LoginWithGmail.this);
            }

        } else {

        }
        // TODO ADD ME KESHAV Google GMail Logout
        Auth.GoogleSignInApi.signOut(mGoogleApiClient);
    }

    @Override
    public void onStop() {
        super.onStop();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        Action viewAction = Action.newAction(
                Action.TYPE_VIEW, // TODO: choose an action type.
                "Login Page", // TODO: Define a title for the content shown.
                // TODO: If you have web page content that matches this app activity's content,
                // make sure this auto-generated web page URL is correct.
                // Otherwise, set the URL to null.
                Uri.parse("http://host/path"),
                // TODO: Make sure this auto-generated app deep link URI is correct.
                Uri.parse("android-app://com.keshav.geofencing/http/host/path")
        );
        AppIndex.AppIndexApi.end(mGoogleApiClient, viewAction);
        mGoogleApiClient.disconnect();
    }

    //Todo  add new method for permission
    @TargetApi(Build.VERSION_CODES.M)
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == RC_SIGN_IN) {
            Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
            signInIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            startActivityForResult(signInIntent, RC_SIGN_IN);

        }
    }

}

**Dependency**
**Need Internet Permission**

Working Code   see Link on  play Store
https://play.google.com/store/search?q=com.codecube.airbucks

Please Like this post if it is helpful


来源: stackexchange

问:
Force sorting json in PHP
How can I sort label in order:

```<code>1080p
720p
480p
360p
</code>```

I've tried all Sorting Arrays in PHP documentation and some another "User Defined" sorting functions, but no luck, it shows completely random, not in order.

My original json:

```<code>[{"file":"***","label":"360p","default":"true","type":"video\/mp4"},
{"file":"***","label":"720p","type":"video\/mp4"},
{"file":"***","label":"1080p","type":"video\/mp4"},
{"file":"***","label":"480p","type":"video\/mp4"}]
</code>```

答:
Here we are using usort to achieve desired output.

Try this code snippet here

```<code><?php

ini_set('display_errors', 1);
$json='[{"file":"***","label":"360p","default":"true","type":"video\/mp4"},
{"file":"***","label":"720p","type":"video\/mp4"},
{"file":"***","label":"1080p","type":"video\/mp4"},
{"file":"***","label":"480p","type":"video\/mp4"}]';
$array=json_decode($json,true);

usort($array, function($value1,$value2){
    $value1["label"]=rtrim($value1["label"],"p");
    $value2["label"]=rtrim($value2["label"],"p");

    return $value1["label"]<$value2["label"];
});
</code>```

ContentLicense: CC BY-SA 3.0

Title: Force sorting json in PHP

Body:
How can I sort label in order:

1080p
720p
480p
360p

I've tried all Sorting Arrays in PHP documentation and some another "User Defined" sorting functions, but no luck, it shows completely random, not in order.

My original json:

[{"file":"***","label":"360p","default":"true","type":"video\/mp4"},
{"file":"***","label":"720p","type":"video\/mp4"},
{"file":"***","label":"1080p","type":"video\/mp4"},
{"file":"***","label":"480p","type":"video\/mp4"}]

Body:
Here we are using usort to achieve desired output.

Try this code snippet here

<?php

ini_set('display_errors', 1);
$json='[{"file":"***","label":"360p","default":"true","type":"video\/mp4"},
{"file":"***","label":"720p","type":"video\/mp4"},
{"file":"***","label":"1080p","type":"video\/mp4"},
{"file":"***","label":"480p","type":"video\/mp4"}]';
$array=json_decode($json,true);

usort($array, function($value1,$value2){
    $value1["label"]=rtrim($value1["label"],"p");
    $value2["label"]=rtrim($value2["label"],"p");

    return $value1["label"]<$value2["label"];
});


问:
'Time.at(seconds)' gives different time than 'fractions(seconds/60, seconds%60)'
I am executing this code:

```<code>t = DateTime.strptime('1:00:23', '%H:%M:%S')
t1 = DateTime.strptime('2:02:40', '%H:%M:%S')
t2 = t1.to_time - t.to_time
time_new = "#{(t2/3600).to_i}" + ":" +"#{((t2/60)%60).to_i}" + ":" + "#{(t2%60).to_i}"
time_units = time_new.split(':')
</code>```

I get:

```<code>Time.at(t2).strftime("%H:%M:%S")
# => 06:32:17
"#{time_units[0]} hours, #{time_units[1]} minutes and #{time_units[2]} seconds"
# => 1 hours, 2 minutes and 17 seconds
</code>```

which are very different. Why does Time.at(seconds) add 5 hours and 30 minutes?

答:
Why does Time.at(seconds) add 5 hours and 30 minutes?

Because you are comparing apples and oranges.

DateTime.strptime returns a DateTime instance in UTC. If you don't provide a date, it uses today's date:

```<code>DateTime.strptime('01:00:23')
#=> Tue, 06 Jun 2017 01:00:23 +0000
#   ^^^^^^^^^^^^^^^^          ^^^^^
#         today                UTC
</code>```

Time.at returns a Time instance in your local time zone, based on the number of seconds since the epoch (1 January 1970):

```<code>Time.at(1 * 3600 + 23)
#=> 1970-01-01 02:00:23 +0100
#   ^^^^^^^^^^          ^^^^^
#   not today          not UTC
</code>```

Body:
I am executing this code:

t = DateTime.strptime('1:00:23', '%H:%M:%S')
t1 = DateTime.strptime('2:02:40', '%H:%M:%S')
t2 = t1.to_time - t.to_time
time_new = "#{(t2/3600).to_i}" + ":" +"#{((t2/60)%60).to_i}" + ":" + "#{(t2%60).to_i}"
time_units = time_new.split(':')

I get:

Time.at(t2).strftime("%H:%M:%S")
# => 06:32:17
"#{time_units[0]} hours, #{time_units[1]} minutes and #{time_units[2]} seconds"
# => 1 hours, 2 minutes and 17 seconds

which are very different. Why does Time.at(seconds) add 5 hours and 30 minutes?

Body:
Why does Time.at(seconds) add 5 hours and 30 minutes?

Because you are comparing apples and oranges.

DateTime.strptime returns a DateTime instance in UTC. If you don't provide a date, it uses today's date:

DateTime.strptime('01:00:23')
#=> Tue, 06 Jun 2017 01:00:23 +0000
#   ^^^^^^^^^^^^^^^^          ^^^^^
#         today                UTC

Time.at returns a Time instance in your local time zone, based on the number of seconds since the epoch (1 January 1970):

Time.at(1 * 3600 + 23)
#=> 1970-01-01 02:00:23 +0100
#   ^^^^^^^^^^          ^^^^^
#   not today          not UTC


问:
My Scannerclass doesn't scan the String - but why?
We received an exercise at college about unicode and ASCII and chars and so on. One part of the exercise is to find a way to read the users input in console that have to be a char and give back the ASCII and Unicode.

Quite easy I think, but my scanner won't scan. Because there's no .nextChar method for the scanner. I was used to use the String method (scanner.nextLine). In the next step, I turned the singlechar-String to a char with char ... = s.charAt and from there I wanted to get the hex and ASCII. Whatever I do my Scanner wont scan the String. Here's the code:

```<code>do{

    System.out.println("Geben Sie ein Zeichen ein um den dazugehoerigen ASCII- und Unicode anzuzeigen");
    input = scan.nextLine();

} while(input.length() >= 2 & input.length() < 1);

zeichen = input.charAt(0);

i = (int) zeichen;

System.out.println("Sie haben " + zeichen + " gewählt.\nDer dazugehoerige ASCII-Code ist " + i + "\nDer dazugehoerige Unicode ist " + (buffer.toString()+ Integer.toHexString(i)));
</code>```

答:
The condition is wrong, because it can never be true.
Maybe you should use this:

```<code>input.length() >= 2 || input.length() < 1
</code>```

Moreover, is your scanner reading from keyboard?
This is how it should looks:

```<code>Scanner scan = new Scanner(System.in);
</code>```

Tried this code and it works well:

```<code>String input = null;
Scanner scan = new Scanner(System.in);
do{

    System.out.println("Geben Sie ein Zeichen ein um den dazugehoerigen ASCII- und Unicode anzuzeigen");
    input = scan.nextLine();

}while(input.length() >= 2 || input.length() < 1);

    char zeichen = input.charAt(0);

    int i = (int) zeichen;
    System.out.println("Sie haben " + zeichen + " gewählt.\nDer dazugehoerige ASCII-Code ist " + i + "\nDer dazugehoerige Unicode ist " + (buffer.toString()+ Integer.toHexString(i)));
</code>```

Body:
We received an exercise at college about unicode and ASCII and chars and so on. One part of the exercise is to find a way to read the users input in console that have to be a char and give back the ASCII and Unicode.

Quite easy I think, but my scanner won't scan. Because there's no .nextChar method for the scanner. I was used to use the String method (scanner.nextLine). In the next step, I turned the singlechar-String to a char with char ... = s.charAt and from there I wanted to get the hex and ASCII. Whatever I do my Scanner wont scan the String. Here's the code:

do{

    System.out.println("Geben Sie ein Zeichen ein um den dazugehoerigen ASCII- und Unicode anzuzeigen");
    input = scan.nextLine();

} while(input.length() >= 2 & input.length() < 1);

zeichen = input.charAt(0);

i = (int) zeichen;

System.out.println("Sie haben " + zeichen + " gewählt.\nDer dazugehoerige ASCII-Code ist " + i + "\nDer dazugehoerige Unicode ist " + (buffer.toString()+ Integer.toHexString(i)));

Body:
The condition is wrong, because it can never be true.
Maybe you should use this:

input.length() >= 2 || input.length() < 1

Moreover, is your scanner reading from keyboard?
This is how it should looks:

Scanner scan = new Scanner(System.in);

Tried this code and it works well:

String input = null;
Scanner scan = new Scanner(System.in);
do{

    System.out.println("Geben Sie ein Zeichen ein um den dazugehoerigen ASCII- und Unicode anzuzeigen");
    input = scan.nextLine();

}while(input.length() >= 2 || input.length() < 1);

    char zeichen = input.charAt(0);

    int i = (int) zeichen;
    System.out.println("Sie haben " + zeichen + " gewählt.\nDer dazugehoerige ASCII-Code ist " + i + "\nDer dazugehoerige Unicode ist " + (buffer.toString()+ Integer.toHexString(i)));


问:
android - DELETE_FAILED_INTERNAL_ERROR Error while Installing
i know this question has been asked before, I did try disable instant run. That is not working.

Let me explain in detail. I did this project on desktop, it is running fine. Now i need to migrate the code into my laptop, the code able to compile and generate an apk. When installing into my device xiaomi mi4 , it failed with DELETE_FAILED_INTERNAL_ERROR even if i manually transfer the apk file into the device and install it (that only tell me fail to install, i do not know how to know the reason of failure.  I am sure this is not the device problem since i am able to install the same source apk file (if i compile it on my desktop)

Any suggestion?

答:
Try to delete the old version of the application on your device manually. Go to Settings -> Apps find your application there and delete it.
I think it may help.
If not check free memory on the device.


问:
What does this 'static' mean and why is it like that
```<code>public class tt {
static{
    System.out.println("class tt");
    }
}
</code>```

It the first time ive come across it and im wondering what it is and what it's used for

答:
Its initilizer block

A static initialization block is a normal block of code enclosed in braces, { }, and preceded by the static keyword. Here is an example:

```<code>static {
    // whatever code is needed for initialization goes here
}
</code>```

A class can have any number of static initialization blocks, and they can appear anywhere in the class body. The runtime system guarantees that static initialization blocks are called in the order that they appear in the source code.
  There is an alternative to static blocks —you can write a private static method:

```<code>class Whatever {
    public static varType myVar = initializeClassVariable();

    private static varType initializeClassVariable() {

        //initialization code goes here
    }
}
</code>```

The advantage of private static methods is that they can be reused later if you need to reinitialize the class variable.

Resource

ContentLicense: CC BY-SA 2.5

Body:
public class tt {
static{
    System.out.println("class tt");
    }
}

It the first time ive come across it and im wondering what it is and what it's used for

Body:
Its initilizer block

A static initialization block is a normal block of code enclosed in braces, { }, and preceded by the static keyword. Here is an example:

static {
    // whatever code is needed for initialization goes here
}

A class can have any number of static initialization blocks, and they can appear anywhere in the class body. The runtime system guarantees that static initialization blocks are called in the order that they appear in the source code.
  There is an alternative to static blocks —you can write a private static method:

class Whatever {
    public static varType myVar = initializeClassVariable();

    private static varType initializeClassVariable() {

        //initialization code goes here
    }
}

The advantage of private static methods is that they can be reused later if you need to reinitialize the class variable.

Resource


问:
How to push to next view controller from xib select button
I would like to push to ParcelPickUpViewController after I clicked a button in LocationDetailsTableViewCell xib. But I've written the code below and it able to run. But the result won't happen at all. Need help on this issue. Thanks.

In LocationDetailsTableViewCell.h

```<code>@property (nonatomic, strong) UINavigationController *viewController;
</code>```

In LocationDetailsTableViewCell.m

```<code>- (IBAction)selectBtn:(id)sender {

    UIStoryboard *mainStoryBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    ParcelPickUpViewController *vc = [mainStoryBoard instantiateViewControllerWithIdentifier: @ "pickUpVC"];
    [self.viewController pushViewController:vc animated: YES];
    [self.viewController setNavigationBarHidden:YES animated:YES];
}
</code>```

答:
Try This ...

```<code> - (IBAction)selectBtn:(id)sender {
    ParcelPickUpViewController *vc = [[HomeScreenVC alloc]initWithNibName:@"pickUpVC" bundle:nil];
    [self.viewController pushViewController:vc animated: YES];
    [self.viewController setNavigationBarHidden:YES animated:YES];
}
</code>```

option 2

you are created the Navigation controller not allocated the memory of your instance navigation controller, so do like

```<code> UIStoryboard *mainStoryBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
ParcelPickUpViewController *vc = [mainStoryBoard instantiateViewControllerWithIdentifier: @ "pickUpVC"];
 self.viewController = [[UINavigationController alloc] init];
[self.viewController pushViewController:vc animated: YES];
[self.viewController setNavigationBarHidden:YES animated:YES];
</code>```

if you no need the setNavigationBarHidden then use like

option 3

```<code> UIStoryboard *mainStoryBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
ParcelPickUpViewController *vc = [mainStoryBoard instantiateViewControllerWithIdentifier: @ "pickUpVC"];

[self presentViewController:vc animated:YES completion:nil];
</code>```

Body:
I would like to push to ParcelPickUpViewController after I clicked a button in LocationDetailsTableViewCell xib. But I've written the code below and it able to run. But the result won't happen at all. Need help on this issue. Thanks.

In LocationDetailsTableViewCell.h

@property (nonatomic, strong) UINavigationController *viewController;

In LocationDetailsTableViewCell.m

- (IBAction)selectBtn:(id)sender {

    UIStoryboard *mainStoryBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    ParcelPickUpViewController *vc = [mainStoryBoard instantiateViewControllerWithIdentifier: @ "pickUpVC"];
    [self.viewController pushViewController:vc animated: YES];
    [self.viewController setNavigationBarHidden:YES animated:YES];
}

Body:
Try This ...

 - (IBAction)selectBtn:(id)sender {
    ParcelPickUpViewController *vc = [[HomeScreenVC alloc]initWithNibName:@"pickUpVC" bundle:nil];
    [self.viewController pushViewController:vc animated: YES];
    [self.viewController setNavigationBarHidden:YES animated:YES];
}

option 2

you are created the Navigation controller not allocated the memory of your instance navigation controller, so do like

 UIStoryboard *mainStoryBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
ParcelPickUpViewController *vc = [mainStoryBoard instantiateViewControllerWithIdentifier: @ "pickUpVC"];
 self.viewController = [[UINavigationController alloc] init];
[self.viewController pushViewController:vc animated: YES];
[self.viewController setNavigationBarHidden:YES animated:YES];

if you no need the setNavigationBarHidden then use like

option 3

 UIStoryboard *mainStoryBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
ParcelPickUpViewController *vc = [mainStoryBoard instantiateViewControllerWithIdentifier: @ "pickUpVC"];

[self presentViewController:vc animated:YES completion:nil];


问:
GPX File does not load iOS Xcode
I am trying to simulate the locations, using a gpx file.

The file does not work in the Xcode nor does it show any error.

The file size is 1.1 MB , has a tracking data from startPoint (A) to startPoint (B).

Does that cause any issues, any suggestion?

Ref: Add GPX File to Xcode 6 Project

答:
I have met this problem recently, and found that GPSBabel can convert track GPX file into waypoint format. Here is a sample command given in the document:

gpsbabel -i gpx -f blah.gpx -x transform,wpt=trk,del -o gpx -F converted.gpx

Title: GPX File does not load iOS Xcode


问:
on click removing all elements in jquery
I have created a jquery dynamic elements showing As of now when ever I click on single elements it deletes all can anyone help me out why is this happening or is there a way it can be done if I click on 1 element it it will remove 1 only

$(document).on("click", ".rmove", function() {
  $(".compraision").remove();
  $('#company_graph').show();
  $('#comparision_graph').hide();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="comparision">
  <div class="compraision index_opt co_heading_area pos">
    <div class="co_info"><span class="float-left">AGIC</span>
      <p class="float-right">44%</p>
      Remove
    </div>
    <div class="clearfix"></div>
  </div>

  <div class="compraision index_opt co_heading_area pos">
    <div class="co_info"><span class="float-left">PSMC</span>
      <p class="float-right">44%</p>
      Remove
    </div>
    <div class="clearfix"></div>
  </div>

  <div class="compraision index_opt co_heading_area pos">
    <div class="co_info"><span class="float-left">AGTL</span>
      <p class="float-right">44%</p>
      Remove
    </div>
    <div class="clearfix"></div>
  </div>
</div></code>```

Fiddle Link

答:
Use .closest() to find element which needs to remove instead of selecting all elements

$(document).on("click", ".rmove", function() {
  $(this).closest(".compraision").remove();
  $('#company_graph').show();
  $('#comparision_graph').hide();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="comparision">
  <div class="compraision index_opt co_heading_area pos">
    <div class="co_info"><span class="float-left">AGIC</span>
      <p class="float-right">44%</p>
      Remove
    </div>
    <div class="clearfix"></div>
  </div>

  <div class="compraision index_opt co_heading_area pos">
    <div class="co_info"><span class="float-left">PSMC</span>
      <p class="float-right">44%</p>
      Remove
    </div>
    <div class="clearfix"></div>
  </div>

  <div class="compraision index_opt co_heading_area pos">
    <div class="co_info"><span class="float-left">AGTL</span>
      <p class="float-right">44%</p>
      Remove
    </div>
    <div class="clearfix"></div>
  </div>
</div></code>```

Body:
I have created a jquery dynamic elements showing As of now when ever I click on single elements it deletes all can anyone help me out why is this happening or is there a way it can be done if I click on 1 element it it will remove 1 only

$(document).on("click", ".rmove", function() {
  $(".compraision").remove();
  $('#company_graph').show();
  $('#comparision_graph').hide();
});

AGIC

44%

      Remove

PSMC

44%

      Remove

AGTL

44%

      Remove

Fiddle Link

Body:
Use .closest() to find element which needs to remove instead of selecting all elements

$(document).on("click", ".rmove", function() {
  $(this).closest(".compraision").remove();
  $('#company_graph').show();
  $('#comparision_graph').hide();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="comparision">
  <div class="compraision index_opt co_heading_area pos">
    <div class="co_info"><span class="float-left">AGIC</span>
      <p class="float-right">44%</p>
      <a class="rmove">Remove </a>
    </div>
    <div class="clearfix"></div>
  </div>

  <div class="compraision index_opt co_heading_area pos">
    <div class="co_info"><span class="float-left">PSMC</span>
      <p class="float-right">44%</p>
      <a class="rmove">Remove</a>
    </div>
    <div class="clearfix"></div>
  </div>

  <div class="compraision index_opt co_heading_area pos">
    <div class="co_info"><span class="float-left">AGTL</span>
      <p class="float-right">44%</p>
      <a class="rmove">Remove </a>
    </div>
    <div class="clearfix"></div>
  </div>
</div>


问:
Calling a function overloaded in several namespaces from inside one namespace
I have the following code snippet:

```<code>void foo(double a) {}

namespace bar_space
{
  struct Bar {};

  void foo(Bar a) {}
}
</code>```

foo(double) is a general function from a library.
I have my own namespace bar_space with my own struct, Bar. I would like to implement an overloading of foo() for Bar, thus making Bar more similar to the built-in types.

Trouble appears when I attempt to call the original foo(double) from within the namespace:

```<code>namespace bar_space
{
  void baz()
  {
    foo(5.0); // error: conversion from ‘double’ to non-scalar type ‘ssc::bar_space::Bar’ requested
  }
}
</code>```

This fails to compile on gcc on both my Fedora and Mac.

Calling

```<code>foo(5.0)
</code>```

from outside the namespace or using

```<code>namespace bar_space
{
  ::foo(5.0)
}
</code>```

works ok, but this doesnt make my new function quite as nice as I had hoped for (other developers are also working inside bar_space).

Is bar_space hiding the original function? Is there a way to make foo(5.0) callable from within bar_space without explicit scoping (::)? Any help is appreciated.

答:
In C++, there is a concept called name hiding.  Basically, a function or class name is "hidden" if there is a function/class of the same name in a nested scope.  This prevents the compiler from "seeing" the hidden name.

Section 3.3.7 of the C++ standard reads:

A name can be hidden by an explicit
  declaration of that same name in a
  nested declarative region or derived
  class (10.2)

So, to answer your question: in your example void foo(double a); is hidden by void bar_space::foo(Bar a);  So you need to use the :: scoping operator to invoke the outer function.

Body:
I have the following code snippet:

void foo(double a) {}

namespace bar_space
{
  struct Bar {};

  void foo(Bar a) {}
}

foo(double) is a general function from a library.
I have my own namespace bar_space with my own struct, Bar. I would like to implement an overloading of foo() for Bar, thus making Bar more similar to the built-in types.

Trouble appears when I attempt to call the original foo(double) from within the namespace:

namespace bar_space
{
  void baz()
  {
    foo(5.0); // error: conversion from ‘double’ to non-scalar type ‘ssc::bar_space::Bar’ requested
  }
}

This fails to compile on gcc on both my Fedora and Mac.

Calling

foo(5.0)

from outside the namespace or using

namespace bar_space
{
  ::foo(5.0)
}

works ok, but this doesnt make my new function quite as nice as I had hoped for (other developers are also working inside bar_space).

Is bar_space hiding the original function? Is there a way to make foo(5.0) callable from within bar_space without explicit scoping (::)? Any help is appreciated.


答: input.length() can not >= 2 and < 1 at the same time. Check your condition.</p>

Title: My Scannerclass doesn't scan the String - but why?


问:
JavaScript: Too much recursion?
I am learning JavaScript through Eloquent JavaScript and one of the exercises is to write a recursive function, isEven, that returns true if a number is even or false if a number is odd.

If I understood correctly, the author specifically wanted the following to be implemented:

If a number == 0, then it is even.

If a number == 1, then it is odd.

"For any number N, its evenness is the same as N-2".

But when I use the code I have below, I get an error: InternalError: too much recursion (line 3 in function isEven) … How can I fix this while still using a recursive function?

```<code>// Your code here.
function isEven(n){
  if(n==0){
    return true;
  }
  else if(n==1){
    return false;
  }
  else{
    n = n-2;
    isEven(n);
  }
}

console.log(isEven(50));
// → true
console.log(isEven(75));
// → false
console.log(isEven(-1));
// → ??
</code>```

答:
function IsEven(n){ return n%2 === 0 }

The core code is this one
return n%2 === 0

In order to increase the program's strength, it is recommended to increase non-number decisions.

Title: JavaScript: Too much recursion?

Body:
I am learning JavaScript through Eloquent JavaScript and one of the exercises is to write a recursive function, isEven, that returns true if a number is even or false if a number is odd.

If I understood correctly, the author specifically wanted the following to be implemented:

If a number == 0, then it is even.

If a number == 1, then it is odd.

"For any number N, its evenness is the same as N-2".

But when I use the code I have below, I get an error: InternalError: too much recursion (line 3 in function isEven) … How can I fix this while still using a recursive function?

// Your code here.
function isEven(n){
  if(n==0){
    return true;
  }
  else if(n==1){
    return false;
  }
  else{
    n = n-2;
    isEven(n);
  }
}

console.log(isEven(50));
// → true
console.log(isEven(75));
// → false
console.log(isEven(-1));
// → ??


答:
You could add another check, before decrementing/incrementing a value.

function isEven(n) {
    if (n == 0) {
        return true;
    }
    if (n == 1) {
        return false;
    }
    if (n > 0) {
        n = n - 2;
    } else {
        n = n + 2;
    }
    return isEven(n);
}

console.log(isEven(50));
console.log(isEven(75));
console.log(isEven(-1));```

Title: JavaScript: Too much recursion?


问:
Devexpress report designer version conflicts
I'm trying to add a DevExpress Report Desginer Wizard to my WPF project but I keep getting an error about versions. I've posted a screenshot to simplify things

This project already contains references to DevExpress controls of a different version.

  The current version is 15.2.4.

  Incorrect reference: DevExpress.Data.v14.1 14.1.8

I've updated the project files per the DevExpress Upgrade notes but this hasn't changed anything.

答:
You can try to execute "upgrade tool" from the visual studio menu
DevExpress -> Upgrade tool,
run this tool on the current solution/project, close the wpf window designer, rebuild solution/project, open your wpf window again in the designer, check that the toolbox contains WPF ReportDesigner v15.2 control and add it to the wpf window.</p>


问:
Can't use retweet twitter API from node.js - error code 34
I'm trying to figure out of a simple node.js script to retweet using Twitter API. I was able to create favorites, post status, but a retweet is not working.

```<code>// rt.js
var Twitter = require('twitter');
var config = require('./config.js');
var T = new Twitter(config);

T.post('statuses/retweet/:id', {
  id: '870436914322472960'
}, (err, data, response) => {
  if (err) {
    console.log(err)
  } else {
    console.log(`${data.text} retweet success!`)
  }
})
</code>```

The error message is :

```<code>[ { message: 'Sorry, that page does not exist', code: 34 } ]
</code>```

I'm using : twitter@1.7.0 (from npm list)

Thanks for your help.

答:
It is working using :

```<code>T.post('statuses/retweet/' + '871703983521492993', (err, data, response) => {
  if (err) {
    console.log(err)
  } else {
    console.log(`${data.text} retweet success!`)
  }
})
</code>```

OR

```<code>var id = '870659570703708160'
 T.post('statuses/retweet/' + id, (err, data, response) => {
  if (err) {
    console.log(err)
  } else {
    console.log(`${data.text} retweet success!`)
  }
})
</code>```

Body:
I'm trying to figure out of a simple node.js script to retweet using Twitter API. I was able to create favorites, post status, but a retweet is not working.

// rt.js
var Twitter = require('twitter');
var config = require('./config.js');
var T = new Twitter(config);

T.post('statuses/retweet/:id', {
  id: '870436914322472960'
}, (err, data, response) => {
  if (err) {
    console.log(err)
  } else {
    console.log(`${data.text} retweet success!`)
  }
})

The error message is :

[ { message: 'Sorry, that page does not exist', code: 34 } ]

I'm using : twitter@1.7.0 (from npm list)

Thanks for your help.

Body:
It is working using :

T.post('statuses/retweet/' + '871703983521492993', (err, data, response) => {
  if (err) {
    console.log(err)
  } else {
    console.log(`${data.text} retweet success!`)
  }
})

OR

var id = '870659570703708160'
 T.post('statuses/retweet/' + id, (err, data, response) => {
  if (err) {
    console.log(err)
  } else {
    console.log(`${data.text} retweet success!`)
  }
})


问:
Is there a python construct that is a dummy function?
Is there a python construct that corresponds to a function taking no argument, doing nothing and returning nothing ? Something similar to object None but that would be a function instead of an object ?

The context

I want to define a class where the constructor gets a function as an argument and references it to a class attribute. Upon instanciation, the user decides whether he/she wants that function to be an actual function which he/she defines him/herself or leave the default which is to call a dummy function which does nothing.

Here is what I have now :

```<code>def sayHello():
    print("hello world !")

def doNothing():
    pass

class myClass:
    def __init__(self, myFunc):
        self.doIt = myFunc

myInstance = myClass(sayHello)
myInstance.doIt()
myInstance = myClass(doNothing) # Works but requires defining function doNothing()
myInstance.doIt()
#myInstance = myClass(None) # Returns error "'NoneType' object is not callable"
myInstance.doIt()
</code>```

答:
I used the following:

```<code>a=lambda:None
a()
print a()
</code>```

The latter line prints None.

Body:
Is there a python construct that corresponds to a function taking no argument, doing nothing and returning nothing ? Something similar to object None but that would be a function instead of an object ?

The context

I want to define a class where the constructor gets a function as an argument and references it to a class attribute. Upon instanciation, the user decides whether he/she wants that function to be an actual function which he/she defines him/herself or leave the default which is to call a dummy function which does nothing.

Here is what I have now :

def sayHello():
    print("hello world !")

def doNothing():
    pass

class myClass:
    def __init__(self, myFunc):
        self.doIt = myFunc

myInstance = myClass(sayHello)
myInstance.doIt()
myInstance = myClass(doNothing) # Works but requires defining function doNothing()
myInstance.doIt()
#myInstance = myClass(None) # Returns error "'NoneType' object is not callable"
myInstance.doIt()

Body:
I used the following:

a=lambda:None
a()
print a()

The latter line prints None.


问:
How to Pass Shiny input$ID variables to dplyr function arguments
I'm trying to create a simple app that plots the mean of a continuous variable by the levels of a factor.
The user chooses one of several factors to group by and chooses the continuous variable to average. The app is supposed to display the plot using ggplot. It is easy to get this function to work outside of shiny, but I am struggling to get it to work within the application.
I know the problem is with my lack of understanding of NSE and SE, but after looking at documentation for a few hours and testing various versions this is the best I could come up with. This appears to be a common problem but I see no answers related to my problem on stack-overflow.

I use the Titanic dataset as an example
I get the following:

Warning in mean.default(input$ContVar) :   argument is not numeric or
  logical: returning NA
  In addition to the error, the mean does  not vary when the plot renders.

```<code>    library(shiny)
    library(dplyr)
    library(ggplot2)
    Titan <- as.data.frame(Titanic)
    Titan <- mutate(Titan, Freq2 = Freq +3)

    shinyApp( ui = basicPage( selectInput("FactVar", "Factor", choices = names(Titan)[1:4]), selectInput("ContVar", "Cont Variable", choices = names(Titan)[5:6]), plotOutput("surv")), server = function(input, output) {
        output$surv <- renderPlot({
            Titan %>%
            group_by_(~input$FactVar) %>%
            summarize_(MeanFreq = ~ mean(input$ContVar))%>%
            ggplot(aes_(x=~ MeanFreq, y = input$FactVar))+geom_point()
        })
    })
</code>```

答:
Here's an option, although it doesn't use dplyr.

I'm using aggregate and explicitly naming the resulting columns, so I can later call these names in ggplot.

```<code>library(shiny)
library(ggplot2)
Titan <- as.data.frame(Titanic)
Titan <- mutate(Titan, Freq2 = Freq +3)

shinyApp(

  ui = basicPage(
    selectInput("FactVar", "Factor", choices = names(Titan)[1:4]),
    selectInput("ContVar", "Cont Variable", choices = names(Titan)[5:6]),
    plotOutput("surv")),

  server = function(input, output) {
   output$surv <- renderPlot({

     MeanFreq <- aggregate(list(ContVar = Titan[, input$ContVar]),
                           list(FactVar = Titan[, input$FactVar]),
                           mean)

      ggplot(MeanFreq, aes(x = ContVar, y = FactVar)) +
        geom_point()
  })
})
</code>```

Body:
I'm trying to create a simple app that plots the mean of a continuous variable by the levels of a factor.
The user chooses one of several factors to group by and chooses the continuous variable to average. The app is supposed to display the plot using ggplot. It is easy to get this function to work outside of shiny, but I am struggling to get it to work within the application.
I know the problem is with my lack of understanding of NSE and SE, but after looking at documentation for a few hours and testing various versions this is the best I could come up with. This appears to be a common problem but I see no answers related to my problem on stack-overflow.

I use the Titanic dataset as an example
I get the following:

Warning in mean.default(input$ContVar) :   argument is not numeric or
  logical: returning NA
  In addition to the error, the mean does  not vary when the plot renders.

    library(shiny)
    library(dplyr)
    library(ggplot2)
    Titan <- as.data.frame(Titanic)
    Titan <- mutate(Titan, Freq2 = Freq +3)

    shinyApp( ui = basicPage( selectInput("FactVar", "Factor", choices = names(Titan)[1:4]), selectInput("ContVar", "Cont Variable", choices = names(Titan)[5:6]), plotOutput("surv")), server = function(input, output) {
        output$surv <- renderPlot({
            Titan %>%
            group_by_(~input$FactVar) %>%
            summarize_(MeanFreq = ~ mean(input$ContVar))%>%
            ggplot(aes_(x=~ MeanFreq, y = input$FactVar))+geom_point()
        })
    })

Body:
Here's an option, although it doesn't use dplyr.

I'm using aggregate and explicitly naming the resulting columns, so I can later call these names in ggplot.

library(shiny)
library(ggplot2)
Titan <- as.data.frame(Titanic)
Titan <- mutate(Titan, Freq2 = Freq +3)

shinyApp(

  ui = basicPage(
    selectInput("FactVar", "Factor", choices = names(Titan)[1:4]),
    selectInput("ContVar", "Cont Variable", choices = names(Titan)[5:6]),
    plotOutput("surv")),

  server = function(input, output) {
   output$surv <- renderPlot({

     MeanFreq <- aggregate(list(ContVar = Titan[, input$ContVar]),
                           list(FactVar = Titan[, input$FactVar]),
                           mean)

      ggplot(MeanFreq, aes(x = ContVar, y = FactVar)) +
        geom_point()
  })
})


答: It is a static initializer. The code inside that block runs when the JVM loads the class, which is immediately before the first time the program needs to do anything with that class (e.g. look up a static field, call a static method, instantiate an object,...).</p>

Title: What does this 'static' mean and why is it like that


问:
Using JSNLog with Angular 2
I am having trouble getting JsNlog to work with Angular 2 (latest full release). I installed JsNlog into my project (empty client web application in Visual Studio 2015) via npm and then set it up in a service but I get the error "XHR error (403 Forbidden) loading" when trying to use one of the methods.  Please can anyone tell me what I am doing wrong?

Below is the code:

My Service:

```<code>import { Injectable, Component } from '@angular/core';
import JL from 'jsnlog';

@Injectable()

export class JSLoggerService
{
 constructor()
 {
 }

log(msg: string)
{
    JL('Angular').trace(msg);
}

debug(msg: string)
{
    JL('Angular').debug(msg);
}

info(msg: string)
{
    JL('Angular').info(msg);
}

warn(msg: string)
{
    JL('Angular').warn(msg);
}

error(msg: string)
{
     JL('Angular').error(msg);
}
}
</code>```

In a component (just parts relevant to jsnlog):

```<code>import { JSLoggerService } from './shared/services/jslogger.service';

export class AppComponent
{
    constructor(private _jsnlog: JSLoggerService)
    {
      _jsnlog.log("hi");
    }
}
</code>```

Systemjs.config.js (just parts relevant to jsnlog):

```<code>          map: {
             'jsnlog': 'npm:jsnlog'
         }
</code>```

package.json (just parts relevant to jsnlog):

```<code>          dependencies: {
             'jsnlog': '2.20.1'
         }
</code>```

app.module.ts (just parts relevant to jsnlog):

```<code>          import { JSLoggerService } from './shared/services/jslogger.service';

@NgModule({
providers: [
    JSLoggerService
],
bootstrap:[ AppComponent]
})
</code>```

答:
I am the author of JSNLog. I finally got round to adding a page to jsnlog.com describing how to add JSNLog to an Angular 2+ app:
http://jsnlog.com/Documentation/HowTo/Angular2Logging</p>

Title: Using JSNLog with Angular 2

Body:
I am having trouble getting JsNlog to work with Angular 2 (latest full release). I installed JsNlog into my project (empty client web application in Visual Studio 2015) via npm and then set it up in a service but I get the error "XHR error (403 Forbidden) loading" when trying to use one of the methods.  Please can anyone tell me what I am doing wrong?

Below is the code:

My Service:

import { Injectable, Component } from '@angular/core';
import JL from 'jsnlog';

@Injectable()

export class JSLoggerService
{
 constructor()
 {
 }

log(msg: string)
{
    JL('Angular').trace(msg);
}

debug(msg: string)
{
    JL('Angular').debug(msg);
}

info(msg: string)
{
    JL('Angular').info(msg);
}

warn(msg: string)
{
    JL('Angular').warn(msg);
}

error(msg: string)
{
     JL('Angular').error(msg);
}
}

In a component (just parts relevant to jsnlog):

import { JSLoggerService } from './shared/services/jslogger.service';

export class AppComponent
{
    constructor(private _jsnlog: JSLoggerService)
    {
      _jsnlog.log("hi");
    }
}

Systemjs.config.js (just parts relevant to jsnlog):

          map: {
             'jsnlog': 'npm:jsnlog'
         }

package.json (just parts relevant to jsnlog):

          dependencies: {
             'jsnlog': '2.20.1'
         }

app.module.ts (just parts relevant to jsnlog):

          import { JSLoggerService } from './shared/services/jslogger.service';

@NgModule({
providers: [
    JSLoggerService
],
bootstrap:[ AppComponent]
})


问:
Row reordering not works in Datatable jquery plugin
I am use Datatable plugin version - 1.10.15

I want to make my table rows draggable for changing sorting orders and for that i use data tables 'Row reordering' feature but it not works

gives me an error : Uncaught TypeError: table.rowReordering is not a function

This is my work but not works

I am trying with include all related external sources

My script is

```<code>$(document).ready(function() {
  var table = $('#example').DataTable({
    "iDisplayLength": 50,
    'createdRow': function(row, data, dataIndex) {
      $(row).attr('id', 'row-' + dataIndex);
    }
  });

  table.rowReordering();
});
</code>```

Please help me to find out where I am going  wrong,by seeing my example

答:
I solved my problem using DataTables 1.10.9, RowReorder 1.0.0

Here is working fiddle with data table child rows

Simple solution is :

```<code>var table = $('#example').DataTable({
  rowReorder: true,
  "iDisplayLength": 50,
});
</code>```

DEMO

Body:
I am use Datatable plugin version - 1.10.15

I want to make my table rows draggable for changing sorting orders and for that i use data tables 'Row reordering' feature but it not works

gives me an error : Uncaught TypeError: table.rowReordering is not a function

This is my work but not works

I am trying with include all related external sources

My script is

$(document).ready(function() {
  var table = $('#example').DataTable({
    "iDisplayLength": 50,
    'createdRow': function(row, data, dataIndex) {
      $(row).attr('id', 'row-' + dataIndex);
    }
  });

  table.rowReordering();
});

Please help me to find out where I am going  wrong,by seeing my example

Body:
I solved my problem using DataTables 1.10.9, RowReorder 1.0.0

Here is working fiddle with data table child rows

Simple solution is :

var table = $('#example').DataTable({
  rowReorder: true,
  "iDisplayLength": 50,
});

DEMO


答:
It is the static initialiser of the class. When the class is loaded, the static initialiser is run. It is like the constructor, but for the class rather than for individual objects.

Multiple static initialisers can appear in a class, as well as direct initialisers for static variables. These will be combined into one initialiser in the order in which they are declared. For example, the following will print "foo" to stdout whenever the class is loaded (usually once per application).

```<code>public class Foo {

  static String a;

  static {
    a = "foo";
  }

  static String b = a;

  static {
    System.println(b);
  }

}
</code>```

Body:
public class tt {
static{
    System.out.println("class tt");
    }
}

It the first time ive come across it and im wondering what it is and what it's used for

Body:
It is the static initialiser of the class. When the class is loaded, the static initialiser is run. It is like the constructor, but for the class rather than for individual objects.

Multiple static initialisers can appear in a class, as well as direct initialisers for static variables. These will be combined into one initialiser in the order in which they are declared. For example, the following will print "foo" to stdout whenever the class is loaded (usually once per application).

public class Foo {

  static String a;

  static {
    a = "foo";
  }

  static String b = a;

  static {
    System.println(b);
  }

}


问:
Form validation not working on code igniter
it's my first time I'm asking in StackOverflow. so forgive me if I'm wrong and I'm new in PHP and CodeIgniter.
Okay, i have a page which serves to create new data.
I'm using form validation on CI, but it's not work like nothing happened to do if I'm filled the form or not. here is my code.

my controller

```<code>function __construct()
{
    parent::__construct();

    /* LOAD CORE LIBRARY */
    $this->load->library('ion_auth');
    $this->load->library('form_validation');

    /* CHECK IF USER IS AUTHENTICATED */
    if (!$this->ion_auth->logged_in())
        redirect('bunker/login', 'refresh');

    $user = $this->ion_auth->user()->row();
    if(empty($user->last_pwd_change)){
        redirect('bunker/account/renew', 'refresh');
    }

    /* THEN LOAD EVERYTHING ELSE */

    /* LOAD ALL NECESSARY HELPER */
    $this->load->helper('url');
    $this->load->helper('language');

    $this->lang->load('auth');

    // Load MongoDB library instead of native db driver if required
    $this->config->item('use_mongodb', 'ion_auth') ?
    $this->load->library('mongo_db') : $this->load->database();
    $this->form_validation->set_error_delimiters($this->config->item('error_start_delimiter', 'ion_auth'), $this->config->item('error_end_delimiter', 'ion_auth'));

    /* LOAD ALL NECESSARY MODELS */
    $this->load->model('system/company_model');
    $this->load->model('system/common_model');
    $this->load->model('website/article_model');
    $this->load->model('website/page_model');

    $this->menu['company'] = $this->company_model->getCompany();
}
function create(){
    $post = $this->input->post();
    if(!empty($post)){
        $this->form_validation->set_rules('page_id', "Page Name", 'required|numeric|xss_clean');
        $this->form_validation->set_rules('article_title', "Article Title", 'required|xss_clean');

        $this->form_validation->set_rules('article_url', "Custom URL", 'xss_clean');
        $this->form_validation->set_rules('article_status', "Publication Status", 'required|xss_clean');
        $this->form_validation->set_rules('article_excerpt', "Excerpt", 'required|min_length[250]|xss_clean');
        $this->form_validation->set_rules('article_content', "Content", 'required|min_lenght[500]|xss_clean');

        $this->form_validation->set_error_delimiters('<li>','</li>');
        if ($this->form_validation->run() == TRUE){
            if(isset($_FILES['article_file'])){
                $cover = $this->common_model->uploadPicture('uploads/images/','article_file');
                $authorId   = $this->ion_auth->get_user_id();
                $result     = $this->article_model->addArticle($this->input->post(), $authorId, $cover);
                if($result){
                    $data = array(
                        'response'  => 'success',
                        'message'   => 'Article successfully created.'
                    );
                }else{
                    $data = array(
                        'response'  => 'error',
                        'message'   => 'Failed to create article, refresh your browser and try again.'
                    );
                }
            }else{
                $data = array(
                    'response'  => 'error',
                    'message'   => 'Please provide an image for your article.'
                );
            }
        }else{
            $data['response'] = 'error';
            $data['message']  = '<ul>';
            $data['message'] .= form_error('page_id');
            $data['message'] .= form_error('article_title');
            $data['message'] .= form_error('article_url');
            $data['message'] .= form_error('article_status');
            $data['message'] .= form_error('article_excerpt');
            $data['message'] .= form_error('article_content');
            $data['message'] .= "</ul>";
        }

        header('Content-Type: application/json');
        echo json_encode($data);
        exit;
    }else{
        // DISPLAY THE PAGE
        $pages = $this->page_model->getAllPages();
        if(!$pages){
            $this->data['pages'] = NULL;
        }else{
            $this->data['pages'] = $pages;
        }

        $this->footer['status'] = "new";

        $this->load->view('common/header');
        $this->load->view('common/menu', $this->menu);
        $this->load->view('website/article/article_form', $this->data);
        $this->load->view('common/script', $this->footer);
        $this->load->view('common/common');
        $this->load->view('website/article/article_script');
        $this->load->view('common/footer');
    }
}
</code>```

view / form

```<code><div class="block-content">
  <h2><strong>Publish</strong> New Article</h2>
  <p>Use the form below to write a new article.</p>
  <form name="article-form" id="article-form" action="<?= base_url(); ?>article/create" method="POST" enctype="multipart/form-data">
    <div class="col-md-6">
      <div class="form-group">
        <label>Page:</label>
        <select name="page_id" class="form-control">
        <option value='0' selected="selected">- Choose -</option>
        <?php if($pages != NULL): ?>
        <?php foreach($pages as $page): ?>
        <option value='<?= $page->id; ?>'><?= $page->name;?></option>
        <?php endforeach; ?>
        <?php endif; ?>
        </select>
        <span class="help-block">Where do you want to publish the article.</span>
      </div>
      <div class="form-group">
        <label>Article Title:</label>
        <input name="article_title" id="article_title" type="text" placeholder="Title of your article" class="form-control">
        <span class="help-block">Provide a title for your article (by default, title will used for the custom url).</span>
      </div>
    </div>
    <div class="col-md-6">
      <div class="form-group">
        <label>Custom URL:</label>
        <input name="article_url" id="article_url" type="text" placeholder="(Optional Field)" class="form-control">
        <span class="help-block">A custom url for this article (i.e <?= base_url(); ?>my-custom-url/).</span>
      </div>
      <div class="form-group">
        <label>Status:</label>
        <select name="article_status" class="form-control">
        <option value='0'>- Choose -</option>
          <option value='draft'>Draft</option>
          <option value='publish'>Published</option>
        </select>
        <span class="help-block">Assign publication status.</span>
      </div>
    </div>
    <div class="col-md-12">
      <div class="form-group">
        <div class="input-group file">
          <input name="article_filename" type="text" placeholder="Select image for your article" class="form-control">
          <input name="article_file" type="file">
          <span class="input-group-btn">
            <button type="button" class="btn btn-primary">Browse</button>
            </span>
        </div>
      </div>
    </div>

    <div class="col-md-12">
      <div class="form-group">
        <label>Excerpt:</label>
        <textarea name="article_excerpt" id="article_excerpt" class="form-control"></textarea>
        <span class="help-block">Provide a short excerpt for your article, an excerpt may only be 1 or 2 paragraphs long.</span>
      </div>
      <div class="form-group">
        <label>Content:</label>
        <textarea name="article_content" id="article_content" class="form-control"></textarea>
        <span class="help-block">Provide the actual content of your article</span>
      </div>
      <div class="form-group">
        <label>Tags:</label>
        <input name="article_tags" id="article_tags" type="text" value="" class="form-control tagsinput">
        <span class="help-block">Provide some tag for your article</span>
      </div>
    </div>
  </form>
</div>
<button type="button" onClick="submitForm();" class="btn btn-success">
</code>```

javascript

```<code><script type="text/javascript">

/* SCRIPT FOR NEW ARTICLE */

$(document).ready(function(){
    $('#article-form').ajaxForm({
        dataType        : 'json',
        beforeSubmit    : ShowRequest,
        success         : SubmitSuccesful,
        error           : AjaxError
    });
});

function submitForm(){
    tinyMCE.triggerSave();
    $('#article-form').submit();
}

function ShowRequest(formData, jqForm, options) {
    return true;
}

function AjaxError(){
    // alertify.alert("An unknown error has occured, please refresh your browser.");
    noty({
        layout: 'topRight',
        text: 'Unknown error occured, please refresh your browser and try again.',
        type: 'warning'
    });
}

function SubmitSuccesful(responseText, statusText) {
    if(responseText.response == "success"){
        $('#article-form')[0].reset();
        noty({
            text: responseText.message,
            layout: 'topRight',
            type: 'success'
        });
        window.setTimeout(function(){location.href="<?=base_url()?>bunker/article"}, 2000);
    }else{
        noty({
            text: responseText.message,
            layout: 'topRight',
            type: 'error'
        });
    }
}

function articleRemove(articleId){
    noty({
    text: 'Are you sure you want to delete this page?',
    buttons: [
            {
                addClass: 'btn btn-danger btn-clean',
                text: 'Delete',
                onClick: function($noty) {
                    console.log("Confirmed");
                    console.log("Article ID: " + articleId);

                    $.ajax({
                        url: '<?= base_url(); ?>bunker/article/delete/' + articleId,
                        type: 'POST',
                        dataType: 'json',
                        success: function (data) {
                            console.log(data.response);
                            noty({
                                layout: 'topRight',
                                text: data.message,
                                type: 'success'
                            });
                            window.setTimeout(function(){location.href="<?=base_url()?>bunker/article"},2000);
                        },
                        failed: function(data){
                            console.log(data.response);
                            noty({
                                layout: 'topRight',
                                text: data.message,
                                type: 'error'
                            });
                        },
                        data: null
                    });
                    $noty.close();
                }
            },
            {
                addClass: 'btn btn-success btn-clean',
                text: 'Cancel',
                onClick: function($noty) {
                    $noty.close();
                }
            }
        ]
    });
}
</script>
</code>```

Sorry if my English so bad.

答:
Refactor your controller#create() method so that you do not use the post-action check. Instead, use the Form Validation Run method.

Example:

```<code>$this->form_validation->set_rules('page_id', "Page Name", 'required|numeric|xss_clean');
$this->form_validation->set_rules('article_title', "Article Title", 'required|xss_clean');

$this->form_validation->set_rules('article_url', "Custom URL", 'xss_clean');
$this->form_validation->set_rules('article_status', "Publication Status", 'required|xss_clean');
$this->form_validation->set_rules('article_excerpt', "Excerpt", 'required|min_length[250]|xss_clean');
$this->form_validation->set_rules('article_content', "Content", 'required|min_lenght[500]|xss_clean');

$this->form_validation->set_error_delimiters('<li>','</li>');
if ($this->form_validation->run() == TRUE){
    // Display Succeeded Site or something else
} else {
    // Display Failed Site or Errors or something else
}
</code>```

Body:
it's my first time I'm asking in StackOverflow. so forgive me if I'm wrong and I'm new in PHP and CodeIgniter.
Okay, i have a page which serves to create new data.
I'm using form validation on CI, but it's not work like nothing happened to do if I'm filled the form or not. here is my code.

my controller

function __construct()
{
    parent::__construct();

    /* LOAD CORE LIBRARY */
    $this->load->library('ion_auth');
    $this->load->library('form_validation');

    /* CHECK IF USER IS AUTHENTICATED */
    if (!$this->ion_auth->logged_in())
        redirect('bunker/login', 'refresh');

    $user = $this->ion_auth->user()->row();
    if(empty($user->last_pwd_change)){
        redirect('bunker/account/renew', 'refresh');
    }

    /* THEN LOAD EVERYTHING ELSE */

    /* LOAD ALL NECESSARY HELPER */
    $this->load->helper('url');
    $this->load->helper('language');

    $this->lang->load('auth');

    // Load MongoDB library instead of native db driver if required
    $this->config->item('use_mongodb', 'ion_auth') ?
    $this->load->library('mongo_db') : $this->load->database();
    $this->form_validation->set_error_delimiters($this->config->item('error_start_delimiter', 'ion_auth'), $this->config->item('error_end_delimiter', 'ion_auth'));

    /* LOAD ALL NECESSARY MODELS */
    $this->load->model('system/company_model');
    $this->load->model('system/common_model');
    $this->load->model('website/article_model');
    $this->load->model('website/page_model');

    $this->menu['company'] = $this->company_model->getCompany();
}
function create(){
    $post = $this->input->post();
    if(!empty($post)){
        $this->form_validation->set_rules('page_id', "Page Name", 'required|numeric|xss_clean');
        $this->form_validation->set_rules('article_title', "Article Title", 'required|xss_clean');

        $this->form_validation->set_rules('article_url', "Custom URL", 'xss_clean');
        $this->form_validation->set_rules('article_status', "Publication Status", 'required|xss_clean');
        $this->form_validation->set_rules('article_excerpt', "Excerpt", 'required|min_length[250]|xss_clean');
        $this->form_validation->set_rules('article_content', "Content", 'required|min_lenght[500]|xss_clean');

        $this->form_validation->set_error_delimiters('
','
');
        if ($this->form_validation->run() == TRUE){
            if(isset($_FILES['article_file'])){
                $cover = $this->common_model->uploadPicture('uploads/images/','article_file');
                $authorId   = $this->ion_auth->get_user_id();
                $result     = $this->article_model->addArticle($this->input->post(), $authorId, $cover);
                if($result){
                    $data = array(
                        'response'  => 'success',
                        'message'   => 'Article successfully created.'
                    );
                }else{
                    $data = array(
                        'response'  => 'error',
                        'message'   => 'Failed to create article, refresh your browser and try again.'
                    );
                }
            }else{
                $data = array(
                    'response'  => 'error',
                    'message'   => 'Please provide an image for your article.'
                );
            }
        }else{
            $data['response'] = 'error';
            $data['message']  = '
';
            $data['message'] .= form_error('page_id');
            $data['message'] .= form_error('article_title');
            $data['message'] .= form_error('article_url');
            $data['message'] .= form_error('article_status');
            $data['message'] .= form_error('article_excerpt');
            $data['message'] .= form_error('article_content');
            $data['message'] .= "
";
        }

        header('Content-Type: application/json');
        echo json_encode($data);
        exit;
    }else{
        // DISPLAY THE PAGE
        $pages = $this->page_model->getAllPages();
        if(!$pages){
            $this->data['pages'] = NULL;
        }else{
            $this->data['pages'] = $pages;
        }

        $this->footer['status'] = "new";

        $this->load->view('common/header');
        $this->load->view('common/menu', $this->menu);
        $this->load->view('website/article/article_form', $this->data);
        $this->load->view('common/script', $this->footer);
        $this->load->view('common/common');
        $this->load->view('website/article/article_script');
        $this->load->view('common/footer');
    }
}

view / form

Publish New Article

Use the form below to write a new article.

  <form name="article-form" id="article-form" action="<?= base_url(); ?>article/create" method="POST" enctype="multipart/form-data">

        Page:
        <select name="page_id" class="form-control">
        <option value='0' selected="selected">- Choose -</option>
        <?php if($pages != NULL): ?>
        <?php foreach($pages as $page): ?>
        <option value='<?= $page->id; ?>'><?= $page->name;?></option>
        <?php endforeach; ?>
        <?php endif; ?>
        </select>
        Where do you want to publish the article.

        Article Title:
        <input name="article_title" id="article_title" type="text" placeholder="Title of your article" class="form-control">
        Provide a title for your article (by default, title will used for the custom url).

        Custom URL:
        <input name="article_url" id="article_url" type="text" placeholder="(Optional Field)" class="form-control">
        A custom url for this article (i.e <?= base_url(); ?>my-custom-url/).

        Status:
        <select name="article_status" class="form-control">
        <option value='0'>- Choose -</option>
          <option value='draft'>Draft</option>
          <option value='publish'>Published</option>
        </select>
        Assign publication status.

          <input name="article_filename" type="text" placeholder="Select image for your article" class="form-control">
          <input name="article_file" type="file">

            <button type="button" class="btn btn-primary">Browse</button>

        Excerpt:
        <textarea name="article_excerpt" id="article_excerpt" class="form-control"></textarea>
        Provide a short excerpt for your article, an excerpt may only be 1 or 2 paragraphs long.

        Content:
        <textarea name="article_content" id="article_content" class="form-control"></textarea>
        Provide the actual content of your article

        Tags:
        <input name="article_tags" id="article_tags" type="text" value="" class="form-control tagsinput">
        Provide some tag for your article

  </form>

<button type="button" onClick="submitForm();" class="btn btn-success">

javascript

Sorry if my English so bad.

Body:
Refactor your controller#create() method so that you do not use the post-action check. Instead, use the Form Validation Run method.

Example:

$this->form_validation->set_rules('page_id', "Page Name", 'required|numeric|xss_clean');
$this->form_validation->set_rules('article_title', "Article Title", 'required|xss_clean');

$this->form_validation->set_rules('article_url', "Custom URL", 'xss_clean');
$this->form_validation->set_rules('article_status', "Publication Status", 'required|xss_clean');
$this->form_validation->set_rules('article_excerpt', "Excerpt", 'required|min_length[250]|xss_clean');
$this->form_validation->set_rules('article_content', "Content", 'required|min_lenght[500]|xss_clean');

$this->form_validation->set_error_delimiters('<li>','</li>');
if ($this->form_validation->run() == TRUE){
    // Display Succeeded Site or something else
} else {
    // Display Failed Site or Errors or something else
}


问:
how to change date at a specific time
I m very new to C# and have some issue. I've a project where I need to change the date when School starts at 0700 am only not at 1200 am. I tried something like this but doesn't work

```<code>System.TimeSpan timeDiff = TimeSpan.FromHours(.292);
DateTime presentDate = (Convert.ToDateTime(sysDateTime)).Subtract(timeDiff);
</code>```

I used this way in VB6 where I just substract .292 from current dateTime to change the date at 0700 am instead of 1200 am but dont know how do I achieve the same in C#.

答:
You can try with </p>

```<code>DateTime d = (Convert.ToDateTime(sysDateTime)).Subtract(new TimeSpan(5, 0, 0));
</code>```

Title: how to change date at a specific time

Body:
I m very new to C# and have some issue. I've a project where I need to change the date when School starts at 0700 am only not at 1200 am. I tried something like this but doesn't work

System.TimeSpan timeDiff = TimeSpan.FromHours(.292);
DateTime presentDate = (Convert.ToDateTime(sysDateTime)).Subtract(timeDiff);

I used this way in VB6 where I just substract .292 from current dateTime to change the date at 0700 am instead of 1200 am but dont know how do I achieve the same in C#.

Body:
You can try with

DateTime d = (Convert.ToDateTime(sysDateTime)).Subtract(new TimeSpan(5, 0, 0));


问:
C# MVC - Passing object with list of another object inside
I want to post an object that has list of another object inside, MVC is receiving the object as null.

MVC Post

```<code>[HttpPost]
public ActionResult Create(ObjectWithList objectWithList) {
  // While debugging objectWithList has its properties null
}
</code>```

ObjectWithList

```<code>public class ObjectWithList
{
    public List<Foo> Foo { get; set; }
    public AnotherFoo AnotherFoo { get; set; }
}
</code>```

Foo and AntoherFoo are classes with normal properties, like string, etc.

Using Postman I POST:
Headers: Content-Type as application/json
Body (raw):

```<code>{
    "Foo": [
        {
          "Name": "test"
        },
        {
         "Name": "test"
        }
   ],
   "AnotherFoo": {
       "Name": "asd",
       "Email": "asd@asd.com"
   }
}
</code>```

If I just pass "Foo" empty:

```<code>{
    "Foo": [
            {}
    ]
    ...
</code>```

it works, (fills AnotherFoo). But as soon as i try to pass something inside Foo, MVC gets everything as null.

I'm correctly naming the properties of Foo and AnotherFoo on the JSON

答:
Have you tried the [FromBody] attribute on the controller action?</p>

```<code>[HttpPost]
public ActionResult Create([FromBody]ObjectWithList objectWithList) {

}
</code>```

Body:
I want to post an object that has list of another object inside, MVC is receiving the object as null.

MVC Post

[HttpPost]
public ActionResult Create(ObjectWithList objectWithList) {
  // While debugging objectWithList has its properties null
}

ObjectWithList

public class ObjectWithList
{
    public List<Foo> Foo { get; set; }
    public AnotherFoo AnotherFoo { get; set; }
}

Foo and AntoherFoo are classes with normal properties, like string, etc.

Using Postman I POST:
Headers: Content-Type as application/json
Body (raw):

{
    "Foo": [
        {
          "Name": "test"
        },
        {
         "Name": "test"
        }
   ],
   "AnotherFoo": {
       "Name": "asd",
       "Email": "asd@asd.com"
   }
}

If I just pass "Foo" empty:

{
    "Foo": [
            {}
    ]
    ...

it works, (fills AnotherFoo). But as soon as i try to pass something inside Foo, MVC gets everything as null.

I'm correctly naming the properties of Foo and AnotherFoo on the JSON

Body:
Have you tried the [FromBody] attribute on the controller action?

[HttpPost]
public ActionResult Create([FromBody]ObjectWithList objectWithList) {

}


问:
appending text in textview not switching keyboard from uppercase to lowercase in ios
if I append some text in text view by tapping button its not switching keyboard from uppercase to lowercase. but its switching from uppercase to lowercase if I write from the keyboard. and I set </p>

```<code>textView.autocapitalizationType = .sentences
</code>```

答: I got an answer.previously I used textview.inserttext() method for insert text now if I use text view.text.append() then it switching keyboard from uppercase to lowercase. </p>

Body:
if I append some text in text view by tapping button its not switching keyboard from uppercase to lowercase. but its switching from uppercase to lowercase if I write from the keyboard. and I set

textView.autocapitalizationType = .sentences


问:
Routing with multiple Get methods in ASP.NET Web API
I am using Web Api with ASP.NET MVC, and I am very new to it. I have gone through some demo on asp.net website and I am trying to do the following.

I have 4 get methods, with the following signatures

```<code>public List<Customer> Get()
{
    // gets all customer
}

public List<Customer> GetCustomerByCurrentMonth()
{
    // gets some customer on some logic
}

public Customer GetCustomerById(string id)
{
    // gets a single customer using id
}

public Customer GetCustomerByUsername(string username)
{
    // gets a single customer using username
}
</code>```

For all the methods above I would like to have my web api somewhat like as shown below

List Get() = api/customers/

Customer GetCustomerById(string Id) = api/customers/13

List GetCustomerByCurrentMonth() = /customers/currentMonth

Customer GetCustomerByUsername(string username) = /customers/customerByUsername/yasser

I tried making changes to routing, but as I am new to it, could'nt understand much.

So, please can some one help me understand and guide me on how this should be done. Thanks

答:
I have two get methods with same or no parameters

```<code>[Route("api/ControllerName/FirstList")]
[HttpGet]
public IHttpActionResult FirstList()
{
}

[Route("api/ControllerName/SecondList")]
[HttpGet]
public IHttpActionResult SecondList()
{
}
</code>```

Just define custom routes in AppStart=>WebApiConfig.cs => under register method

```<code>config.Routes.MapHttpRoute(
       name: "GetFirstList",
       routeTemplate: "api/Controllername/FirstList"
       );
config.Routes.MapHttpRoute(
       name: "GetSecondList",
       routeTemplate: "api/Controllername/SecondList"
       );
</code>```

Body:
I am using Web Api with ASP.NET MVC, and I am very new to it. I have gone through some demo on asp.net website and I am trying to do the following.

I have 4 get methods, with the following signatures

public List<Customer> Get()
{
    // gets all customer
}

public List<Customer> GetCustomerByCurrentMonth()
{
    // gets some customer on some logic
}

public Customer GetCustomerById(string id)
{
    // gets a single customer using id
}

public Customer GetCustomerByUsername(string username)
{
    // gets a single customer using username
}

For all the methods above I would like to have my web api somewhat like as shown below

List Get() = api/customers/

Customer GetCustomerById(string Id) = api/customers/13

List GetCustomerByCurrentMonth() = /customers/currentMonth

Customer GetCustomerByUsername(string username) = /customers/customerByUsername/yasser

I tried making changes to routing, but as I am new to it, could'nt understand much.

So, please can some one help me understand and guide me on how this should be done. Thanks

Body:
I have two get methods with same or no parameters

[Route("api/ControllerName/FirstList")]
[HttpGet]
public IHttpActionResult FirstList()
{
}

[Route("api/ControllerName/SecondList")]
[HttpGet]
public IHttpActionResult SecondList()
{
}

Just define custom routes in AppStart=>WebApiConfig.cs => under register method

config.Routes.MapHttpRoute(
       name: "GetFirstList",
       routeTemplate: "api/Controllername/FirstList"
       );
config.Routes.MapHttpRoute(
       name: "GetSecondList",
       routeTemplate: "api/Controllername/SecondList"
       );