问:
Why use std::forward in concepts?
I was reading the cppreference page on Constraints and noticed this example:

```<code>// example constraint from the standard library (ranges TS)
template <class T, class U = T>
concept bool Swappable = requires(T t, U u) {
    swap(std::forward<T>(t), std::forward<U>(u));
    swap(std::forward<U>(u), std::forward<T>(t));
};
</code>```

I'm puzzled why they're using std::forward.  Some attempt to support reference types in the template parameters?  Don't we want to call swap with lvalues, and wouldn't the forward expressions be rvalues when T and U are scalar (non-reference) types?

For example, I would expect this program to fail given their Swappable implementation:

```<code>#include <utility>

// example constraint from the standard library (ranges TS)
template <class T, class U = T>
concept bool Swappable = requires(T t, U u) {
    swap(std::forward<T>(t), std::forward<U>(u));
    swap(std::forward<U>(u), std::forward<T>(t));
};

class MyType {};
void swap(MyType&, MyType&) {}

void f(Swappable& x) {}

int main()
{
    MyType x;
    f(x);
}
</code>```

Unfortunately g++ 7.1.0 gives me an internal compiler error, which doesn't shed much light on this.

Here both T and U should be MyType, and std::forward<T>(t) should return MyType&&, which can't be passed to my swap function.

Is this implementation of Swappable wrong?  Have I missed something?

答:
I'm still very new to concepts, so feel free to point out any errors I need to fix in this answer.  The answer is divided into three sections: The first directly regards the use of std::forward, the second expands on Swappable, and the third regards the internal error.

This appears to be a typo1, and likely should be requires(T&& t, U&& u).  In this case, perfect forwarding is used to ensure that the concept will be properly evaluated for both lvalue and rvalue references, guaranteeing that only lvalue references will be marked as swappable.

The full Ranges TS Swappable concept, which this is based on, is fully defined as:

```<code>template <class T>
concept bool Swappable() {
    return requires(T&& a, T&& b) {
               ranges::swap(std::forward<T>(a), std::forward<T>(b));
           };
}

template <class T, class U>
concept bool Swappable() {
    return ranges::Swappable<T>() &&
           ranges::Swappable<U>() &&
           ranges::CommonReference<const T&, const U&>() &&
           requires(T&& t, U&& u) {
               ranges::swap(std::forward<T>(t), std::forward<U>(u));
               ranges::swap(std::forward<U>(u), std::forward<T>(t));
           };
}
</code>```

The concept shown on the Constraints and concepts page is a simplified version of this, which appears to be intended as a minimal implementation of library concept Swappable.  As the full definition specifies requires(T&&, U&&), it stands to reason that this simplified version should as well.  std::forward is thus used with the expectation that t and u are forwarding references.

1: Cubbi's comment, made while I was testing code, doing research, and eating supper, confirms that it's a typo.

[The following expands on Swappable.  Feel free to skip it if this doesn't concern you.]

Note that this section only applies if Swappable is defined outside namespace std; if defined in std, as it appears to be in the draft, the two std::swap()s will automatically be considered during overload resolution, meaning no additional work is required to include them.  Thanks go to Cubbi for linking to the draft and stating that Swappable was taken directly from it.

Note, however, that the simplified form by itself isn't a full implementation of Swappable, unless using std::swap has already been specified.  [swappable.requirements/3] states that overload resolution must consider both the two std::swap() templates and any swap()s found by ADL (i.e., resolution must proceed as if the using-declaration using std::swap had been specified).  As concepts cannot contain using-declarations, a more complete Swappable might look something like this:

```<code>template<typename T, typename U = T>
concept bool ADLSwappable = requires(T&& t, U&& u) {
    swap(std::forward<T>(t), std::forward<U>(u));
    swap(std::forward<U>(u), std::forward<T>(t));
};

template<typename T, typename U = T>
concept bool StdSwappable = requires(T&& t, U&& u) {
    std::swap(std::forward<T>(t), std::forward<U>(u));
    std::swap(std::forward<U>(u), std::forward<T>(t));
};

template<typename T, typename U = T>
concept bool Swappable = ADLSwappable<T, U> || StdSwappable<T, U>;
</code>```

This expanded Swappable will allow for proper detection of parameters that fulfil the library concept, like so.

[The following regards GCC's internal error, and isn't directly related to Swappable itself.  Feel free to skip it if this doesn't concern you.]

To use this, however, f() needs a few modifications.  Rather than:

```<code>void f(Swappable& x) {}
</code>```

One of the following should instead be used:

```<code>template<typename T>
void f(T&& x) requires Swappable<T&&> {}

template<typename T>
void f(T& x) requires Swappable<T&> {}
</code>```

This is due to an interaction between GCC and concept resolution rules, and will probably be sorted out in future versions of the compiler.  Using a constraint-expression sidesteps the interaction that I believe is responsible for the internal error, making it a viable (if more verbose) stopgap measure for the time being.

The internal error appears to be caused by the way GCC handles concept resolution rules.  When it encounters this function:

```<code>void f(Swappable& x) {}
</code>```

As function concepts can be overloaded, concept resolution is performed when concept names are encountered in certain contexts (such as when used as a constrained type specifier, like Swappable is here).  Thus, GCC attempts to resolve Swappable as specified by concept resolution rule #1, in the Concept resolution section of this page:

As Swappable is used without a parameter list, it takes a single wildcard as its argument.  This wildcard can match any possible template parameter (whether type, non-type, or template), and thus is a perfect match for T.

As Swappable's second parameter doesn't correspond to an argument, its default template argument will be used, as specified after the numbered rules; I believe this to be the problem.  As T is currently (wildcard), a simplistic approach would be to temporarily instantiate U as either another wildcard or a copy of the first wildcard, and determine whether Swappable<(wildcard), (wildcard)> matches the pattern template<typename T, typename U> (it does); it could then deduce T, and use that to properly determine whether it resolves to the Swappable concept.

Instead, GCC appears to have reached a Catch-22: It can't instantiate U until it deduces T, but it can't deduce T until it determines whether this Swappable correctly resolves to the Swappable concept... which it can't do without U.  So, it needs to figure out what U is before it can figure out whether we have the right Swappable, but it needs to know whether we have the right Swappable before it can figure out what U is; faced with this unresolvable conundrum, it has an aneurysm, keels over, and dies.

Title: Why use std::forward in concepts?

Body:
I was reading the cppreference page on Constraints and noticed this example:

// example constraint from the standard library (ranges TS)
template <class T, class U = T>
concept bool Swappable = requires(T t, U u) {
    swap(std::forward<T>(t), std::forward(u));
    swap(std::forward(u), std::forward<T>(t));
};

I'm puzzled why they're using std::forward.  Some attempt to support reference types in the template parameters?  Don't we want to call swap with lvalues, and wouldn't the forward expressions be rvalues when T and U are scalar (non-reference) types?

For example, I would expect this program to fail given their Swappable implementation:

#include <utility>

// example constraint from the standard library (ranges TS)
template <class T, class U = T>
concept bool Swappable = requires(T t, U u) {
    swap(std::forward<T>(t), std::forward(u));
    swap(std::forward(u), std::forward<T>(t));
};

class MyType {};
void swap(MyType&, MyType&) {}

void f(Swappable& x) {}

int main()
{
    MyType x;
    f(x);
}

Unfortunately g++ 7.1.0 gives me an internal compiler error, which doesn't shed much light on this.

Here both T and U should be MyType, and std::forward<T>(t) should return MyType&&, which can't be passed to my swap function.

Is this implementation of Swappable wrong?  Have I missed something?

Body:
I'm still very new to concepts, so feel free to point out any errors I need to fix in this answer.  The answer is divided into three sections: The first directly regards the use of std::forward, the second expands on Swappable, and the third regards the internal error.

This appears to be a typo1, and likely should be requires(T&& t, U&& u).  In this case, perfect forwarding is used to ensure that the concept will be properly evaluated for both lvalue and rvalue references, guaranteeing that only lvalue references will be marked as swappable.

The full Ranges TS Swappable concept, which this is based on, is fully defined as:

template <class T>
concept bool Swappable() {
    return requires(T&& a, T&& b) {
               ranges::swap(std::forward<T>(a), std::forward<T>(b));
           };
}

template <class T, class U>
concept bool Swappable() {
    return ranges::Swappable<T>() &&
           ranges::Swappable<U>() &&
           ranges::CommonReference<const T&, const U&>() &&
           requires(T&& t, U&& u) {
               ranges::swap(std::forward<T>(t), std::forward<U>(u));
               ranges::swap(std::forward<U>(u), std::forward<T>(t));
           };
}

The concept shown on the Constraints and concepts page is a simplified version of this, which appears to be intended as a minimal implementation of library concept Swappable.  As the full definition specifies requires(T&&, U&&), it stands to reason that this simplified version should as well.  std::forward is thus used with the expectation that t and u are forwarding references.

1: Cubbi's comment, made while I was testing code, doing research, and eating supper, confirms that it's a typo.

[The following expands on Swappable.  Feel free to skip it if this doesn't concern you.]

Note that this section only applies if Swappable is defined outside namespace std; if defined in std, as it appears to be in the draft, the two std::swap()s will automatically be considered during overload resolution, meaning no additional work is required to include them.  Thanks go to Cubbi for linking to the draft and stating that Swappable was taken directly from it.

Note, however, that the simplified form by itself isn't a full implementation of Swappable, unless using std::swap has already been specified.  [swappable.requirements/3] states that overload resolution must consider both the two std::swap() templates and any swap()s found by ADL (i.e., resolution must proceed as if the using-declaration using std::swap had been specified).  As concepts cannot contain using-declarations, a more complete Swappable might look something like this:

template<typename T, typename U = T>
concept bool ADLSwappable = requires(T&& t, U&& u) {
    swap(std::forward<T>(t), std::forward<U>(u));
    swap(std::forward<U>(u), std::forward<T>(t));
};

template<typename T, typename U = T>
concept bool StdSwappable = requires(T&& t, U&& u) {
    std::swap(std::forward<T>(t), std::forward<U>(u));
    std::swap(std::forward<U>(u), std::forward<T>(t));
};

template<typename T, typename U = T>
concept bool Swappable = ADLSwappable<T, U> || StdSwappable<T, U>;

This expanded Swappable will allow for proper detection of parameters that fulfil the library concept, like so.

[The following regards GCC's internal error, and isn't directly related to Swappable itself.  Feel free to skip it if this doesn't concern you.]

To use this, however, f() needs a few modifications.  Rather than:

void f(Swappable& x) {}

One of the following should instead be used:

template<typename T>
void f(T&& x) requires Swappable<T&&> {}

template<typename T>
void f(T& x) requires Swappable<T&> {}

This is due to an interaction between GCC and concept resolution rules, and will probably be sorted out in future versions of the compiler.  Using a constraint-expression sidesteps the interaction that I believe is responsible for the internal error, making it a viable (if more verbose) stopgap measure for the time being.

The internal error appears to be caused by the way GCC handles concept resolution rules.  When it encounters this function:

void f(Swappable& x) {}

As function concepts can be overloaded, concept resolution is performed when concept names are encountered in certain contexts (such as when used as a constrained type specifier, like Swappable is here).  Thus, GCC attempts to resolve Swappable as specified by concept resolution rule #1, in the Concept resolution section of this page:

As Swappable is used without a parameter list, it takes a single wildcard as its argument.  This wildcard can match any possible template parameter (whether type, non-type, or template), and thus is a perfect match for T.

As Swappable's second parameter doesn't correspond to an argument, its default template argument will be used, as specified after the numbered rules; I believe this to be the problem.  As T is currently (wildcard), a simplistic approach would be to temporarily instantiate U as either another wildcard or a copy of the first wildcard, and determine whether Swappable<(wildcard), (wildcard)> matches the pattern template<typename T, typename U> (it does); it could then deduce T, and use that to properly determine whether it resolves to the Swappable concept.

Instead, GCC appears to have reached a Catch-22: It can't instantiate U until it deduces T, but it can't deduce T until it determines whether this Swappable correctly resolves to the Swappable concept... which it can't do without U.  So, it needs to figure out what U is before it can figure out whether we have the right Swappable, but it needs to know whether we have the right Swappable before it can figure out what U is; faced with this unresolvable conundrum, it has an aneurysm, keels over, and dies.


来源: stackexchange

问:
Android login activity only shows Google sign-in upon launch
The first time opening a newly installed version of my app shows a custom login/register field and a Google sign-in button beneath the custom option. After logging in, I am brought to the MainActivity without an issue, however, when I try to re-launch the app, it always prompts me with the Google sign-in that I cannot get past without either logging in with a Google account or uninstalling and reinstalling the app.

LoginActivity.java

```<code>public class LoginActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener, OnClickListener {

private static final String TAG = "LoginActivity";
private static final int RC_SIGN_IN = 9001;

    // Id to identity READ_CONTACTS permission request.
private static final int REQUEST_READ_CONTACTS = 0;

// UI references.
private EditText mEmailView;
private EditText mPasswordView;
private View mProgressView;
private View mLoginFormView;

private Button mEmailSignInButton;
private Button mEmailRegisterButton;
private SignInButton googleSignInButton;

// Firebase Auth
private FirebaseAuth fbAuth;
private FirebaseUser fbu;

// Firebase DB
private FirebaseDatabase database;
private DatabaseReference myUsers;

// Google
private GoogleApiClient mGoogleApiClient;
private GoogleSignInOptions gso;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);
    // Set up the login form.
    mEmailView = (EditText) findViewById(R.id.email_edittext);
    mPasswordView = (EditText) findViewById(R.id.password_edittext);

    googleSignInButton= (SignInButton) findViewById(R.id.google_sign_in_button);
    googleSignInButton.setSize(SignInButton.SIZE_STANDARD);
    googleSignInButton.setOnClickListener(this);

    mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
            if (id == R.id.login || id == EditorInfo.IME_NULL) {
                attemptEmailLogin();
                return true;
            }
            return false;
        }
    });

    mEmailRegisterButton = (Button) findViewById(R.id.register_button);
    mEmailRegisterButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            attemptEmailRegister();
        }
    });

    mEmailSignInButton = (Button) findViewById(R.id.sign_in_button);
    mEmailSignInButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            attemptEmailLogin();
        }
    });

    mLoginFormView = findViewById(R.id.login_form);
    mProgressView = findViewById(R.id.login_progress);

    // Google sign in
    gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestIdToken(getString(R.string.default_web_client_id))
            .requestEmail()
            .build();
    buildGoogleApiClient();

    // Initialize FirebaseAuth instance
    fbAuth = FirebaseAuth.getInstance();
    fbu = fbAuth.getCurrentUser();
    if (fbu != null) {
        Intent signInIntent = Auth
                .GoogleSignInApi
                .getSignInIntent(mGoogleApiClient);
        startActivityForResult(signInIntent, RC_SIGN_IN);
        finish();
    } else {
        Log.d(TAG, "No user is logged in");
    }

    // FireBase DB
    database = FirebaseDatabase.getInstance();
    myUsers = database.getReference("users");
}

@Override
protected void onStart() {
    super.onStart();
    fbu = fbAuth.getCurrentUser();
    if (fbu != null) {
        Intent signInIntent = Auth
                .GoogleSignInApi
                .getSignInIntent(mGoogleApiClient);
        startActivityForResult(signInIntent, RC_SIGN_IN);
        finish();
    } else {
        Log.d(TAG, "No user is logged in");
    }
}

protected synchronized void buildGoogleApiClient() {
    Log.i(TAG, "Building GoogleApiClient");
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .enableAutoManage(this /* FragmentActivity (AppCompatActivity) */, this /* OnConnectionFailedListener */)
            .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
            .build();
    mGoogleApiClient.connect();
}

private void attemptEmailRegister() {

    // Reset errors.
    mEmailView.setError(null);
    mPasswordView.setError(null);

    // Store values at the time of the login attempt.
    String email = mEmailView.getText().toString();
    String password = mPasswordView.getText().toString();

    boolean cancel = false;
    View focusView = null;

    // Check for a valid password, if the user entered one.
    if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
        mPasswordView.setError(getString(R.string.error_invalid_password));
        focusView = mPasswordView;
        cancel = true;
    }

    // Check for a valid email address.
    if (TextUtils.isEmpty(email)) {
        mEmailView.setError(getString(R.string.error_field_required));
        focusView = mEmailView;
        cancel = true;
    } else if (!isEmailValid(email)) {
        mEmailView.setError(getString(R.string.error_invalid_email));
        focusView = mEmailView;
        cancel = true;
    }

    if (cancel) {
        // There was an error; don't attempt register and focus the first
        // form field with an error.
        focusView.requestFocus();
    } else {
        // perform the user register attempt.
        showProgress(true);
        fbAuth.createUserWithEmailAndPassword(email, password)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()) {
                            // Register success
                            Log.d(TAG, "createUserWithEmail:success");
                            FirebaseUser user = fbAuth.getCurrentUser();
                            onAuthSuccess(user);
                        } else {
                            // If register fails, display a message to the user.
                            Log.w(TAG, "createUserWithEmail:failure", task.getException());
                            Toast.makeText(LoginActivity.this, "Registration authentication failed.",
                                    Toast.LENGTH_SHORT).show();
                            Intent startMainActivity = new Intent(LoginActivity.this, LoginActivity.class);
                            startActivity(startMainActivity);
                            finish();
                        }
                    }
                });
    }

}

private void attemptEmailLogin(){

    // Reset errors.
    mEmailView.setError(null);
    mPasswordView.setError(null);

    // Store values at the time of the login attempt.
    String email = mEmailView.getText().toString();
    String password = mPasswordView.getText().toString();

    boolean cancel = false;
    View focusView = null;

    // Check for a valid password, if the user entered one.
    if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
        mPasswordView.setError(getString(R.string.error_invalid_password));
        focusView = mPasswordView;
        cancel = true;
    }

    // Check for a valid email address.
    if (TextUtils.isEmpty(email)) {
        mEmailView.setError(getString(R.string.error_field_required));
        focusView = mEmailView;
        cancel = true;
    } else if (!isEmailValid(email)) {
        mEmailView.setError(getString(R.string.error_invalid_email));
        focusView = mEmailView;
        cancel = true;
    }

    if (cancel) {
        // There was an error; don't attempt register and focus the first
        // form field with an error.
        focusView.requestFocus();
    } else {
        // perform the user register attempt.
        showProgress(true);
        fbAuth.signInWithEmailAndPassword(email, password)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()) {
                            // Sign in success
                            Log.d(TAG, "signInWithEmail:success");
                            FirebaseUser user = fbAuth.getCurrentUser();
                            Intent startMainActivity = new Intent(LoginActivity.this, MainActivity.class);
                            startActivity(startMainActivity);
                        } else {
                            // If sign in fails, display a message to the user.
                            Log.w(TAG, "signInWithEmail:failure", task.getException());
                            Toast.makeText(LoginActivity.this, "Login authentication failed.",
                                    Toast.LENGTH_SHORT).show();
                            Intent startMainActivity = new Intent(LoginActivity.this, LoginActivity.class);
                            startActivity(startMainActivity);
                        }

                    }
                });
    }

}

private void onAuthSuccess(FirebaseUser user) {
    String username = usernameFromEmail(user.getEmail());
    String[] names = firstAndLastNameFromDisplayName(user.getDisplayName());

    // Write new user
    writeNewUser(user.getUid(), names, username, user.getEmail());

    // Go to MainActivity
    Intent startMainActivity = new Intent(LoginActivity.this, MainActivity.class);
    startActivity(startMainActivity);
    finish();
}
private String usernameFromEmail(String email) {
    if (email.contains("@")) {
        return email.split("@")[0];
    } else {
        return email;
    }
}
private String[] firstAndLastNameFromDisplayName(String fullName) {
    if (fullName != null) {
        if (fullName.contains(" ")) {
            return new String[]{fullName.split(" ")[0], fullName.split(" ")[1]};
        } else {
            return new String[]{fullName, "emptyLastName"};
        }
    } else {
        return new String[]{"defaultfirst","defaultlast"};
    }
}
private void writeNewUser(String userId, String[] names, String username, String email) {
    User user = new User(username,names[0],names[1], email);
    myUsers.child("users").child(userId).setValue(user);
}

private boolean isEmailValid(String email) {
    return email.contains("@");
}

private boolean isPasswordValid(String password) {
    return (password.length() > 4) && !password.contains("\\");
}

/**
 * Shows the progress UI and hides the login form.
 */
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
private void showProgress(final boolean show) {
    // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
    // for very easy animations. If available, use these APIs to fade-in
    // the progress spinner.
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
        int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);

        mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
        mLoginFormView.animate().setDuration(shortAnimTime).alpha(
                show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
            }
        });

        mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
        mProgressView.animate().setDuration(shortAnimTime).alpha(
                show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            }
        });
    } else {
        // The ViewPropertyAnimator APIs are not available, so simply show
        // and hide the relevant UI components.
        mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
        mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
    }
}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
    Log.e(TAG, "onConnectionFailed called");
}

@Override
public void onClick(View view) {
    switch (view.getId()) {
        case R.id.google_sign_in_button:
            Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
            startActivityForResult(signInIntent, RC_SIGN_IN);
            break;
    }
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
    if (requestCode == RC_SIGN_IN) {
        GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
        handleSignInResult(result);
    }
}

private void handleSignInResult(GoogleSignInResult result) {
    Log.d(TAG, "handleSignInResult:" + result.isSuccess());
    if (result.isSuccess()) {
        // Signed in successfully, show authenticated UI.
        GoogleSignInAccount account = result.getSignInAccount();
        firebaseAuthWithGoogle(account);
        Log.d(TAG, "google handleSignInResult: success!");
        Intent startMainActivity = new Intent(LoginActivity.this, MainActivity.class);
        startActivity(startMainActivity);
    } else {
        // Signed out, show unauthenticated
        Toast.makeText(LoginActivity.this, "HandleSignInResult malfunction. Try again.",
                Toast.LENGTH_SHORT).show();
        Intent startMainActivity = new Intent(LoginActivity.this, LoginActivity.class);
        startActivity(startMainActivity);
    }
}

private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
    Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());

    AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
    fbAuth.signInWithCredential(credential)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if (task.isSuccessful()) {
                        // Sign in success, update UI with the signed-in user's information
                        Log.d(TAG, "signInWithCredential:success");
                        FirebaseUser user = fbAuth.getCurrentUser();
                    } else {
                        // If sign in fails, display a message to the user.
                        Log.w(TAG, "signInWithCredential:failure", task.getException());
                        Toast.makeText(LoginActivity.this, "Authentication failed.",
                                Toast.LENGTH_SHORT).show();
                        Intent startMainActivity = new Intent(LoginActivity.this, LoginActivity.class);
                        startActivity(startMainActivity);
                    }

                }
            });
}
}
</code>```

答:
It's actually quite a simple fix. I was misled by the boilerplate Firebase structure, when the logic doesn't exactly apply to my instance:

```<code>FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
    // User is signed in
} else {
    // No user is signed in
}
</code>```

But LoginActivity.java only really needs to prompt when the button is pressed, not onCreate() or onStart(). Here's the fix:

```<code>// Initialize FirebaseAuth instance
        fbAuth = FirebaseAuth.getInstance();
        fbu = fbAuth.getCurrentUser();
        if (fbu == null) {
            Log.d(TAG, "No user is logged in");
//            Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
//            startActivityForResult(signInIntent, RC_SIGN_IN);
        } else {
            Log.d(TAG, "User is already logged in");
            Intent i = new Intent(LoginActivity.this, MainActivity.class);
            startActivity(i);
            finish();
        }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
The first time opening a newly installed version of my app shows a custom login/register field and a Google sign-in button beneath the custom option. After logging in, I am brought to the MainActivity without an issue, however, when I try to re-launch the app, it always prompts me with the Google sign-in that I cannot get past without either logging in with a Google account or uninstalling and reinstalling the app.

LoginActivity.java

public class LoginActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener, OnClickListener {

private static final String TAG = "LoginActivity";
private static final int RC_SIGN_IN = 9001;

    // Id to identity READ_CONTACTS permission request.
private static final int REQUEST_READ_CONTACTS = 0;

// UI references.
private EditText mEmailView;
private EditText mPasswordView;
private View mProgressView;
private View mLoginFormView;

private Button mEmailSignInButton;
private Button mEmailRegisterButton;
private SignInButton googleSignInButton;

// Firebase Auth
private FirebaseAuth fbAuth;
private FirebaseUser fbu;

// Firebase DB
private FirebaseDatabase database;
private DatabaseReference myUsers;

// Google
private GoogleApiClient mGoogleApiClient;
private GoogleSignInOptions gso;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);
    // Set up the login form.
    mEmailView = (EditText) findViewById(R.id.email_edittext);
    mPasswordView = (EditText) findViewById(R.id.password_edittext);

    googleSignInButton= (SignInButton) findViewById(R.id.google_sign_in_button);
    googleSignInButton.setSize(SignInButton.SIZE_STANDARD);
    googleSignInButton.setOnClickListener(this);

    mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
            if (id == R.id.login || id == EditorInfo.IME_NULL) {
                attemptEmailLogin();
                return true;
            }
            return false;
        }
    });

    mEmailRegisterButton = (Button) findViewById(R.id.register_button);
    mEmailRegisterButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            attemptEmailRegister();
        }
    });

    mEmailSignInButton = (Button) findViewById(R.id.sign_in_button);
    mEmailSignInButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            attemptEmailLogin();
        }
    });

    mLoginFormView = findViewById(R.id.login_form);
    mProgressView = findViewById(R.id.login_progress);

    // Google sign in
    gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestIdToken(getString(R.string.default_web_client_id))
            .requestEmail()
            .build();
    buildGoogleApiClient();

    // Initialize FirebaseAuth instance
    fbAuth = FirebaseAuth.getInstance();
    fbu = fbAuth.getCurrentUser();
    if (fbu != null) {
        Intent signInIntent = Auth
                .GoogleSignInApi
                .getSignInIntent(mGoogleApiClient);
        startActivityForResult(signInIntent, RC_SIGN_IN);
        finish();
    } else {
        Log.d(TAG, "No user is logged in");
    }

    // FireBase DB
    database = FirebaseDatabase.getInstance();
    myUsers = database.getReference("users");
}

@Override
protected void onStart() {
    super.onStart();
    fbu = fbAuth.getCurrentUser();
    if (fbu != null) {
        Intent signInIntent = Auth
                .GoogleSignInApi
                .getSignInIntent(mGoogleApiClient);
        startActivityForResult(signInIntent, RC_SIGN_IN);
        finish();
    } else {
        Log.d(TAG, "No user is logged in");
    }
}

protected synchronized void buildGoogleApiClient() {
    Log.i(TAG, "Building GoogleApiClient");
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .enableAutoManage(this /* FragmentActivity (AppCompatActivity) */, this /* OnConnectionFailedListener */)
            .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
            .build();
    mGoogleApiClient.connect();
}

private void attemptEmailRegister() {

    // Reset errors.
    mEmailView.setError(null);
    mPasswordView.setError(null);

    // Store values at the time of the login attempt.
    String email = mEmailView.getText().toString();
    String password = mPasswordView.getText().toString();

    boolean cancel = false;
    View focusView = null;

    // Check for a valid password, if the user entered one.
    if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
        mPasswordView.setError(getString(R.string.error_invalid_password));
        focusView = mPasswordView;
        cancel = true;
    }

    // Check for a valid email address.
    if (TextUtils.isEmpty(email)) {
        mEmailView.setError(getString(R.string.error_field_required));
        focusView = mEmailView;
        cancel = true;
    } else if (!isEmailValid(email)) {
        mEmailView.setError(getString(R.string.error_invalid_email));
        focusView = mEmailView;
        cancel = true;
    }

    if (cancel) {
        // There was an error; don't attempt register and focus the first
        // form field with an error.
        focusView.requestFocus();
    } else {
        // perform the user register attempt.
        showProgress(true);
        fbAuth.createUserWithEmailAndPassword(email, password)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()) {
                            // Register success
                            Log.d(TAG, "createUserWithEmail:success");
                            FirebaseUser user = fbAuth.getCurrentUser();
                            onAuthSuccess(user);
                        } else {
                            // If register fails, display a message to the user.
                            Log.w(TAG, "createUserWithEmail:failure", task.getException());
                            Toast.makeText(LoginActivity.this, "Registration authentication failed.",
                                    Toast.LENGTH_SHORT).show();
                            Intent startMainActivity = new Intent(LoginActivity.this, LoginActivity.class);
                            startActivity(startMainActivity);
                            finish();
                        }
                    }
                });
    }

}

private void attemptEmailLogin(){

    // Reset errors.
    mEmailView.setError(null);
    mPasswordView.setError(null);

    // Store values at the time of the login attempt.
    String email = mEmailView.getText().toString();
    String password = mPasswordView.getText().toString();

    boolean cancel = false;
    View focusView = null;

    // Check for a valid password, if the user entered one.
    if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
        mPasswordView.setError(getString(R.string.error_invalid_password));
        focusView = mPasswordView;
        cancel = true;
    }

    // Check for a valid email address.
    if (TextUtils.isEmpty(email)) {
        mEmailView.setError(getString(R.string.error_field_required));
        focusView = mEmailView;
        cancel = true;
    } else if (!isEmailValid(email)) {
        mEmailView.setError(getString(R.string.error_invalid_email));
        focusView = mEmailView;
        cancel = true;
    }

    if (cancel) {
        // There was an error; don't attempt register and focus the first
        // form field with an error.
        focusView.requestFocus();
    } else {
        // perform the user register attempt.
        showProgress(true);
        fbAuth.signInWithEmailAndPassword(email, password)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()) {
                            // Sign in success
                            Log.d(TAG, "signInWithEmail:success");
                            FirebaseUser user = fbAuth.getCurrentUser();
                            Intent startMainActivity = new Intent(LoginActivity.this, MainActivity.class);
                            startActivity(startMainActivity);
                        } else {
                            // If sign in fails, display a message to the user.
                            Log.w(TAG, "signInWithEmail:failure", task.getException());
                            Toast.makeText(LoginActivity.this, "Login authentication failed.",
                                    Toast.LENGTH_SHORT).show();
                            Intent startMainActivity = new Intent(LoginActivity.this, LoginActivity.class);
                            startActivity(startMainActivity);
                        }

                    }
                });
    }

}

private void onAuthSuccess(FirebaseUser user) {
    String username = usernameFromEmail(user.getEmail());
    String[] names = firstAndLastNameFromDisplayName(user.getDisplayName());

    // Write new user
    writeNewUser(user.getUid(), names, username, user.getEmail());

    // Go to MainActivity
    Intent startMainActivity = new Intent(LoginActivity.this, MainActivity.class);
    startActivity(startMainActivity);
    finish();
}
private String usernameFromEmail(String email) {
    if (email.contains("@")) {
        return email.split("@")[0];
    } else {
        return email;
    }
}
private String[] firstAndLastNameFromDisplayName(String fullName) {
    if (fullName != null) {
        if (fullName.contains(" ")) {
            return new String[]{fullName.split(" ")[0], fullName.split(" ")[1]};
        } else {
            return new String[]{fullName, "emptyLastName"};
        }
    } else {
        return new String[]{"defaultfirst","defaultlast"};
    }
}
private void writeNewUser(String userId, String[] names, String username, String email) {
    User user = new User(username,names[0],names[1], email);
    myUsers.child("users").child(userId).setValue(user);
}

private boolean isEmailValid(String email) {
    return email.contains("@");
}

private boolean isPasswordValid(String password) {
    return (password.length() > 4) && !password.contains("\\");
}

/**
 * Shows the progress UI and hides the login form.
 */
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
private void showProgress(final boolean show) {
    // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
    // for very easy animations. If available, use these APIs to fade-in
    // the progress spinner.
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
        int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);

        mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
        mLoginFormView.animate().setDuration(shortAnimTime).alpha(
                show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
            }
        });

        mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
        mProgressView.animate().setDuration(shortAnimTime).alpha(
                show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            }
        });
    } else {
        // The ViewPropertyAnimator APIs are not available, so simply show
        // and hide the relevant UI components.
        mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
        mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
    }
}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
    Log.e(TAG, "onConnectionFailed called");
}

@Override
public void onClick(View view) {
    switch (view.getId()) {
        case R.id.google_sign_in_button:
            Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
            startActivityForResult(signInIntent, RC_SIGN_IN);
            break;
    }
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
    if (requestCode == RC_SIGN_IN) {
        GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
        handleSignInResult(result);
    }
}

private void handleSignInResult(GoogleSignInResult result) {
    Log.d(TAG, "handleSignInResult:" + result.isSuccess());
    if (result.isSuccess()) {
        // Signed in successfully, show authenticated UI.
        GoogleSignInAccount account = result.getSignInAccount();
        firebaseAuthWithGoogle(account);
        Log.d(TAG, "google handleSignInResult: success!");
        Intent startMainActivity = new Intent(LoginActivity.this, MainActivity.class);
        startActivity(startMainActivity);
    } else {
        // Signed out, show unauthenticated
        Toast.makeText(LoginActivity.this, "HandleSignInResult malfunction. Try again.",
                Toast.LENGTH_SHORT).show();
        Intent startMainActivity = new Intent(LoginActivity.this, LoginActivity.class);
        startActivity(startMainActivity);
    }
}

private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
    Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());

    AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
    fbAuth.signInWithCredential(credential)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if (task.isSuccessful()) {
                        // Sign in success, update UI with the signed-in user's information
                        Log.d(TAG, "signInWithCredential:success");
                        FirebaseUser user = fbAuth.getCurrentUser();
                    } else {
                        // If sign in fails, display a message to the user.
                        Log.w(TAG, "signInWithCredential:failure", task.getException());
                        Toast.makeText(LoginActivity.this, "Authentication failed.",
                                Toast.LENGTH_SHORT).show();
                        Intent startMainActivity = new Intent(LoginActivity.this, LoginActivity.class);
                        startActivity(startMainActivity);
                    }

                }
            });
}
}

Body:
It's actually quite a simple fix. I was misled by the boilerplate Firebase structure, when the logic doesn't exactly apply to my instance:

FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
    // User is signed in
} else {
    // No user is signed in
}

But LoginActivity.java only really needs to prompt when the button is pressed, not onCreate() or onStart(). Here's the fix:

// Initialize FirebaseAuth instance
        fbAuth = FirebaseAuth.getInstance();
        fbu = fbAuth.getCurrentUser();
        if (fbu == null) {
            Log.d(TAG, "No user is logged in");
//            Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
//            startActivityForResult(signInIntent, RC_SIGN_IN);
        } else {
            Log.d(TAG, "User is already logged in");
            Intent i = new Intent(LoginActivity.this, MainActivity.class);
            startActivity(i);
            finish();
        }


问:
Looping over a huge list, check string equal to true
I have a requirement as below:

```<code>List<User> userList = listOfUsers(); // Morethan 50,000 users
</code>```

I need to find a user status from the list of users. if any one of the users is active then break the loop.

what is the efficient way to handle this in java ?

答:
One way to accelerate the search (Without Using Java 8) is by searching both directions in the ArrayList (i.e from the beginning to the middle, and from the end to the middle) at the same time via using multi-threading, I created this example and tested it against 1 million object/user to check if any of them is active (Note that I made only one user active and put him in the middle to see the longest time the search may take).

```<code>import java.util.ArrayList;

public class User {
    // some fields to test
    String name;
    boolean active;
    //volatile means all writes up to the volatile variable
    //from other any thread are now visible to all other threads.
    //so they can share working on that variable
    static volatile boolean finishFirst = false; // to announce first thread finish
    static volatile boolean finishSecond = false; // to announce second thread finish
    static volatile boolean found = false; // // to announce if an active user found

    /**
     * Simple Constructor
     * @param name
     * @param active
     */
    public User(String name, boolean active){
        this.name = name;
        this.active = active;
    }

   public static void main(String[] args) {

     // create an ArrayList of type User
     ArrayList<User> list = new ArrayList<User>();

     // populate it with 1 MILLION user!!
     int i=0;
     for(;i<1000000; i++){
         // make only the one in the very middle active to prolong the search to max
         if(i==500000){
             list.add(new User(String.valueOf(i),true));
         }
         else{
             list.add(new User(String.valueOf(i),false));
         }

     }
     System.out.println("End of Adding " + i + " User" );

     // to measure how long it will take
     long startTime, endTime;
     startTime = System.currentTimeMillis();

     System.out.println("Found Any Active: "+ isAnyActive(list)); // invoke the method

     endTime = System.currentTimeMillis();
     System.out.println(endTime-startTime + " MilliScond");

   }

   public static boolean isAnyActive(ArrayList<User> list){
       found = false;

       // create two threads, each search the half of the array
       // so that shall save time to half
       Thread t1 = new Thread(new Runnable(){
         @Override
         public void run() {
            // read one more index in case the size is not an even number
             // so it will exceed the middle in one -> no problem at all
             for(int i=0; i<=(list.size()/2)+1; i++){
                   if(list.get(i).active) {
                       found = true;
                       finishFirst = true;
                       break;
                   }
             }
             finishFirst = true; // in case did not find any
         }
       });

       // second thread the same, but read from the end to the middle
       Thread t2 = new Thread(new Runnable(){
             public void run() {
                 for(int i=list.size()-1; i>=list.size()/2; i--){
                       if(list.get(i).active) {
                           found = true;
                           finishSecond = true;
                           break;
                    }
                 }
                 finishSecond = true;
            }
       });

       // start both thread
       t2.start();
       t1.start();

       // while one of them has not finished yet
       while(!finishFirst || !finishSecond){
        // but in case not finished looping but found an active user
           // break the loop
               if(found){break;}
        }

       return found; // return the result
   }
}
</code>```

Test

```<code>End of Adding 1000000 User
Found Any Active: true
31 MilliScond
</code>```

Body:
I have a requirement as below:

List<User> userList = listOfUsers(); // Morethan 50,000 users

I need to find a user status from the list of users. if any one of the users is active then break the loop.

what is the efficient way to handle this in java ?

Body:
One way to accelerate the search (Without Using Java 8) is by searching both directions in the ArrayList (i.e from the beginning to the middle, and from the end to the middle) at the same time via using multi-threading, I created this example and tested it against 1 million object/user to check if any of them is active (Note that I made only one user active and put him in the middle to see the longest time the search may take).

import java.util.ArrayList;

public class User {
    // some fields to test
    String name;
    boolean active;
    //volatile means all writes up to the volatile variable
    //from other any thread are now visible to all other threads.
    //so they can share working on that variable
    static volatile boolean finishFirst = false; // to announce first thread finish
    static volatile boolean finishSecond = false; // to announce second thread finish
    static volatile boolean found = false; // // to announce if an active user found

    /**
     * Simple Constructor
     * @param name
     * @param active
     */
    public User(String name, boolean active){
        this.name = name;
        this.active = active;
    }

   public static void main(String[] args) {

     // create an ArrayList of type User
     ArrayList<User> list = new ArrayList<User>();

     // populate it with 1 MILLION user!!
     int i=0;
     for(;i<1000000; i++){
         // make only the one in the very middle active to prolong the search to max
         if(i==500000){
             list.add(new User(String.valueOf(i),true));
         }
         else{
             list.add(new User(String.valueOf(i),false));
         }

     }
     System.out.println("End of Adding " + i + " User" );

     // to measure how long it will take
     long startTime, endTime;
     startTime = System.currentTimeMillis();

     System.out.println("Found Any Active: "+ isAnyActive(list)); // invoke the method

     endTime = System.currentTimeMillis();
     System.out.println(endTime-startTime + " MilliScond");

   }

   public static boolean isAnyActive(ArrayList<User> list){
       found = false;

       // create two threads, each search the half of the array
       // so that shall save time to half
       Thread t1 = new Thread(new Runnable(){
         @Override
         public void run() {
            // read one more index in case the size is not an even number
             // so it will exceed the middle in one -> no problem at all
             for(int i=0; i<=(list.size()/2)+1; i++){
                   if(list.get(i).active) {
                       found = true;
                       finishFirst = true;
                       break;
                   }
             }
             finishFirst = true; // in case did not find any
         }
       });

       // second thread the same, but read from the end to the middle
       Thread t2 = new Thread(new Runnable(){
             public void run() {
                 for(int i=list.size()-1; i>=list.size()/2; i--){
                       if(list.get(i).active) {
                           found = true;
                           finishSecond = true;
                           break;
                    }
                 }
                 finishSecond = true;
            }
       });

       // start both thread
       t2.start();
       t1.start();

       // while one of them has not finished yet
       while(!finishFirst || !finishSecond){
        // but in case not finished looping but found an active user
           // break the loop
               if(found){break;}
        }

       return found; // return the result
   }
}

Test

End of Adding 1000000 User
Found Any Active: true
31 MilliScond


问:
Laravel 5 custom helper could not set session
I have custom helper, class, in my Laravel project:

```<code><?php

namespace App\Http\Helpers;

class FoxUtils {

  public static function isAuthTo($name)
  {
     if (self::test($name)){
       \Session::push('AuthList',[$name => true]);
       return true;
     }
     else{
      \Session::push('AuthList',[$name => false]);
       return false;
     }
  }
}
</code>```

There two notes:

The session variable AuthList is numerical indexed array with values as arrays like the following:

```<code>array:2 [▼
  0 => array:1 [▼
    "name1" => true
  ]
  1 => array:1 [▼
    "newName" => true
  ]
]
</code>```

The value "name1" => true is defined from other place than my helper. When I try to use my helper's method I respect new keys should be added to the array:

```<code>\FoxUtils::isAuthTo('AnotherName');
dd(session('AuthList'))
</code>```

the above code prints array with only two keys while I expect three:

```<code>array:2 [▼
      0 => array:1 [▼
        "name1" => true
      ]
      1 => array:1 [▼
        "AnotherName" => true
      ]
    ]
</code>```

In other words, always the last value of the AuthList is replaced with new value! What is the problem here?

答:
From this I tried to use Session::save() and it worked fine:

```<code>....
if (self::test($name)){
       \Session::push('AuthList',[$name => true]);
       \Session::save();
       return true;
     }
....
</code>```

Body:
I have custom helper, class, in my Laravel project:

<?php

namespace App\Http\Helpers;

class FoxUtils {

  public static function isAuthTo($name)
  {
     if (self::test($name)){
       \Session::push('AuthList',[$name => true]);
       return true;
     }
     else{
      \Session::push('AuthList',[$name => false]);
       return false;
     }
  }
}

There two notes:

The session variable AuthList is numerical indexed array with values as arrays like the following:

array:2 [▼
  0 => array:1 [▼
    "name1" => true
  ]
  1 => array:1 [▼
    "newName" => true
  ]
]

The value "name1" => true is defined from other place than my helper. When I try to use my helper's method I respect new keys should be added to the array:

\FoxUtils::isAuthTo('AnotherName');
dd(session('AuthList'))

the above code prints array with only two keys while I expect three:

array:2 [▼
      0 => array:1 [▼
        "name1" => true
      ]
      1 => array:1 [▼
        "AnotherName" => true
      ]
    ]

In other words, always the last value of the AuthList is replaced with new value! What is the problem here?

Body:
From this I tried to use Session::save() and it worked fine:

....
if (self::test($name)){
       \Session::push('AuthList',[$name => true]);
       \Session::save();
       return true;
     }
....


问:
replacing list items that fit condition in lambda
I've been stuck on a line of my code for a while, and I'm at a loss as to why it returns as it does.

```<code>guess = 'a'
word = ['a', 'b', 'c']
board = ['_', '_', '_']
board = list(map(lambda x: guess if word[board.index(x)] == guess else x, board))

print(board)
</code>```

This returns

```<code>['a', 'a', 'a']
</code>```

Whereas my goal is a return of

```<code>['a', '_', '_']
</code>```

My previous solution was to loop through the list with an increasing value for the index, and to individually check each entry in word against the guess, and to replace the board list at the same index, but I feel that there is a more concise and pythonic way using lambda, I just can't quite get it.

答:
You're probably looking for something like this:</p>

```<code>board=map(lambda x: x[1] if x[1] == guess else board[x[0]], enumerate(word))
</code>```

Body:
I've been stuck on a line of my code for a while, and I'm at a loss as to why it returns as it does.

guess = 'a'
word = ['a', 'b', 'c']
board = ['_', '_', '_']
board = list(map(lambda x: guess if word[board.index(x)] == guess else x, board))

print(board)

This returns

['a', 'a', 'a']

Whereas my goal is a return of

['a', '_', '_']

My previous solution was to loop through the list with an increasing value for the index, and to individually check each entry in word against the guess, and to replace the board list at the same index, but I feel that there is a more concise and pythonic way using lambda, I just can't quite get it.

Body:
You're probably looking for something like this:

board=map(lambda x: x[1] if x[1] == guess else board[x[0]], enumerate(word))


问:
Angular 2 Resolve - Local Variable scope
I'm new to angular etc, and I have been playing around with resolve. However, when I want to pass a local boolean I get undefined? i'm trying to understand why. This below is my guard, my service just calls an api and it is passing. I want to pass a boolean to the component that the resolve is attached to, in order to display an error or not.

```<code>resolve(): boolean {
    let passed: boolean;
    let uid: string = window['appdata'].uid;
    let tbt: string = window['appdata'].tbt
    let lang: string = window['appdata'].apiUserLanguage;

    if(uid != null || undefined && tbt != null && undefined){
        console.log('Uid is: ' + uid + ' tbt is: ' + tbt);
        this.validateEmailService.emailCheck(uid, tbt, lang).subscribe(
            data => {
                passed = true;
            },
            err => {
                passed = false;
            }
        );
    }
    console.log('Passed is: ' + passed);
    return passed;
}
</code>```

}

答:
the boolean will be returned ,but you can show it after subscribing the observable returned by the service, because subscribe is an asynchrounous method. try to log it into subscribe like this & its value will be shown :)

```<code>resolve(): boolean {
let passed: boolean;
let uid: string = window['appdata'].uid;
let tbt: string = window['appdata'].tbt
let lang: string = window['appdata'].apiUserLanguage;

if(uid != null || undefined && tbt != null && undefined){
    console.log('Uid is: ' + uid + ' tbt is: ' + tbt);
    this.validateEmailService.emailCheck(uid, tbt, lang).subscribe(
        data => {
            passed = true;
            console.log('Passed is: ' + passed);// Passed is: true
        },
        err => {
            passed = false;
            console.log('Passed is: ' + passed);// Passed is: false
        }
    );
}

return passed;
</code>```

}

Body:
I'm new to angular etc, and I have been playing around with resolve. However, when I want to pass a local boolean I get undefined? i'm trying to understand why. This below is my guard, my service just calls an api and it is passing. I want to pass a boolean to the component that the resolve is attached to, in order to display an error or not.

resolve(): boolean {
    let passed: boolean;
    let uid: string = window['appdata'].uid;
    let tbt: string = window['appdata'].tbt
    let lang: string = window['appdata'].apiUserLanguage;

    if(uid != null || undefined && tbt != null && undefined){
        console.log('Uid is: ' + uid + ' tbt is: ' + tbt);
        this.validateEmailService.emailCheck(uid, tbt, lang).subscribe(
            data => {
                passed = true;
            },
            err => {
                passed = false;
            }
        );
    }
    console.log('Passed is: ' + passed);
    return passed;
}

}

Body:
the boolean will be returned ,but you can show it after subscribing the observable returned by the service, because subscribe is an asynchrounous method. try to log it into subscribe like this & its value will be shown :)

resolve(): boolean {
let passed: boolean;
let uid: string = window['appdata'].uid;
let tbt: string = window['appdata'].tbt
let lang: string = window['appdata'].apiUserLanguage;

if(uid != null || undefined && tbt != null && undefined){
    console.log('Uid is: ' + uid + ' tbt is: ' + tbt);
    this.validateEmailService.emailCheck(uid, tbt, lang).subscribe(
        data => {
            passed = true;
            console.log('Passed is: ' + passed);// Passed is: true
        },
        err => {
            passed = false;
            console.log('Passed is: ' + passed);// Passed is: false
        }
    );
}

return passed;

}

ContentLicense: CC BY-SA 4.0


问:
Hue support for Azure Active Directory using OAuth
Is there a way to authorize access to Hue portal via an Azure Active Directory using OAuth? Does Hue provide the same by some configuration changes, if not, then how can it be done?</p>

答: Hue has a OAuth backend, so it might be supported (not sure if some tweaks are needed).</p>


问:
Path of the USB devices which are connected to the machine?
If I have some USB devices which are connected to my machine, how can I know which is the path to access each one of them?

Is there way to know it through the code?

答:
Thumbs Up for Ardman's answer. Perfect.
To add a slight modification to it I would like to add modification to it where you can find the type of drive. It should cater your problem.

```<code>DriveInfo[] mydrives = DriveInfo.GetDrives();

        foreach (DriveInfo mydrive in mydrives)
        {
            if (mydrive.DriveType == DriveType.Removable)
            {
                Console.WriteLine("\nRemovable disk");
                Console.WriteLine("Drive: {0}", mydrive.Name);
                Console.WriteLine("Type: {0}", mydrive.DriveType);
            }
            else
            {
                Console.WriteLine("\nNon Removable disk\n");
                Console.WriteLine("Drive: {0}", mydrive.Name);
                Console.WriteLine("Type: {0}", mydrive.DriveType);
            }
        }
</code>```

Or if you want to get the drive names specifically you can do like this too. Please mind that these were examples from web so that the particular authors should get the credit. What I have done is creating a complete program using those code snippets so that you can understand.

```<code>[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
    static extern bool GetVolumeInformation(string Volume, StringBuilder VolumeName, uint VolumeNameSize,out uint SerialNumber, out uint SerialNumberLength, out uint flags,StringBuilder fs, uint fs_size);
</code>```

First write this function as it is. It uses the kernel32.dll to retreive the drive info.
Then in the main function you can simply add these codes (If it's a console application or if you have a GUI do appropriately.)

```<code>uint serialNum, serialNumLength, flags;
        StringBuilder volumename = new StringBuilder(256);
        StringBuilder fstype = new StringBuilder(256);
        bool ok = false;
        //Cursor.Current = Cursors.WaitCursor;
        foreach (string drives in Environment.GetLogicalDrives())
        {
            ok = GetVolumeInformation(drives, volumename, (uint)volumename.Capacity - 1, out serialNum,
                                   out serialNumLength, out flags, fstype, (uint)fstype.Capacity - 1);
            if (ok)
            {
                Console.WriteLine( "\n Volume Information of " + drives + "\n");
                Console.WriteLine( "\nSerialNumber of is..... " + serialNum.ToString() + " \n");
                if (volumename != null)
                {
                    Console.WriteLine("VolumeName is..... " + volumename.ToString() + " \n");
                }
                if (fstype != null)
                {
                    Console.WriteLine( "FileType is..... " + fstype.ToString() + " \n");
                }
            }
            ok = false;
        }
</code>```

I guess this should be a complete answer for you.

ContentLicense: CC BY-SA 2.5

Body:
Thumbs Up for Ardman's answer. Perfect.
To add a slight modification to it I would like to add modification to it where you can find the type of drive. It should cater your problem.

DriveInfo[] mydrives = DriveInfo.GetDrives();

        foreach (DriveInfo mydrive in mydrives)
        {
            if (mydrive.DriveType == DriveType.Removable)
            {
                Console.WriteLine("\nRemovable disk");
                Console.WriteLine("Drive: {0}", mydrive.Name);
                Console.WriteLine("Type: {0}", mydrive.DriveType);
            }
            else
            {
                Console.WriteLine("\nNon Removable disk\n");
                Console.WriteLine("Drive: {0}", mydrive.Name);
                Console.WriteLine("Type: {0}", mydrive.DriveType);
            }
        }

Or if you want to get the drive names specifically you can do like this too. Please mind that these were examples from web so that the particular authors should get the credit. What I have done is creating a complete program using those code snippets so that you can understand.

[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
    static extern bool GetVolumeInformation(string Volume, StringBuilder VolumeName, uint VolumeNameSize,out uint SerialNumber, out uint SerialNumberLength, out uint flags,StringBuilder fs, uint fs_size);

First write this function as it is. It uses the kernel32.dll to retreive the drive info.
Then in the main function you can simply add these codes (If it's a console application or if you have a GUI do appropriately.)

uint serialNum, serialNumLength, flags;
        StringBuilder volumename = new StringBuilder(256);
        StringBuilder fstype = new StringBuilder(256);
        bool ok = false;
        //Cursor.Current = Cursors.WaitCursor;
        foreach (string drives in Environment.GetLogicalDrives())
        {
            ok = GetVolumeInformation(drives, volumename, (uint)volumename.Capacity - 1, out serialNum,
                                   out serialNumLength, out flags, fstype, (uint)fstype.Capacity - 1);
            if (ok)
            {
                Console.WriteLine( "\n Volume Information of " + drives + "\n");
                Console.WriteLine( "\nSerialNumber of is..... " + serialNum.ToString() + " \n");
                if (volumename != null)
                {
                    Console.WriteLine("VolumeName is..... " + volumename.ToString() + " \n");
                }
                if (fstype != null)
                {
                    Console.WriteLine( "FileType is..... " + fstype.ToString() + " \n");
                }
            }
            ok = false;
        }

I guess this should be a complete answer for you.


问:
How to run Eclipse Maven builds with command-line arguments
I am converting projects to Maven using Eclipse. A little background:

We are behind a firewall that does not allow access to the Maven central repo; instead, we have a corporate mirror repository that requires a keystore file to connect to. The file is provided, and we are able to build successfully using maven in the command line with mvn clean compile package, using the argument --Djavax.net.ssl.trustStore to point to the file.

This works fine outside of eclipse, but the integrated Maven plugin fails to build because it cannot connect to the repository without the keystore, so all of our code is littered with import/package errors, which makes it extremely tedious to get anything done.

I need to be able to configure Eclipse to have this command line argument whenever I run one of the internal Maven operations like Run As -> Maven Install. Using Run Configurations works, but it does not change the context menu Maven options, and does not clear up the import errors.

Eclipse 4.6.2 Java EE edition, Windows 7 x64

答: Add the -Djavax.net.ssl.trustStore... to the eclipse.ini file associated with your Eclipse installation.


问:
React - How to open only one modal in an array
So I have just started learning react and for my for first little project I decided to make a simple UI using the Marvel API. I have an array that displays all marvel characters that begin with a certain letter, for example; a user inputs 'h' and then they are shown every character that begins with the letter h. When a users clicks a character a modal pops up and displays info about that specific character.

My problem is that when a user clicks on a picture to open the modal all of the modals for every character in the array are opened. I dont know how to make only the modal that is selected to open.

```<code>    render () {
var characters = _.map(this.state.characters, (character, i) => {
var pic = character.thumbnail.path
var picExt = character.thumbnail.extension
return (
  <div className="styleResults" key={i}>
    <li><h3>{character.name}</h3></li>
    <div>
      <img src={`${pic}/standard_fantastic.${picExt}`}
alt={`${character.name}`} onClick={() => this.openModal()}/>
      <Modal isOpen={this.state.isModalOpen} onClose={() =>
      this.closeModal()} contentLabel="marvelModal">
          <div>
            <div><h1>{character.name}</h1></div>
            <div><img className="modalIm" src=
 {`${pic}/standard_fantastic.${character.thumbnail.extension}`} alt=
 {`${character.name}`}/></div>
            <div>{character.description}</div>
          </div>
       <p><button onClick={() => this.closeModal()}>Close</button></p>
      </Modal>
    </div>
  </div>
);
});
return (
  <div>
    <div>
      <div>
        <h2>Enter a Character's Name</h2>
        <input ref="charS" type="text"/>
        <button onClick={ (e) => { this.updateCharSearch(); }
        }>Search</button>
      </div>
      <div className="CharAndComDiv">
        <h2>Enter a Comic's Name</h2>
        <input ref="comicSearch" type="text"/>
        <button onClick={ (e) => { this.updateComicSearch(); }
         }>Search</button>
      </div>
    </div>
    <div>
      <div>
        <ul>{characters}</ul>
      </div>
      <div>
        <ul>{comics}</ul>
      </div>
    </div>
  </div>
);
}
    openModal() {
    this.setState({ isModalOpen: true })
}

   closeModal() {
   this.setState({ isModalOpen: false })
  }
};
</code>```

答:
Don't create a modal for each character - create one modal that can render any selected character.

For example, store modalOpenIndex which will store the index of the currently opened character or -1 for a closed model. Then move the <Modal to be the last item of the render (not in the map function).

```<code><Modal
    isOpen={this.state.modalOpenIndex >= 0}
    onClose={() => this.closeModal()} contentLabel="marvelModal">
</code>```

Body:
So I have just started learning react and for my for first little project I decided to make a simple UI using the Marvel API. I have an array that displays all marvel characters that begin with a certain letter, for example; a user inputs 'h' and then they are shown every character that begins with the letter h. When a users clicks a character a modal pops up and displays info about that specific character.

My problem is that when a user clicks on a picture to open the modal all of the modals for every character in the array are opened. I dont know how to make only the modal that is selected to open.

    render () {
var characters = _.map(this.state.characters, (character, i) => {
var pic = character.thumbnail.path
var picExt = character.thumbnail.extension
return (

{character.name}

      <img src={`${pic}/standard_fantastic.${picExt}`}
alt={`${character.name}`} onClick={() => this.openModal()}/>
      <Modal isOpen={this.state.isModalOpen} onClose={() =>
      this.closeModal()} contentLabel="marvelModal">

{character.name}

<img className="modalIm" src=
 {`${pic}/standard_fantastic.${character.thumbnail.extension}`} alt=
 {`${character.name}`}/>

{character.description}

<button onClick={() => this.closeModal()}>Close</button>

      </Modal>

);
});
return (

Enter a Character's Name

        <input ref="charS" type="text"/>
        <button onClick={ (e) => { this.updateCharSearch(); }
        }>Search</button>

Enter a Comic's Name

        <input ref="comicSearch" type="text"/>
        <button onClick={ (e) => { this.updateComicSearch(); }
         }>Search</button>

{characters}

{comics}

);
}
    openModal() {
    this.setState({ isModalOpen: true })
}

   closeModal() {
   this.setState({ isModalOpen: false })
  }
};

Body:
Don't create a modal for each character - create one modal that can render any selected character.

For example, store modalOpenIndex which will store the index of the currently opened character or -1 for a closed model. Then move the <Modal to be the last item of the render (not in the map function).

<Modal
    isOpen={this.state.modalOpenIndex >= 0}
    onClose={() => this.closeModal()} contentLabel="marvelModal">


问:
Xcode doesn't write anything to output console
I am working on an iPhone/iPad app. All of a sudden output console stopped displaying ANY messages AT ALL. I tried to open older project - works just fine. So I thought that local project's repository got corrupted somehow, so I tried to create a new project - no messages at all are getting written to console output. Did I do something with Xcode settings accidentally? I am at a complete loss and frustrated.

Please help if you have any ideas.

Thanks.

答:
In my case it was due to hitting resource limits.  iTerm was unable to fork new processes.

Quitting some apps or increasing resource limits may help.


问:
How to customize FoxitReader shortcut keys
Recently, FoxitReader for Linux was officially introduced and I love it.

http://www.webupd8.org/2015/09/foxit-pdf-reader-sees-new-linux-release.html

However, somehow FoxitReader does not support shortcut keys for any comment tools. This is quite inconvenience for me, especially when I have to use the trackpad of my laptop to select the tool first.

So I would like to ask if is there any way to configure the shortcut keys of FoxitReader?

I do not see this feature in the preference of FoxitReader, so looking into the configuration files of FoxitReader in Linux could be a possible solution. But I am don't know how to do it.

Thanks for taking time reading my post!

答:
It is impossible to customized the shortcut on the Linux version. But for the windows version, Adiii has provided the solutions.

Two commonly used shortcut, which is already predefined in the Linux version is

CTRL + L: highlight

CTRL + N: note

Hope it helps.


问:
Mix ecto.create filling with insufficient privileges error
Received this error after trying to run mix ecto.create:

** (Mix) The database for Rumbl.Repo couldn't be created: ERROR 42501 (insufficient_privilege): permission denied to create database

Anyone knows what I should do?

答: Resolved this by changing the username field in the config/dev.exs from postgres to my user name.</p>


问:
how to return customized response on exception in apache camel
I am using Apache camel and jboss fuse, I have created a sample route blue print listed below in

```<code><?xml version="1.0" encoding="UTF-8"?>
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"
    xmlns:camel="http://camel.apache.org/schema/blueprint"
    xmlns:cxf="http://camel.apache.org/schema/blueprint/cxf"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.osgi.org/xmlns/blueprint/v1.0.0 http://www.osgi.org/xmlns/blueprint/v1.0.0/blueprint.xsd        http://camel.apache.org/schema/blueprint http://camel.apache.org/schema/blueprint/camel-blueprint.xsd">
    <cxf:rsServer address="/testservice" id="testserver" serviceClass="com.company.HelloBean">
    <camelContext id="testContext" trace="false" xmlns="http://camel.apache.org/schema/blueprint">
        <route id="testRoute" >
            <from id="_from1" uri="cxfrs:bean:testserver"/>
                <bean beanType="com.company.HelloBean"
                    id="_bean1" method="hello"/>
        </route>
    </camelContext>
</blueprint>
</code>```

and java class that implements it

```<code>@Path("/testservicenew")
public class HelloBean {

    @POST
    @Path("/test")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public String hello(Person name ) {

        return "Hello:"+name.getName();
    }
}
</code>```

but when I send wrong JSON it returns bad request, I some custom interceptor so I can control the the returned response with my customized body and header

答:
you can define as Custom Exception Handler as

```<code>@Provider
public class ExceptionHandler implements ExceptionMapper<Throwable> {
    @Override
    public Response toResponse(Throwable exception) {

        System.out.println("Exception type:" + exception.getClass().getCanonicalName());

        exception.printStackTrace();
         if (exception instanceof BadRequestException) {

            return Response.status(Response.Status.BAD_REQUEST)
                    .header("unexpected request data", "BadRequestExceptiont").build();

        }

        return Response.status(Response.Status.REQUEST_TIMEOUT).header("Problemo", "yes problemo").build();
    }

}
</code>```

and you can define it in your route to use this class

```<code><?xml version="1.0" encoding="UTF-8"?>
    <blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"
        xmlns:camel="http://camel.apache.org/schema/blueprint"
        xmlns:cxf="http://camel.apache.org/schema/blueprint/cxf"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.osgi.org/xmlns/blueprint/v1.0.0 http://www.osgi.org/xmlns/blueprint/v1.0.0/blueprint.xsd        http://camel.apache.org/schema/blueprint http://camel.apache.org/schema/blueprint/camel-blueprint.xsd">
        <cxf:rsServer address="/testservice" id="testserver" serviceClass="com.company.HelloBean">
  <cxf:providers>
            <bean class="com.company.ExceptionHandler" id="securityException"/>
        </cxf:providers>
    </cxf:rsServer>
        <camelContext id="testContext" trace="false" xmlns="http://camel.apache.org/schema/blueprint">
            <route id="testRoute" >
                <from id="_from1" uri="cxfrs:bean:testserver"/>
                    <bean beanType="com.company.HelloBean"
                        id="_bean1" method="hello"/>
            </route>
        </camelContext>
    </blueprint>
</code>```

Body:
I am using Apache camel and jboss fuse, I have created a sample route blue print listed below in

<?xml version="1.0" encoding="UTF-8"?>
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"
    xmlns:camel="http://camel.apache.org/schema/blueprint"
    xmlns:cxf="http://camel.apache.org/schema/blueprint/cxf"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.osgi.org/xmlns/blueprint/v1.0.0 http://www.osgi.org/xmlns/blueprint/v1.0.0/blueprint.xsd        http://camel.apache.org/schema/blueprint http://camel.apache.org/schema/blueprint/camel-blueprint.xsd">
    <cxf:rsServer address="/testservice" id="testserver" serviceClass="com.company.HelloBean">
    <camelContext id="testContext" trace="false" xmlns="http://camel.apache.org/schema/blueprint">
        <route id="testRoute" >
            <from id="_from1" uri="cxfrs:bean:testserver"/>
                <bean beanType="com.company.HelloBean"
                    id="_bean1" method="hello"/>
        </route>
    </camelContext>
</blueprint>

and java class that implements it

@Path("/testservicenew")
public class HelloBean {

    @POST
    @Path("/test")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public String hello(Person name ) {

        return "Hello:"+name.getName();
    }
}

but when I send wrong JSON it returns bad request, I some custom interceptor so I can control the the returned response with my customized body and header

Body:
you can define as Custom Exception Handler as

@Provider
public class ExceptionHandler implements ExceptionMapper<Throwable> {
    @Override
    public Response toResponse(Throwable exception) {

        System.out.println("Exception type:" + exception.getClass().getCanonicalName());

        exception.printStackTrace();
         if (exception instanceof BadRequestException) {

            return Response.status(Response.Status.BAD_REQUEST)
                    .header("unexpected request data", "BadRequestExceptiont").build();

        }

        return Response.status(Response.Status.REQUEST_TIMEOUT).header("Problemo", "yes problemo").build();
    }

}

and you can define it in your route to use this class

<?xml version="1.0" encoding="UTF-8"?>
    <blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"
        xmlns:camel="http://camel.apache.org/schema/blueprint"
        xmlns:cxf="http://camel.apache.org/schema/blueprint/cxf"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.osgi.org/xmlns/blueprint/v1.0.0 http://www.osgi.org/xmlns/blueprint/v1.0.0/blueprint.xsd        http://camel.apache.org/schema/blueprint http://camel.apache.org/schema/blueprint/camel-blueprint.xsd">
        <cxf:rsServer address="/testservice" id="testserver" serviceClass="com.company.HelloBean">
  <cxf:providers>
            <bean class="com.company.ExceptionHandler" id="securityException"/>
        </cxf:providers>
    </cxf:rsServer>
        <camelContext id="testContext" trace="false" xmlns="http://camel.apache.org/schema/blueprint">
            <route id="testRoute" >
                <from id="_from1" uri="cxfrs:bean:testserver"/>
                    <bean beanType="com.company.HelloBean"
                        id="_bean1" method="hello"/>
            </route>
        </camelContext>
    </blueprint>


问:
block duplicate usernames in php
and i just got a basic registration system for my website, and i can't figure out how to disallow duplicate usernames, can anyone help me?</p>

```<code><?php
  if(!empty($_POST['email']) && !empty($_POST['password'])){
$query = "INSERT INTO users (name, email, password) VALUES (:name, :email, :password)";
$stmt = $conn->prepare($query);

$stmt->bindValue(':name', $_POST['name']);
$stmt->bindValue(':email', $_POST['email']);
$stmt->bindValue(':password', password_hash($_POST['password'], PASSWORD_BCRYPT));

if( $stmt->execute() ){
  echo 'Success';
} else {
  echo 'Failure';
  print $stmt->errorCode();
}

}

?>
</code>```

答:
You prevent duplicate user names by defining a unique index/constraint on the table:

```<code>create unique index unq_users_name on users(name);
</code>```

Any attempt to insert or update values resulting in a name appearing twice will result in an error, and the insert will fail.

Title: block duplicate usernames in php

Body:
and i just got a basic registration system for my website, and i can't figure out how to disallow duplicate usernames, can anyone help me?

<?php
  if(!empty($_POST['email']) && !empty($_POST['password'])){
$query = "INSERT INTO users (name, email, password) VALUES (:name, :email, :password)";
$stmt = $conn->prepare($query);

$stmt->bindValue(':name', $_POST['name']);
$stmt->bindValue(':email', $_POST['email']);
$stmt->bindValue(':password', password_hash($_POST['password'], PASSWORD_BCRYPT));

if( $stmt->execute() ){
  echo 'Success';
} else {
  echo 'Failure';
  print $stmt->errorCode();
}

}

?>

Body:
You prevent duplicate user names by defining a unique index/constraint on the table:

create unique index unq_users_name on users(name);

Any attempt to insert or update values resulting in a name appearing twice will result in an error, and the insert will fail.


答:
The problem is the list.index method which returns the index of the first match:

list.index(x[, start[, end]])

Return zero-based index in the list of the first item whose value is x. Raises a ValueError if there is no such item. [...]

If you're also interested in a solution: You could simply iterate over both word and board:

```<code>guess = 'a'
word = ['a', 'b', 'c']
board = ['_', '_', '_']
board = list(map(lambda x, y: guess if x == guess else y, word, board))  # 3 parameters!

print(board)  # ['a', '_', '_']
</code>```

Given that you want to "replace" you could also use a normal for-loop. That way you would avoid creating and discarding lists all the time:

```<code>for idx, char in enumerate(word):
    if char == guess:
        board[idx] = char
</code>```

Title: replacing list items that fit condition in lambda

Body:
The problem is the list.index method which returns the index of the first match:

list.index(x[, start[, end]])

Return zero-based index in the list of the first item whose value is x. Raises a ValueError if there is no such item. [...]

If you're also interested in a solution: You could simply iterate over both word and board:

guess = 'a'
word = ['a', 'b', 'c']
board = ['_', '_', '_']
board = list(map(lambda x, y: guess if x == guess else y, word, board))  # 3 parameters!

print(board)  # ['a', '_', '_']

Given that you want to "replace" you could also use a normal for-loop. That way you would avoid creating and discarding lists all the time:

for idx, char in enumerate(word):
    if char == guess:
        board[idx] = char


问:
Paypal button return URL with variables
I have added a variable to my PayPal button and it is passing it to PayPal but I have forgotten what to put into the "Add advanced variables" under step 3 of the button creation.  I had this entered in the page before but when I had to change the button the return URL and all variables were removed.  I do not remember where I found the information prior.  An example of the return URL should look like http://example.com/ThanksForYourOrder.cfm?CustomerID=1234

The CustommerID number is sent as a button form field.

答: You stick it on the URL itself. The only button field you can pass apart from Paypal's define fields is custom.

Title: Paypal button return URL with variables


问:
Android Java - setVolume past max 1.0f
I'm using mediaplayer to set my volumes. I understand 0.0f is silent and 1.0f is full volume. Is there any way I can get the music to play louder than it's 100% volume programmatically?

```<code> mPlayer.setVolume(2.0f, 2.0f);
</code>```

Seems to just keep it still at 1.0f volume

答:
If 1.0 is full volume, then 2.0 is the same as 1.0

If they were different, then 1.0 would not be the full volume.

In other words, I'm pretty sure it's not possible to do that.

Title: Android Java - setVolume past max 1.0f

Body:
I'm using mediaplayer to set my volumes. I understand 0.0f is silent and 1.0f is full volume. Is there any way I can get the music to play louder than it's 100% volume programmatically?

 mPlayer.setVolume(2.0f, 2.0f);

Seems to just keep it still at 1.0f volume


问:
Check if a number has a decimal place/is a whole number
I am looking for an easy way in JavaScript to check if a number has a decimal place in it (in order to determine if it is an integer).  For instance,

23 -> OK
5 -> OK
3.5 -> not OK
34.345 -> not OK
```

```if(number is integer) {...}```

答:
```<code>number = 20.5

if (number == Math.floor(number)) {

alert("Integer")

} else {

alert("Decimal")

}
</code>```

Pretty cool and works for things like XX.0 too!
It works because Math.floor() chops off any decimal if it has one so if the floor is different from the original number we know it is a decimal! And no string conversions :)

Body:
I am looking for an easy way in JavaScript to check if a number has a decimal place in it (in order to determine if it is an integer).  For instance,

23 -> OK
5 -> OK
3.5 -> not OK
34.345 -> not OK

if(number is integer) {...}

Body:
number = 20.5

if (number == Math.floor(number)) {

alert("Integer")

} else {

alert("Decimal")

}

Pretty cool and works for things like XX.0 too!
It works because Math.floor() chops off any decimal if it has one so if the floor is different from the original number we know it is a decimal! And no string conversions :)


问:
How can I generate a random number within a certain range with Java?
I want to generate a random number in Java. It can be of integer, byte or float type, but all I really need it is to generate a random number. This is what I'm doing:

Generate a random number within a certain range (e.g. 5 through 20).

Take the number and store it within a variable.

Perform arithmetic on it.

Here's the code:

```<code>import java.util.HashMap;

public class Attack {
    public static void main(String[] args) {
        HashMap<String, Integer> attacks = new HashMap<String, Integer>();
        attacks.put("Punch", 1);
        attacks.put("Uppercut", 3);
        attacks.put("Roundhouse Kick", 5);

        int actionPoints = // Code for random number generation

        System.out.println("A brigade integrant appeared!");
        System.out.println("What do you do?");
        System.out.println("1: Punch [1 AP], 2: Uppercut [3 AP], 3: Roundhouse Kick [5 AP]");
        System.out.println("You have " + actionPoints + " Action Points.");
        Scanner reader = new Scanner(System.in);
        System.out.println("Enter a number: ");
        int n = reader.nextInt();
        reader.close();

        if n == 1 {
            System.out.println("The brigade integrant takes 2 HP of damage!");
        }
        else if n == 2 {
            System.out.println("The brigade integrant takes 5 HP of damage!");
        }
        else if n == 3 {
            System.out.println("The brigade integrant takes 8 HP of damage!");
        }
    }
}
</code>```

答:
There are multiple options for you to generate a random number. Two of these would be:

```<code>Math.random(); // Random values ranging from 0 to 1

Random rand; rand.nextInt(x); // Random int ranging from 0 to x
</code>```

To specify the exact range you could do something like this:

```<code>int RandomNumber = Min + (int)(Math.random() * Max);
</code>```

Body:
I want to generate a random number in Java. It can be of integer, byte or float type, but all I really need it is to generate a random number. This is what I'm doing:

Generate a random number within a certain range (e.g. 5 through 20).

Take the number and store it within a variable.

Perform arithmetic on it.

Here's the code:

import java.util.HashMap;

public class Attack {
    public static void main(String[] args) {
        HashMap<String, Integer> attacks = new HashMap<String, Integer>();
        attacks.put("Punch", 1);
        attacks.put("Uppercut", 3);
        attacks.put("Roundhouse Kick", 5);

        int actionPoints = // Code for random number generation

        System.out.println("A brigade integrant appeared!");
        System.out.println("What do you do?");
        System.out.println("1: Punch [1 AP], 2: Uppercut [3 AP], 3: Roundhouse Kick [5 AP]");
        System.out.println("You have " + actionPoints + " Action Points.");
        Scanner reader = new Scanner(System.in);
        System.out.println("Enter a number: ");
        int n = reader.nextInt();
        reader.close();

        if n == 1 {
            System.out.println("The brigade integrant takes 2 HP of damage!");
        }
        else if n == 2 {
            System.out.println("The brigade integrant takes 5 HP of damage!");
        }
        else if n == 3 {
            System.out.println("The brigade integrant takes 8 HP of damage!");
        }
    }
}

Body:
There are multiple options for you to generate a random number. Two of these would be:

Math.random(); // Random values ranging from 0 to 1

Random rand; rand.nextInt(x); // Random int ranging from 0 to x

To specify the exact range you could do something like this:

int RandomNumber = Min + (int)(Math.random() * Max);


问:
How to profile TensorFlow networks?
Is there a way to calculate the time cost for each node in a TensorFlow network?

I find it hard to locate the performance bottlenecks.

EDIT: The Timeline profiler is really awesome (https://stackoverflow.com/a/37774470/3632556).

答:
https://github.com/tensorflow/tensorflow/tree/master/tensorflow/core/profiler

Major Features:

Measure model parameters, float operations, tensor shapes.

Profile op execution times, requested memory size and device placement.

Inspect checkpoint tensors' shapes and their values.

Selectively group, filter, account and order ops.

Title: How to profile TensorFlow networks?


问:
Explaining the math behind an algorithm
Given a sorted array of integers a, find such an integer x that the value of

abs(a[0] - x) + abs(a[1] - x) + ... + abs(a[a.length - 1] - x)
is the smallest possible (here abs denotes the absolute value).
If there are several possible answers, output the smallest one.

Example

For a = [2, 4, 7], the output should be
absoluteValuesSumMinimization(a) = 4.

I was able to solve this by brute forcing it but then i came upon this

```<code>function absoluteValuesSumMinimization(A) {
    return A[Math.ceil(A.length/2)-1];
}
</code>```

looking to learn how/why this works.

答:
We can write the problem as follows:

http://imgur.com/I1fvjuL

When we factor out the N, the first term becomes the average of the list "a":

N (mean(a) - aj)

If we assume that the list of sorted, then the value that will minimize this quantity is the value that is closest to the term mean(a), which is the median of the list.

Math.ceil(A.length/2)-1 simply returns the middle value of the list, which is the median of a sorted list.

Title: Explaining the math behind an algorithm

Body:
Given a sorted array of integers a, find such an integer x that the value of

abs(a[0] - x) + abs(a[1] - x) + ... + abs(a[a.length - 1] - x)
is the smallest possible (here abs denotes the absolute value).
If there are several possible answers, output the smallest one.

Example

For a = [2, 4, 7], the output should be
absoluteValuesSumMinimization(a) = 4.

I was able to solve this by brute forcing it but then i came upon this

function absoluteValuesSumMinimization(A) {
    return A[Math.ceil(A.length/2)-1];
}

looking to learn how/why this works.


问:
Embedding JSON Data into YAML file
I am writing a fixture for my table. And a one of the coloums takes in a JSON string as a value.

The problem is the fixture is not loading failing as:

```<code>Fixture::FormatError: a YAML error occurred parsing /home/saurajeet/code/dcbox/test/fixtures/hardware.yml. Please note that YAML must be consistently indented using spaces. Tabs are not allowed. Please have a look at http://www.yaml.org/faq.html
The exact error was:
  ArgumentError: syntax error on line 145, col 73: `  portslist: [{"name":"ob1","port_num":0,"port_type":"network"},{"name":"ob2","port_nu'.....
</code>```

Any solutions to this.

答:
In my table, the column stripe_connect is of type JSONB .  In the fixture, here is what worked.  Note that the outer single-quotes are necessary, but square brackets are not.  Everything between the single quotes is one long line.

```<code> stripe_connect: '{"scope":"read_write", "livemode":false, "token_type":"bearer", "access_token":"sk_test_madeupvalue", "refresh_token":"rt_Ae29madeupvalueyX", "stripe_user_id":"acct_103yZabcdefg", "stripe_publishable_key":"pk_test_0HEOmadeupvalue"}'
</code>```

Title: Embedding JSON Data into YAML file

Body:
I am writing a fixture for my table. And a one of the coloums takes in a JSON string as a value.

The problem is the fixture is not loading failing as:

Fixture::FormatError: a YAML error occurred parsing /home/saurajeet/code/dcbox/test/fixtures/hardware.yml. Please note that YAML must be consistently indented using spaces. Tabs are not allowed. Please have a look at http://www.yaml.org/faq.html
The exact error was:
  ArgumentError: syntax error on line 145, col 73: `  portslist: [{"name":"ob1","port_num":0,"port_type":"network"},{"name":"ob2","port_nu'.....

Any solutions to this.

Body:
In my table, the column stripe_connect is of type JSONB .  In the fixture, here is what worked.  Note that the outer single-quotes are necessary, but square brackets are not.  Everything between the single quotes is one long line.

 stripe_connect: '{"scope":"read_write", "livemode":false, "token_type":"bearer", "access_token":"sk_test_madeupvalue", "refresh_token":"rt_Ae29madeupvalueyX", "stripe_user_id":"acct_103yZabcdefg", "stripe_publishable_key":"pk_test_0HEOmadeupvalue"}'