问:
setOnClickListener() doesn't work
I have my MainActivity and a LoginActivity. I can call each method without any problem, but as soon as I try to click on the button "btnLogin" or "btnLinkToRegister", nothing happens.

LoginActivity

```<code>import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;

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

import java.util.HashMap;
import java.util.Map;

import com.test.music.myapplication.MainActivity;
import com.test.music.myapplication.R;
import com.test.music.myapplication.app.LoginConfig;
import com.test.music.myapplication.app.LoginController;
import com.test.music.myapplication.helper.SQLiteHandler;
import com.test.music.myapplication.helper.SessionManager;

public class LoginActivity extends Activity{
    private static final String TAG = RegisterActivity.class.getSimpleName();
    private Button btnLogin;
    private Button btnLinkToRegister;
    private EditText inputEmail;
    private EditText inputPassword;
    private ProgressDialog pDialog;
    private SessionManager session;
    private SQLiteHandler db;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_fragment);

        inputEmail = (EditText) findViewById(R.id.email);
        inputPassword = (EditText) findViewById(R.id.password);
        btnLogin = (Button) findViewById(R.id.btnLogin);
        btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);

        // Progress dialog
        pDialog = new ProgressDialog(this);
        pDialog.setCancelable(false);

        // SQLite database handler
        db = new SQLiteHandler(getApplicationContext());

        // Session manager
        session = new SessionManager(getApplicationContext());

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

        // Login button Click Event
        /*btnLogin.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                String email = inputEmail.getText().toString().trim();
                String password = inputPassword.getText().toString().trim();

                // Check for empty data in the form
                if (!email.isEmpty() && !password.isEmpty()) {
                    // login user
                    checkLogin(email, password);
                } else {
                    // Prompt user to enter credentials
                    Toast.makeText(getApplicationContext(),
                            "Please enter the credentials!", Toast.LENGTH_LONG)
                            .show();
                }
            }

        });

        // Link to Register Screen
        btnLinkToRegister.setOnClickListener(new OnClickListener() {

            public void onClick(View view) {
                Intent i = new Intent(getApplicationContext(),
                        RegisterActivity.class);
                startActivity(i);
                finish();
            }
        });*/

    }

    /**
     * function to verify login details in mysql db
     * */
    public void checkLogin(final String email, final String password) {
        // Tag used to cancel the request
        String tag_string_req = "req_login";

        pDialog.setMessage("Logging in ...");
        showDialog();

        StringRequest strReq = new StringRequest(Method.POST,
                LoginConfig.URL_LOGIN, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                Log.d(TAG, "Login Response: " + response.toString());
                hideDialog();

                try {
                    JSONObject jObj = new JSONObject(response);
                    boolean error = jObj.getBoolean("error");

                    // Check for error node in json
                    if (!error) {
                        // user successfully logged in
                        // Create login session
                        session.setLogin(true);

                        // Now store the user in SQLite
                        String uid = jObj.getString("uid");

                        JSONObject user = jObj.getJSONObject("user");
                        String name = user.getString("name");
                        String email = user.getString("email");
                        String created_at = user
                                .getString("created_at");

                        // Inserting row in users table
                        db.addUser(name, email, uid, created_at);

                        // Launch main activity
                        Intent intent = new Intent(LoginActivity.this,
                                MainActivity.class);
                        startActivity(intent);
                        finish();
                    } else {
                        // Error in login. Get the error message
                        String errorMsg = jObj.getString("error_msg");
                        Toast.makeText(getApplicationContext(),
                                errorMsg, Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    // JSON error
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
                }

            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, "Login Error: " + error.getMessage());
                Toast.makeText(getApplicationContext(),
                        error.getMessage(), Toast.LENGTH_LONG).show();
                hideDialog();
            }
        }) {

            @Override
            protected Map<String, String> getParams() {
                // Posting parameters to login url
                Map<String, String> params = new HashMap<String, String>();
                params.put("email", email);
                params.put("password", password);

                return params;
            }

        };

        // Adding request to request queue
        LoginController.getInstance().addToRequestQueue(strReq, tag_string_req);
    }

    private void showDialog() {
        if (!pDialog.isShowing())
            pDialog.show();
    }

    private void hideDialog() {
        if (pDialog.isShowing())
            pDialog.dismiss();
    }

    public Button getBtnLogin() {
        return btnLogin;
    }

    public Button getBtnLinkToRegister() {
        return btnLinkToRegister;
    }

    public void setBtnLogin(Button btnLogin) {
        this.btnLogin = btnLogin;
    }

    public void setBtnLinkToRegister(Button btnLinkToRegister) {
        this.btnLinkToRegister = btnLinkToRegister;
    }

    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}
</code>```

LoginFragment

```<code>import android.app.ProgressDialog;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.test.music.myapplication.activity.LoginActivity;
import com.test.music.myapplication.activity.RegisterActivity;
import com.test.music.myapplication.helper.SQLiteHandler;
import com.test.music.myapplication.helper.SessionManager;

public class LoginFragment extends Fragment {
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private String mParam1;
    private String mParam2;
    private Button btnLogin;
    private Button btnLinkToRegister;
    private EditText inputEmail;
    private EditText inputPassword;
    private ProgressDialog pDialog;
    private SessionManager session;
    private SQLiteHandler db;
    private static final String TAG = RegisterActivity.class.getSimpleName();
    LoginActivity Log = new LoginActivity();

    private OnFragmentInteractionListener mListener;

    public LoginFragment() {
        // Required empty public constructor
    }

    public static LoginFragment newInstance(String param1, String param2) {
        LoginFragment fragment = new LoginFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    public void onCreate() {
        //super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }

        // Login button Click Event
        btnLogin.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                String email = inputEmail.getText().toString().trim();
                String password = inputPassword.getText().toString().trim();

                if (!email.isEmpty() && !password.isEmpty()) {
                    Log.checkLogin(email, password);
                } else {
                    Toast.makeText(Log.getApplicationContext(),
                            "Please enter the credentials!", Toast.LENGTH_LONG)
                            .show();
                }
            }

        });
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.login_fragment, container, false);
    }

    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}
</code>```

login_fragment

```<code><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.test.music.myapplication.LoginFragment"
    android:background="@color/bg_login"
    android:gravity="center"
    android:orientation="vertical"
    android:padding="0dp" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:orientation="vertical"
        android:paddingLeft="0dp"
        android:paddingRight="0dp" >

        <EditText
            android:id="@+id/email"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"
            android:background="@color/white"
            android:hint="@string/hint_email"
            android:inputType="textEmailAddress"
            android:padding="10dp"
            android:textColor="@color/input_login"
            android:textColorHint="@color/input_login_hint" />

        <EditText
            android:id="@+id/password"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"
            android:background="@color/white"
            android:hint="@string/hint_password"
            android:inputType="textPassword"
            android:padding="10dp"
            android:textColor="@color/input_login"
            android:textColorHint="@color/input_login_hint" />

        <!-- Login Button -->

        <Button
            android:id="@+id/btnLogin"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="40dip"
            android:background="@color/btn_login_bg"
            android:text="@string/btn_login"
            android:textColor="@color/btn_login" />

        <!-- Link to Login Screen -->

        <Button
            android:id="@+id/btnLinkToRegisterScreen"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="40dip"
            android:background="@null"
            android:text="@string/btn_link_to_register"
            android:textAllCaps="false"
            android:textColor="@color/white"
            android:textSize="15dp" />

    </LinearLayout>

</FrameLayout>
</code>```

logcat

```<code>06-08 14:47:56.703 18829-18829/? I/art: Late-enabling -Xcheck:jni
06-08 14:47:56.734 18829-18829/? D/TidaProvider: TidaProvider()
06-08 14:47:56.766 18829-18829/app.myapplication W/ActivityThread: Application app.myapplication is waiting for the debugger on port 8100...
06-08 14:47:56.769 18829-18829/app.myapplication I/System.out: Sending WAIT chunk
06-08 14:47:56.958 18829-18835/app.myapplication I/art: Debugger is active
06-08 14:47:56.971 18829-18829/app.myapplication I/System.out: Debugger has connected
06-08 14:47:56.971 18829-18829/app.myapplication I/System.out: waiting for debugger to settle...
06-08 14:47:57.171 18829-18829/app.myapplication I/System.out: waiting for debugger to settle...
06-08 14:47:57.371 18829-18829/app.myapplication I/System.out: waiting for debugger to settle...
06-08 14:47:57.571 18829-18829/app.myapplication I/System.out: waiting for debugger to settle...
06-08 14:47:57.772 18829-18829/app.myapplication I/System.out: waiting for debugger to settle...
06-08 14:47:57.972 18829-18829/app.myapplication I/System.out: waiting for debugger to settle...
06-08 14:47:58.172 18829-18829/app.myapplication I/System.out: waiting for debugger to settle...
06-08 14:47:58.372 18829-18829/app.myapplication I/System.out: waiting for debugger to settle...
06-08 14:47:58.572 18829-18829/app.myapplication I/System.out: debugger has settled (1478)
06-08 14:47:58.585 18829-18829/app.myapplication W/System: ClassLoader referenced unknown path: /data/app/app.myapplication-1/lib/arm64
06-08 14:47:58.700 18829-18829/app.myapplication V/BoostFramework: mAcquireFunc method = public int com.qualcomm.qti.Performance.perfLockAcquire(int,int[])
06-08 14:47:58.700 18829-18829/app.myapplication V/BoostFramework: mReleaseFunc method = public int com.qualcomm.qti.Performance.perfLockRelease()
06-08 14:47:58.700 18829-18829/app.myapplication V/BoostFramework: mAcquireTouchFunc method = public int com.qualcomm.qti.Performance.perfLockAcquireTouch(android.view.MotionEvent,android.util.DisplayMetrics,int,int[])
06-08 14:47:58.700 18829-18829/app.myapplication V/BoostFramework: mIOPStart method = public int com.qualcomm.qti.Performance.perfIOPrefetchStart(int,java.lang.String)
06-08 14:47:58.700 18829-18829/app.myapplication V/BoostFramework: mIOPStop method = public int com.qualcomm.qti.Performance.perfIOPrefetchStop()
06-08 14:47:58.704 18829-18829/app.myapplication V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance@f8b3883
06-08 14:47:58.704 18829-18829/app.myapplication V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance@1d12a00
06-08 14:47:58.704 18829-18829/app.myapplication V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance@cdb1239
06-08 14:47:58.704 18829-18829/app.myapplication V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance@9ea507e
06-08 14:47:58.803 18829-18829/app.myapplication V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance@11983e3
06-08 14:47:58.803 18829-18829/app.myapplication V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance@29e81e0
06-08 14:47:58.835 18829-18829/app.myapplication D/SQLiteHandler: Fetching user from Sqlite: {}
06-08 14:47:58.889 18829-18971/app.myapplication D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
06-08 14:47:58.910 18829-18829/app.myapplication D/ActivityThreadInjector: clearCachedDrawables.
06-08 14:47:58.996 18829-18971/app.myapplication I/Adreno: QUALCOMM build                   : a7823f5, I59a6815413
                                                                               Build Date                       : 09/23/16
                                                                               OpenGL ES Shader Compiler Version: XE031.07.00.00
                                                                               Local Branch                     : mybranch22028469
                                                                               Remote Branch                    : quic/LA.BR.1.3.3_rb2.26
                                                                               Remote Branch                    : NONE
                                                                               Reconstruct Branch               : NOTHING
06-08 14:47:59.030 18829-18971/app.myapplication I/OpenGLRenderer: Initialized EGL, version 1.4
06-08 14:47:59.072 18829-18971/app.myapplication E/HAL: hw_get_module_by_class: module name gralloc
06-08 14:47:59.072 18829-18971/app.myapplication E/HAL: hw_get_module_by_class: module name gralloc
06-08 14:48:02.796 18829-18829/app.myapplication W/PathParser: Points are too far apart 4.000000596046461
06-08 14:48:03.830 18829-18829/app.myapplication W/PathParser: Points are too far apart 4.000000596046461
</code>```

If you need any more code, just let me know.

答:
You write Edit Your Fragment Class

```<code>public class LoginFragment extends Fragment {
  public  Button btnLogin;
    @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.login_fragment,container,false):

btnLogin.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                String email = inputEmail.getText().toString().trim();
                String password = inputPassword.getText().toString().trim();

                // Check for empty data in the form
                if (!email.isEmpty() && !password.isEmpty()) {
                    // login user
                    checkLogin(email, password);
                } else {
                    // Prompt user to enter credentials
                    Toast.makeText(getApplicationContext(),
                            "Please enter the credentials!", Toast.LENGTH_LONG)
                            .show();
                }
            }

        });

        // Link to Register Screen
        btnLinkToRegister.setOnClickListener(new OnClickListener() {

            public void onClick(View view) {
                Intent i = new Intent(getApplicationContext(),
                        RegisterActivity.class);
                startActivity(i);
                finish();
            }
        });
            return view;
        }
    }
</code>```

Write this Way is Helping Too Much in Login Fragment .xml

Title: setOnClickListener() doesn't work

Body:
I have my MainActivity and a LoginActivity. I can call each method without any problem, but as soon as I try to click on the button "btnLogin" or "btnLinkToRegister", nothing happens.

LoginActivity

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;

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

import java.util.HashMap;
import java.util.Map;

import com.test.music.myapplication.MainActivity;
import com.test.music.myapplication.R;
import com.test.music.myapplication.app.LoginConfig;
import com.test.music.myapplication.app.LoginController;
import com.test.music.myapplication.helper.SQLiteHandler;
import com.test.music.myapplication.helper.SessionManager;

public class LoginActivity extends Activity{
    private static final String TAG = RegisterActivity.class.getSimpleName();
    private Button btnLogin;
    private Button btnLinkToRegister;
    private EditText inputEmail;
    private EditText inputPassword;
    private ProgressDialog pDialog;
    private SessionManager session;
    private SQLiteHandler db;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_fragment);

        inputEmail = (EditText) findViewById(R.id.email);
        inputPassword = (EditText) findViewById(R.id.password);
        btnLogin = (Button) findViewById(R.id.btnLogin);
        btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);

        // Progress dialog
        pDialog = new ProgressDialog(this);
        pDialog.setCancelable(false);

        // SQLite database handler
        db = new SQLiteHandler(getApplicationContext());

        // Session manager
        session = new SessionManager(getApplicationContext());

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

        // Login button Click Event
        /*btnLogin.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                String email = inputEmail.getText().toString().trim();
                String password = inputPassword.getText().toString().trim();

                // Check for empty data in the form
                if (!email.isEmpty() && !password.isEmpty()) {
                    // login user
                    checkLogin(email, password);
                } else {
                    // Prompt user to enter credentials
                    Toast.makeText(getApplicationContext(),
                            "Please enter the credentials!", Toast.LENGTH_LONG)
                            .show();
                }
            }

        });

        // Link to Register Screen
        btnLinkToRegister.setOnClickListener(new OnClickListener() {

            public void onClick(View view) {
                Intent i = new Intent(getApplicationContext(),
                        RegisterActivity.class);
                startActivity(i);
                finish();
            }
        });*/

    }

    /**
     * function to verify login details in mysql db
     * */
    public void checkLogin(final String email, final String password) {
        // Tag used to cancel the request
        String tag_string_req = "req_login";

        pDialog.setMessage("Logging in ...");
        showDialog();

        StringRequest strReq = new StringRequest(Method.POST,
                LoginConfig.URL_LOGIN, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                Log.d(TAG, "Login Response: " + response.toString());
                hideDialog();

                try {
                    JSONObject jObj = new JSONObject(response);
                    boolean error = jObj.getBoolean("error");

                    // Check for error node in json
                    if (!error) {
                        // user successfully logged in
                        // Create login session
                        session.setLogin(true);

                        // Now store the user in SQLite
                        String uid = jObj.getString("uid");

                        JSONObject user = jObj.getJSONObject("user");
                        String name = user.getString("name");
                        String email = user.getString("email");
                        String created_at = user
                                .getString("created_at");

                        // Inserting row in users table
                        db.addUser(name, email, uid, created_at);

                        // Launch main activity
                        Intent intent = new Intent(LoginActivity.this,
                                MainActivity.class);
                        startActivity(intent);
                        finish();
                    } else {
                        // Error in login. Get the error message
                        String errorMsg = jObj.getString("error_msg");
                        Toast.makeText(getApplicationContext(),
                                errorMsg, Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    // JSON error
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
                }

            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, "Login Error: " + error.getMessage());
                Toast.makeText(getApplicationContext(),
                        error.getMessage(), Toast.LENGTH_LONG).show();
                hideDialog();
            }
        }) {

            @Override
            protected Map<String, String> getParams() {
                // Posting parameters to login url
                Map<String, String> params = new HashMap<String, String>();
                params.put("email", email);
                params.put("password", password);

                return params;
            }

        };

        // Adding request to request queue
        LoginController.getInstance().addToRequestQueue(strReq, tag_string_req);
    }

    private void showDialog() {
        if (!pDialog.isShowing())
            pDialog.show();
    }

    private void hideDialog() {
        if (pDialog.isShowing())
            pDialog.dismiss();
    }

    public Button getBtnLogin() {
        return btnLogin;
    }

    public Button getBtnLinkToRegister() {
        return btnLinkToRegister;
    }

    public void setBtnLogin(Button btnLogin) {
        this.btnLogin = btnLogin;
    }

    public void setBtnLinkToRegister(Button btnLinkToRegister) {
        this.btnLinkToRegister = btnLinkToRegister;
    }

    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}

LoginFragment

import android.app.ProgressDialog;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.test.music.myapplication.activity.LoginActivity;
import com.test.music.myapplication.activity.RegisterActivity;
import com.test.music.myapplication.helper.SQLiteHandler;
import com.test.music.myapplication.helper.SessionManager;

public class LoginFragment extends Fragment {
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private String mParam1;
    private String mParam2;
    private Button btnLogin;
    private Button btnLinkToRegister;
    private EditText inputEmail;
    private EditText inputPassword;
    private ProgressDialog pDialog;
    private SessionManager session;
    private SQLiteHandler db;
    private static final String TAG = RegisterActivity.class.getSimpleName();
    LoginActivity Log = new LoginActivity();

    private OnFragmentInteractionListener mListener;

    public LoginFragment() {
        // Required empty public constructor
    }

    public static LoginFragment newInstance(String param1, String param2) {
        LoginFragment fragment = new LoginFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    public void onCreate() {
        //super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }

        // Login button Click Event
        btnLogin.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                String email = inputEmail.getText().toString().trim();
                String password = inputPassword.getText().toString().trim();

                if (!email.isEmpty() && !password.isEmpty()) {
                    Log.checkLogin(email, password);
                } else {
                    Toast.makeText(Log.getApplicationContext(),
                            "Please enter the credentials!", Toast.LENGTH_LONG)
                            .show();
                }
            }

        });
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.login_fragment, container, false);
    }

    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}

login_fragment

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.test.music.myapplication.LoginFragment"
    android:background="@color/bg_login"
    android:gravity="center"
    android:orientation="vertical"
    android:padding="0dp" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:orientation="vertical"
        android:paddingLeft="0dp"
        android:paddingRight="0dp" >

        <EditText
            android:id="@+id/email"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"
            android:background="@color/white"
            android:hint="@string/hint_email"
            android:inputType="textEmailAddress"
            android:padding="10dp"
            android:textColor="@color/input_login"
            android:textColorHint="@color/input_login_hint" />

        <EditText
            android:id="@+id/password"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"
            android:background="@color/white"
            android:hint="@string/hint_password"
            android:inputType="textPassword"
            android:padding="10dp"
            android:textColor="@color/input_login"
            android:textColorHint="@color/input_login_hint" />

        <Button
            android:id="@+id/btnLogin"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="40dip"
            android:background="@color/btn_login_bg"
            android:text="@string/btn_login"
            android:textColor="@color/btn_login" />

        <Button
            android:id="@+id/btnLinkToRegisterScreen"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="40dip"
            android:background="@null"
            android:text="@string/btn_link_to_register"
            android:textAllCaps="false"
            android:textColor="@color/white"
            android:textSize="15dp" />

    </LinearLayout>

</FrameLayout>

logcat

06-08 14:47:56.703 18829-18829/? I/art: Late-enabling -Xcheck:jni
06-08 14:47:56.734 18829-18829/? D/TidaProvider: TidaProvider()
06-08 14:47:56.766 18829-18829/app.myapplication W/ActivityThread: Application app.myapplication is waiting for the debugger on port 8100...
06-08 14:47:56.769 18829-18829/app.myapplication I/System.out: Sending WAIT chunk
06-08 14:47:56.958 18829-18835/app.myapplication I/art: Debugger is active
06-08 14:47:56.971 18829-18829/app.myapplication I/System.out: Debugger has connected
06-08 14:47:56.971 18829-18829/app.myapplication I/System.out: waiting for debugger to settle...
06-08 14:47:57.171 18829-18829/app.myapplication I/System.out: waiting for debugger to settle...
06-08 14:47:57.371 18829-18829/app.myapplication I/System.out: waiting for debugger to settle...
06-08 14:47:57.571 18829-18829/app.myapplication I/System.out: waiting for debugger to settle...
06-08 14:47:57.772 18829-18829/app.myapplication I/System.out: waiting for debugger to settle...
06-08 14:47:57.972 18829-18829/app.myapplication I/System.out: waiting for debugger to settle...
06-08 14:47:58.172 18829-18829/app.myapplication I/System.out: waiting for debugger to settle...
06-08 14:47:58.372 18829-18829/app.myapplication I/System.out: waiting for debugger to settle...
06-08 14:47:58.572 18829-18829/app.myapplication I/System.out: debugger has settled (1478)
06-08 14:47:58.585 18829-18829/app.myapplication W/System: ClassLoader referenced unknown path: /data/app/app.myapplication-1/lib/arm64
06-08 14:47:58.700 18829-18829/app.myapplication V/BoostFramework: mAcquireFunc method = public int com.qualcomm.qti.Performance.perfLockAcquire(int,int[])
06-08 14:47:58.700 18829-18829/app.myapplication V/BoostFramework: mReleaseFunc method = public int com.qualcomm.qti.Performance.perfLockRelease()
06-08 14:47:58.700 18829-18829/app.myapplication V/BoostFramework: mAcquireTouchFunc method = public int com.qualcomm.qti.Performance.perfLockAcquireTouch(android.view.MotionEvent,android.util.DisplayMetrics,int,int[])
06-08 14:47:58.700 18829-18829/app.myapplication V/BoostFramework: mIOPStart method = public int com.qualcomm.qti.Performance.perfIOPrefetchStart(int,java.lang.String)
06-08 14:47:58.700 18829-18829/app.myapplication V/BoostFramework: mIOPStop method = public int com.qualcomm.qti.Performance.perfIOPrefetchStop()
06-08 14:47:58.704 18829-18829/app.myapplication V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance@f8b3883
06-08 14:47:58.704 18829-18829/app.myapplication V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance@1d12a00
06-08 14:47:58.704 18829-18829/app.myapplication V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance@cdb1239
06-08 14:47:58.704 18829-18829/app.myapplication V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance@9ea507e
06-08 14:47:58.803 18829-18829/app.myapplication V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance@11983e3
06-08 14:47:58.803 18829-18829/app.myapplication V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance@29e81e0
06-08 14:47:58.835 18829-18829/app.myapplication D/SQLiteHandler: Fetching user from Sqlite: {}
06-08 14:47:58.889 18829-18971/app.myapplication D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
06-08 14:47:58.910 18829-18829/app.myapplication D/ActivityThreadInjector: clearCachedDrawables.
06-08 14:47:58.996 18829-18971/app.myapplication I/Adreno: QUALCOMM build                   : a7823f5, I59a6815413
                                                                               Build Date                       : 09/23/16
                                                                               OpenGL ES Shader Compiler Version: XE031.07.00.00
                                                                               Local Branch                     : mybranch22028469
                                                                               Remote Branch                    : quic/LA.BR.1.3.3_rb2.26
                                                                               Remote Branch                    : NONE
                                                                               Reconstruct Branch               : NOTHING
06-08 14:47:59.030 18829-18971/app.myapplication I/OpenGLRenderer: Initialized EGL, version 1.4
06-08 14:47:59.072 18829-18971/app.myapplication E/HAL: hw_get_module_by_class: module name gralloc
06-08 14:47:59.072 18829-18971/app.myapplication E/HAL: hw_get_module_by_class: module name gralloc
06-08 14:48:02.796 18829-18829/app.myapplication W/PathParser: Points are too far apart 4.000000596046461
06-08 14:48:03.830 18829-18829/app.myapplication W/PathParser: Points are too far apart 4.000000596046461

If you need any more code, just let me know.

Body:
You write Edit Your Fragment Class

public class LoginFragment extends Fragment {
  public  Button btnLogin;
    @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.login_fragment,container,false):

btnLogin.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                String email = inputEmail.getText().toString().trim();
                String password = inputPassword.getText().toString().trim();

                // Check for empty data in the form
                if (!email.isEmpty() && !password.isEmpty()) {
                    // login user
                    checkLogin(email, password);
                } else {
                    // Prompt user to enter credentials
                    Toast.makeText(getApplicationContext(),
                            "Please enter the credentials!", Toast.LENGTH_LONG)
                            .show();
                }
            }

        });

        // Link to Register Screen
        btnLinkToRegister.setOnClickListener(new OnClickListener() {

            public void onClick(View view) {
                Intent i = new Intent(getApplicationContext(),
                        RegisterActivity.class);
                startActivity(i);
                finish();
            }
        });
            return view;
        }
    }

Write this Way is Helping Too Much in Login Fragment .xml


来源: stackexchange

问:
Creating A List of Possible String Combination

Possible Duplicate:

Generate list of all possible permutations of a string

I need to work on a small algorithm project where I need to be able to list and write to a text file the possible combination of a given set of characters based on a given limit.

For example, if I enter the characters "a", "b", and "c" and set the limit to 3 the possible output would be:

```<code>a
b
c
aa
bb
cc
ab
ac
ba
bc
ca
cb
...
    aaa
    bbb
    ccc
    ...
    ...
    abc
    acb
    bac
    bca
    cab
    cba
</code>```

Until all possible combinations have been devised.

Writing this to a text file is no problem with me. Having an algorithm that would write the combination is something that I am quite not good at.

Appreciate in .NET (C# or VB) codes.

Thanks.

PS

On a side note, I wonder how long it would take for an application to create a string combination of all possible keyboard characters and how big the file would get to be.

Updated:
I should also show character combination from n characters to the implied limit..

答:
Well, for your example, I might try something like this.

```<code>string chars = "abc";

for (int a = 0; a < chars.Length; a++)
{
    for (int b = 0; b < chars.Length; b++)
    {
        for (int c = 0; c < chars.Length; c++)
        {
            string row = String.Format("{0}{1}{2}", chars[a], chars[b], chars[c]);
        }
    }
}
</code>```

That's just typed here so it may contain errors. Also, I'm not sure if the character limit is tied to the number of possible characters. But perhaps this will give you a starting point.

ContentLicense: CC BY-SA 4.0

Body:
Possible Duplicate:

Generate list of all possible permutations of a string

I need to work on a small algorithm project where I need to be able to list and write to a text file the possible combination of a given set of characters based on a given limit.

For example, if I enter the characters "a", "b", and "c" and set the limit to 3 the possible output would be:

a
b
c
aa
bb
cc
ab
ac
ba
bc
ca
cb
...
    aaa
    bbb
    ccc
    ...
    ...
    abc
    acb
    bac
    bca
    cab
    cba

Until all possible combinations have been devised.

Writing this to a text file is no problem with me. Having an algorithm that would write the combination is something that I am quite not good at.

Appreciate in .NET (C# or VB) codes.

Thanks.

PS

On a side note, I wonder how long it would take for an application to create a string combination of all possible keyboard characters and how big the file would get to be.

Updated:
I should also show character combination from n characters to the implied limit..

Body:
Well, for your example, I might try something like this.

string chars = "abc";

for (int a = 0; a < chars.Length; a++)
{
    for (int b = 0; b < chars.Length; b++)
    {
        for (int c = 0; c < chars.Length; c++)
        {
            string row = String.Format("{0}{1}{2}", chars[a], chars[b], chars[c]);
        }
    }
}

That's just typed here so it may contain errors. Also, I'm not sure if the character limit is tied to the number of possible characters. But perhaps this will give you a starting point.

ContentLicense: CC BY-SA 2.5


问:
spark 2.x write to parquet by partition compared to hdfs extremely slow
Can't figure out where to start troubleshooting why a simple write to parquet by partition from spark/scala into hdfs would be matter of a few seconds versus a few minutes when I write to s3 instead. </p>

```<code>    def saveDF(df: org.apache.spark.sql.DataFrame) : Unit = {

      df.write
        .mode("overwrite")
        .option("compression", "snappy")
        .partitionBy("col")
//        .parquet(s"hdfs://localhost:9000/${fileout}") // this is a few seconds
        .parquet(s"s3a://${s3bucket}/${s3folder}/${fileout}") // this is a few minutes
    }
</code>```

答:
try following configuration to improve performance

```<code>--conf "spark.sql.parquet.enable.summary-metadata=false"\
--conf "spark.hadooop.mapreduce.fileoutputcommitter.algorithm.version=2"\
</code>```

However, you won't achieve same performance as with hdfs. The problem is with commit algorithm and commit implementation in s3(move from _temporary folder in s3 is not O(1) as in hdfs, but rather O(n))

ContentLicense: CC BY-SA 3.0

Body:
Can't figure out where to start troubleshooting why a simple write to parquet by partition from spark/scala into hdfs would be matter of a few seconds versus a few minutes when I write to s3 instead.

    def saveDF(df: org.apache.spark.sql.DataFrame) : Unit = {

      df.write
        .mode("overwrite")
        .option("compression", "snappy")
        .partitionBy("col")
//        .parquet(s"hdfs://localhost:9000/${fileout}") // this is a few seconds
        .parquet(s"s3a://${s3bucket}/${s3folder}/${fileout}") // this is a few minutes
    }

Body:
try following configuration to improve performance

--conf "spark.sql.parquet.enable.summary-metadata=false"\
--conf "spark.hadooop.mapreduce.fileoutputcommitter.algorithm.version=2"\

However, you won't achieve same performance as with hdfs. The problem is with commit algorithm and commit implementation in s3(move from _temporary folder in s3 is not O(1) as in hdfs, but rather O(n))


问:
How to make question mark optional in RewriteRules?
I have this url:

```<code>www.example.com/chk-error/errcat=5&errcd=514&id=12&in=gt5
</code>```

that I can grab using the follow RewriteRule:

```<code>RewriteRule ^chk-error/(.*) chk_err.php?error=$1 [L]
</code>```

Now I need to grab this url:

```<code>www.example.com/chk-error/?errcat=5&errcd=514&id=12&in=gt5
</code>```

That is almost the same but has only the question mark "chk-error/?".

I would like to make it optional. I mean, I would like a RewriteRule to grab both urls with OR without question mark.

答:
Your second url contains a Querystring. To grab parts of the querystring , you need to match against %{QUERY_STRING} variable, try this rule to handle your second url</p>

```<code>RewriteCond %{QUERY_STRING} (.+)
RewriteRule ^chk-error/$ chk-error.php?error=%1 [L]
</code>```

Body:
I have this url:

www.example.com/chk-error/errcat=5&errcd=514&id=12&in=gt5

that I can grab using the follow RewriteRule:

RewriteRule ^chk-error/(.*) chk_err.php?error=$1 [L]

Now I need to grab this url:

www.example.com/chk-error/?errcat=5&errcd=514&id=12&in=gt5

That is almost the same but has only the question mark "chk-error/?".

I would like to make it optional. I mean, I would like a RewriteRule to grab both urls with OR without question mark.

Body:
Your second url contains a Querystring. To grab parts of the querystring , you need to match against %{QUERY_STRING} variable, try this rule to handle your second url

RewriteCond %{QUERY_STRING} (.+)
RewriteRule ^chk-error/$ chk-error.php?error=%1 [L]


问:
Is it possible to use Perl's Getopt::Std in 2 packages?
[perl script]
perl_script.pl -b "HELLO" -v

```<code>use package1;
use package2;

my $argb = GetPackage1Option;
my $argv = GetPackage2Option;

print "$argb\n";                                # Print -b argument
print "v is found!\n" if ( GetPackage2Option ); # Print
</code>```

[package1.pm]

```<code>use Getopt::Std;
require Exporter;
@ISA = qw(Exporter);
@EXPORT = qw( GetPackage1Option );

sub GetPackage1Option {

    getopt('b');
    our ($opt_b);

    my $argb = $opt_b || '';

    return $argb;
}
</code>```

[package2.pm]

```<code>use Getopt::Std;
require Exporter;
@ISA = qw(Exporter);
@EXPORT = qw( GetPackage2Option );

sub GetPackage2Option {

    my $bool = 0;
    my %opt;
    getopts('v', \%opt);

    return ( defined $optHash{v} ) ? $optHash{v} : $bool;
}
</code>```

I am calling 2 functions from 2 separate packages and each function uses a different option.

I tried this but I am only getting the option for -b. The -v option works if I remove the functions that use -b.

Apologies this only sort of a summary of my original code.

Please let me know if my question is confusing. Thanks :)

答:
Getopt::Std operates on and "consumes" the global @ARGV array. To run getopt or getopts multiple times, you could use local to make a temporary copy of @ARGV.

```<code>sub GetPackage1Option {
    local @ARGV = @ARGV;
    getopt('b');
    our ($opt_b);
    my $argb = $opt_b || '';
    return $argb;
}        # end of scope, original @ARGV restored
</code>```

Though like Sinan and simbabque say, this is an unorthodox design that you should probably reconsider.

Body:
[perl script]
perl_script.pl -b "HELLO" -v

use package1;
use package2;

my $argb = GetPackage1Option;
my $argv = GetPackage2Option;

print "$argb\n";                                # Print -b argument
print "v is found!\n" if ( GetPackage2Option ); # Print

[package1.pm]

use Getopt::Std;
require Exporter;
@ISA = qw(Exporter);
@EXPORT = qw( GetPackage1Option );

sub GetPackage1Option {

    getopt('b');
    our ($opt_b);

    my $argb = $opt_b || '';

    return $argb;
}

[package2.pm]

use Getopt::Std;
require Exporter;
@ISA = qw(Exporter);
@EXPORT = qw( GetPackage2Option );

sub GetPackage2Option {

    my $bool = 0;
    my %opt;
    getopts('v', \%opt);

    return ( defined $optHash{v} ) ? $optHash{v} : $bool;
}

I am calling 2 functions from 2 separate packages and each function uses a different option.

I tried this but I am only getting the option for -b. The -v option works if I remove the functions that use -b.

Apologies this only sort of a summary of my original code.

Please let me know if my question is confusing. Thanks :)

Body:
Getopt::Std operates on and "consumes" the global @ARGV array. To run getopt or getopts multiple times, you could use local to make a temporary copy of @ARGV.

sub GetPackage1Option {
    local @ARGV = @ARGV;
    getopt('b');
    our ($opt_b);
    my $argb = $opt_b || '';
    return $argb;
}        # end of scope, original @ARGV restored

Though like Sinan and simbabque say, this is an unorthodox design that you should probably reconsider.


问:
NativeQuery Spring Data return object
I need to implement a query in Spring Data like this :-

```<code>Select User.name, sum(Activity.minutes)
From User, Activity, ActivityStatus
Where User.id = ActivityStatus.userId
And Activity.id = ActivityStatus.activityId
AND ActivityStatus = "COMPLETED"
GROUP BY user.name;
</code>```

So i need to join 3 tables, therefore I have to use @Query with nativeQuery = true ( correct me if I'm wrong here )

And so my Repository method looks like this :-

```<code>@Query(value = "Select User.name, sum(Activity.minutes) as total_minutes
    From User, Activity, ActivityStatus
    Where User.id = ActivityStatus.userId
    And Activity.id = ActivityStatus.activityId
    AND ActivityStatus = "COMPLETED"
    AND User.Type = ?1
    GROUP BY user.name;",
    nativeQuery = true
    )
List<MyObj> getTotalActivityMinutesByUserType(String userType);
</code>```

MyObj class looks like this :-

```<code>public class MyObj {
    String name;
    long total_minutes;

// getter and setter methods

    public MyObj(String name, long total_minutes) {
        this.name = name;
        this.total_minutes = total_minutes;
    }
}
</code>```

My Test Method :-

```<code>@Test
public void TotalActivityTest() throws Exception {
    List<MyObj> objA = myRepository.getTotalActivityMinutesByUser("TEST");

}
</code>```

and i get the following exception :-

org.springframework.core.convert.ConversionFailedException: Failed to
  convert from type [java.lang.Object[]] to type
  [com.mycomp.MyObj] for value '{TEST, 5.0}'; nested
  exception is
  org.springframework.core.convert.ConverterNotFoundException: No
  converter found capable of converting from type [java.lang.String] to
  type [com.mycomp.dto.MyObj]

I need a way to return the result as MyObj. ( Or at least a way to cast it to MyObj) Is this possible?

EDIT:

Building from @Cepr0's answer My Entity class looks like this :-

```<code>@Entity
public class ActivityStatus extends Base {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH, CascadeType.DETACH})
    private Activity activity;

    @ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH, CascadeType.DETACH})
    private User user;

}
</code>```

I am not sure how the JOIN query in JPQL should look like...

答:
The query is returning object array which you are storing in an normal object.Iterate through object array and set it to object like below</p>

```<code>List<MyObj > test= new ArrayList<>();
List<Object[]> rows= query.list();
for (Object[] row : rows) {
MyObj temp=new MyObj (arg1,arg2);
temp.set((Dataype) row[0])//You need to create getters and setters for your pojo
..
test.add(temp);
}
</code>```

Title: NativeQuery Spring Data return object

Body:
I need to implement a query in Spring Data like this :-

Select User.name, sum(Activity.minutes)
From User, Activity, ActivityStatus
Where User.id = ActivityStatus.userId
And Activity.id = ActivityStatus.activityId
AND ActivityStatus = "COMPLETED"
GROUP BY user.name;

So i need to join 3 tables, therefore I have to use @Query with nativeQuery = true ( correct me if I'm wrong here )

And so my Repository method looks like this :-

@Query(value = "Select User.name, sum(Activity.minutes) as total_minutes
    From User, Activity, ActivityStatus
    Where User.id = ActivityStatus.userId
    And Activity.id = ActivityStatus.activityId
    AND ActivityStatus = "COMPLETED"
    AND User.Type = ?1
    GROUP BY user.name;",
    nativeQuery = true
    )
List<MyObj> getTotalActivityMinutesByUserType(String userType);

MyObj class looks like this :-

public class MyObj {
    String name;
    long total_minutes;

// getter and setter methods

    public MyObj(String name, long total_minutes) {
        this.name = name;
        this.total_minutes = total_minutes;
    }
}

My Test Method :-

@Test
public void TotalActivityTest() throws Exception {
    List<MyObj> objA = myRepository.getTotalActivityMinutesByUser("TEST");

}

and i get the following exception :-

org.springframework.core.convert.ConversionFailedException: Failed to
  convert from type [java.lang.Object[]] to type
  [com.mycomp.MyObj] for value '{TEST, 5.0}'; nested
  exception is
  org.springframework.core.convert.ConverterNotFoundException: No
  converter found capable of converting from type [java.lang.String] to
  type [com.mycomp.dto.MyObj]

I need a way to return the result as MyObj. ( Or at least a way to cast it to MyObj) Is this possible?

EDIT:

Building from @Cepr0's answer My Entity class looks like this :-

@Entity
public class ActivityStatus extends Base {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH, CascadeType.DETACH})
    private Activity activity;

    @ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH, CascadeType.DETACH})
    private User user;

}

I am not sure how the JOIN query in JPQL should look like...

Body:
The query is returning object array which you are storing in an normal object.Iterate through object array and set it to object like below

List<MyObj > test= new ArrayList<>();
List<Object[]> rows= query.list();
for (Object[] row : rows) {
MyObj temp=new MyObj (arg1,arg2);
temp.set((Dataype) row[0])//You need to create getters and setters for your pojo
..
test.add(temp);
}


问:
Maven plugin classloading
Could anybody please explain how the Core Classloader loads resources when, for instance, surefire test plugin is used?

What I'd especially need to know is the order in which project sources and resources from target/classes + target/test-classes AND project dependencies are loaded.

For instance, if I have a resource which exists both in a project and in a dependency. Which one is loaded first?

Thank you

答:
It turned out the answer was really simple.

First off, one can see the plugin classpath in the debug mode, $mvn test -X

And the first entry is target/test-classes, then target/classes and then plugins and all the project dependencies.

Title: Maven plugin classloading


答: That's because your HDFS cluster co-habits your AWS EMR cluster and your s3 access needs to move data across the data center.</p>

Title: spark 2.x write to parquet by partition compared to hdfs extremely slow


问:
two way communication through channels in golang
I have several functions that I want them to be executed atomically since they deal with sensitive data structures. Suppose the following scenario:
There are two functions: lock(sth) and unlock(sth) that can be called anytime by a goroutine to lock or unlock sth in a global array. I was thinking about having a command channel so that goroutines send lock and unlock commands into the channel, and on the receive side of the channel, some kind of handler handles lock, unlock requests, sequentially, by grabbing commands from the channel. That's fine, but what if the handler wants to send the result back to the requester? Is it possible to do so use golang channels? I know that it is possible to use some kind of lock mechanism like mutex, but I was wondering if it's possible to use channels for such use-case? I saw somewhere that it is recommended to use channel instead of goland low-level lock structs.

In a single sentence:

In a channel with the capacity of 1, I want the receiver side to be able to reply back to the goroutine which sent the message.

or equivalently:

A goroutine sends something to a channel; the message is received by another goroutine and handled leading to some result; how does the sender become aware of the result?

答:
The other questions have covered locking well, but I wanted to address the other part of the question around using channels to send a response back to a caller. There is a not-uncommon pattern in Go of sending a response channel with the request. For example, you might send commands to a handler over a channel; these commands would be a struct with implementation-specific details, and the struct would include a channel for sending the result back, typed to the result type. Each command sent would include a new channel, which the handler would use to send back the response, and then close. To illustrate:

```<code>type Command struct {
    // command parameters etc
    Results chan Result
}

type Result struct {
    // Whatever a result is in this case
}

var workQueue = make(chan Command)

// Example for executing synchronously
func Example(param1 string, param2 int) Result {
    workQueue <- Command{
        Param1: param1,
        Param2: param2,
        Results: make(chan Result),
    }
    return <- Results
</code>```

Body:
The other questions have covered locking well, but I wanted to address the other part of the question around using channels to send a response back to a caller. There is a not-uncommon pattern in Go of sending a response channel with the request. For example, you might send commands to a handler over a channel; these commands would be a struct with implementation-specific details, and the struct would include a channel for sending the result back, typed to the result type. Each command sent would include a new channel, which the handler would use to send back the response, and then close. To illustrate:

type Command struct {
    // command parameters etc
    Results chan Result
}

type Result struct {
    // Whatever a result is in this case
}

var workQueue = make(chan Command)

// Example for executing synchronously
func Example(param1 string, param2 int) Result {
    workQueue <- Command{
        Param1: param1,
        Param2: param2,
        Results: make(chan Result),
    }
    return <- Results


问:
Android AppCompat change text color of material buttons
I want to change button's text color, but I can't figure out how (I want to use buttons from AppCompat v22.2). I tried android:color, android:textColor, android:textColorPrimary and android:colorForeground, but these didn't do the job for me.

Can you say me what could go wrong or show a working example where you change text color of button to e.g. green? I'll be really happy when it'll be over :-)

I looked for solution for about four days, so please don't reply with links to Google Search. If you have anything relevant, then please link that

There was android:style="?android/textAppearanceSmall" in Button definition in layout XML (activity was generated from LoginActivity). I'm sorry for that (I actually don't know how to say it better in English).

答:
I know it's been a long time since I asked the question, but I didn't know how to properly close questions when I find the solution by myself back then, so I'm doing it now so that users who get here find their answer where they expect it to be.

The problem was that the Button's style was set to ?android/textAppearanceSmall (wrong even if I wanted to use the attribute :) ), so it just fell back to default values for everything. Once I removed the android:style attribute, everything was OK.


问:
Error in tensorflow: Should not fail if dtype is None
I was trying to run a code that creates some layers of a convolutional neural network and I get the following error:

Traceback (most recent call last):
  File "prova_error.py", line 39, in
    conv2_shape = tf.concat(0,[[-1],[tf.reduce_prod(tf.slice(tf.shape(h_conv2),[1],[3]),0)]])
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/array_ops.py", line 336, in concat
    name=name)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/gen_array_ops.py", line 180, in _concat
    name=name)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/op_def_library.py", line 379, in apply_op
    assert dtype is not None, "Should not fail if dtype is None"
AssertionError: Should not fail if dtype is None

I don't know what the error "Should not fail if dtype is None" means, there's no reference about it. I wanted to know what it means and how to solve it.

The code used is:

```<code>import tensorflow as tf
def weight_variable(shape,name=None):
    initial=tf.truncated_normal(shape=shape,stddev=0.1)
    return tf.Variable(initial,name=name)
def bias_variable(shape,name=None):
    initial = tf.constant(value=0.0, shape=shape)
    return tf.Variable(initial,name=name)
def conv2d(x, W, stride, pad = 'SAME'):
    return tf.nn.conv2d(x, W, strides=[1, stride, stride, 1], padding=pad)
def max_pool(x, kernelSz, stride, pad = 'SAME'):
    return tf.nn.max_pool(x, ksize=[1, kernelSz, kernelSz, 1], strides=[1, stride, stride, 1], padding=pad)
inputs=tf.placeholder("float")
targets=tf.placeholder("float",[None,1])
#conv layer 1
W_conv1=weight_variable([3,3,3,16],"w1")
b_conv1=bias_variable([16],"b1")
h_conv1=tf.nn.relu(conv2d(inputs,W_conv1,1)+b_conv1)
#pooling layer 1
h_pool1 =  max_pool(h_conv1, 3, 2)
#fully conv layer 1
w_conv2 = weight_variable([6,6,16,16],"w2")
b_conv2 = bias_variable([16],"b2")
h_conv2 = tf.nn.relu(conv2d(h_pool1, w_conv2, 2, pad="VALID") + b_conv2)
#fully conv layer 2
w_conv3 = weight_variable([1,1,16,1],"w3")
b_conv3 = bias_variable([1],"b3")
h_conv3 = tf.nn.sigmoid(conv2d(h_conv2, w_conv3, 1) + b_conv3)
conv2_shape = tf.concat(0,[[-1],[tf.reduce_prod(tf.slice(tf.shape(h_conv2),[1],[3]),0)]])
h_conv2_reshaped = tf.reshape(h_conv2,conv2_shape)
conv3_shape = tf.concat(0,[[-1],[tf.reduce_prod(tf.slice(tf.shape(h_conv3),[1],[3]),0)]])
h_conv3_reshaped = tf.reshape(h_conv3,conv3_shape)
</code>```

Thanks in advance

答:
Changing as you say I obtain:

Traceback (most recent call last):
  File "prova_error.py", line 39, in
    conv2_shape = tf.concat([[-1],[tf.reduce_prod(tf.slice(tf.shape(h_conv2),[1],[3]),0)]],0)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/array_ops.py", line 331, in concat
    dtype=dtypes.int32).get_shape(
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 566, in convert_to_tensor
    ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/constant_op.py", line 179, in _constant_tensor_conversion_function
    return constant(v, dtype=dtype, name=name)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/constant_op.py", line 162, in constant
    tensor_util.make_tensor_proto(value, dtype=dtype, shape=shape))
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/tensor_util.py", line 332, in make_tensor_proto
    _AssertCompatible(values, dtype)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/tensor_util.py", line 272, in _AssertCompatible
    (dtype.name, repr(mismatch), type(mismatch).name))
TypeError: Expected int32, got list containing Tensors of type '_Message' instead.

The version of Tensorflow installed is 0.8.0. I saw that for the new versions of tensorflow the position of parameters of tf.concat change, but in this case it was correct.

Body:
I was trying to run a code that creates some layers of a convolutional neural network and I get the following error:

Traceback (most recent call last):
  File "prova_error.py", line 39, in
    conv2_shape = tf.concat(0,[[-1],[tf.reduce_prod(tf.slice(tf.shape(h_conv2),[1],[3]),0)]])
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/array_ops.py", line 336, in concat
    name=name)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/gen_array_ops.py", line 180, in _concat
    name=name)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/op_def_library.py", line 379, in apply_op
    assert dtype is not None, "Should not fail if dtype is None"
AssertionError: Should not fail if dtype is None

I don't know what the error "Should not fail if dtype is None" means, there's no reference about it. I wanted to know what it means and how to solve it.

The code used is:

import tensorflow as tf
def weight_variable(shape,name=None):
    initial=tf.truncated_normal(shape=shape,stddev=0.1)
    return tf.Variable(initial,name=name)
def bias_variable(shape,name=None):
    initial = tf.constant(value=0.0, shape=shape)
    return tf.Variable(initial,name=name)
def conv2d(x, W, stride, pad = 'SAME'):
    return tf.nn.conv2d(x, W, strides=[1, stride, stride, 1], padding=pad)
def max_pool(x, kernelSz, stride, pad = 'SAME'):
    return tf.nn.max_pool(x, ksize=[1, kernelSz, kernelSz, 1], strides=[1, stride, stride, 1], padding=pad)
inputs=tf.placeholder("float")
targets=tf.placeholder("float",[None,1])
#conv layer 1
W_conv1=weight_variable([3,3,3,16],"w1")
b_conv1=bias_variable([16],"b1")
h_conv1=tf.nn.relu(conv2d(inputs,W_conv1,1)+b_conv1)
#pooling layer 1
h_pool1 =  max_pool(h_conv1, 3, 2)
#fully conv layer 1
w_conv2 = weight_variable([6,6,16,16],"w2")
b_conv2 = bias_variable([16],"b2")
h_conv2 = tf.nn.relu(conv2d(h_pool1, w_conv2, 2, pad="VALID") + b_conv2)
#fully conv layer 2
w_conv3 = weight_variable([1,1,16,1],"w3")
b_conv3 = bias_variable([1],"b3")
h_conv3 = tf.nn.sigmoid(conv2d(h_conv2, w_conv3, 1) + b_conv3)
conv2_shape = tf.concat(0,[[-1],[tf.reduce_prod(tf.slice(tf.shape(h_conv2),[1],[3]),0)]])
h_conv2_reshaped = tf.reshape(h_conv2,conv2_shape)
conv3_shape = tf.concat(0,[[-1],[tf.reduce_prod(tf.slice(tf.shape(h_conv3),[1],[3]),0)]])
h_conv3_reshaped = tf.reshape(h_conv3,conv3_shape)

Thanks in advance


问:
Start tracking a file in Git without adding to to the index
Is it possible to start tracking files in git without adding them to the index?

I have new files which I'd like to survive a git clean, but will likely change before the next commit. Do I simply add them to the index now, and then add them again later just before the commit?

答:
Seems like you're looking for git add --intent-to-add (or git add -N). From the official git add documentation:

```<code>-N
--intent-to-add
</code>```

Record only the fact that the path will be added later. An entry for the path is placed in the index with no content. This is useful for, among other things, showing the unstaged content of such files with git diff and committing them with git commit -a.

See the What does git add --intent-to-add or -N do and when should it be used? question for more information.

Body:
Seems like you're looking for git add --intent-to-add (or git add -N). From the official git add documentation:

-N
--intent-to-add

Record only the fact that the path will be added later. An entry for the path is placed in the index with no content. This is useful for, among other things, showing the unstaged content of such files with git diff and committing them with git commit -a.

See the What does git add --intent-to-add or -N do and when should it be used? question for more information.


问:
.NET VSTO - Excel ribbon tab label is blank, but only on first instance of Excel
So I am a moderately seasoned VSTO developer, but I am having a new issue with one of my add-ins. The add-in installs and runs just fine, but for whatever reason, when the first instance of Excel is opened (as in, there are no other workbooks currently open), the add-in's ribbon tab label is blank (see below).

To be clear, this problem only appears on the first instance of Excel. If I open another workbook using Ctrl+N or File-->New, the label appears fine on the new workbook (although the first workbook will still show a blank label). Also, before anyone asks, the ribbon tab type is set to Custom, not Office.

To make matters worse, I can't reproduce the problem on my computer, only on the customer's computers. Has anyone seen or heard of this issue before? If so, a link would help out tremendously.

UPDATE

So I resolved the issue, but I'm still not 100% sure how. There was an error in the ribbon's load event that I wasn't handling well, and it somehow short-circuited the label. I made some changes to the handling of that error (and also fixed the error), and now the label appears correctly.

ANOTHER UPDATE

The issue has returned. Any ideas? I'll add a bounty for encouragement.

答:
Here is how I solved this issue:

Quit Excel

Set the LoadBehavior value to 16 (Load first time, then load on demand) in  HKEY_CURRENT_USER\Software\Microsoft\Office\Excel\Addins\MyExcelAddIn

Delete %LocalAppData%\Microsoft\Office\Excel*.customUI file(s) as instructed at Where is VSTO add-in's ribbon cached?

Relaunch Excel


问:
Microsoft SSIS 2005 removing columns from an XML source
I have an XML source in a Microsoft SSIS 2005 package and when I debug the package I am receiving warnings like:

[DTS.Pipeline] Warning: The output column "AccBasicRateDesc" (15229) on output "AccFwdDetail" (303) and component "XML Source" (1) is not subsequently used in the Data Flow task. Removing this unused output column can increase Data Flow task performance.

So I tried to remove all of these but this seems to cause a problem as there will be whole xml outputs that I will not be using and this gives me the error:

Error at Contact Insert [DTS.Pipeline]: "output "AccFwdDetail" (19)" contains no output columns. An asynchronous output must contain output columns.

Is there a neat way to define which outputs I want from the xml file? I have tried removing the whole output in the advanced editor but this gives me the error:

Error at Contact Insert [XML Source [1]]: An output cannot be removed from the outputs column.

答:
Looks like Catch 42.

I would just ignore the original warning in this case - it is just a performance warning, it would not cause any real problems. And the performance implications are minor in this case, since nobody will consume data from this output.

OwnerDisplayName: Michael


问:
Could I use a pre-built CMS or should I build one from the ground-up?
I am working on a project for a client that started out as a simple CMS with pages, posts, and a directory. The client is constantly expanding the scope of this project with requirements for customization of just about everything. As a single developer, I am having trouble keeping up with the clients time-table. I have googled for software packages that might already exist that proved the features my client needs but I have not found anything. Does anyone know of any pre-built software that allows for the following customization or at least better words to describe this type of package?

Here are some examples of the customization that is requested:

A page or directory listing needs to be formatted from an admin-defined template. Within this template there needs to be admin-defined sections that contain admin-defined data types. (This is so the look and feel of the site can be maintained while users can easily build content, add listings, and etc.)

Advertising-tiles need to be able to be defined and populated globally and at page level.

All user generated content, pages, posts, and directory listings need to be associated with user and have flexibility to show all other user generated content for inter-linking between same users content.

Site would need billing/e-commerce system for premium listings, premium posts, advertising tiles, and etc.

Approval system for all user added or edited content (pages, posts, directory listings, etc.)

(asp.net and mvc are definitely preferable)

答:
Site would need billing/e-commerce system

This is the number one reason you should not roll your own. Find an established CMS and take the time to learn to use it.


问:
how remove picture frame for Highchart chart pie
how removing as picture iframe?

Highcharts.chart('container', {
      chart: {
         renderTo: 'container',
         plotBackgroundColor: null,
         plotBorderWidth: null,
         plotShadow: null
      },
      title: {
         text: 'Ideas por Estado',
         align: 'center',
         style:
         {
             color: '#000000',
            fontWeight: 'bold'
         }
      },
      credits: {
       enabled: false
    },
      legend: {
        align: 'center',
        verticalAlign: 'bottom',
        layout: 'vertical',
        itemStyle: {
            color: '#000000',
            fontSize: 12
        },
        x: 0,
        y: -50

      },
      plotOptions: {
         pie: {
            allowPointSelect: true,
            cursor: 'pointer',
            size: '80%',
            center: [ '50%', '45%' ],
            dataLabels: {
               enabled: true,
               distance: -35,
               color: '#ffffff',
               style: {
                   fontWeight: 'bold',
                   fontSize: 13
               },
               formatter: function() {
                  if(this.point.color=='#fd4c01'){
                      return '' + this.y +' %';
                  }
                  if(this.point.color=='#77c646'){
                      return '' + this.y +' %';
                  }
                  if(this.point.color=='#01a698'){
                      return '' + this.y +' %';
                  }

               }
            },
            showInLegend: true
         },
      },
      series: [{
         type: 'pie',
         data: [
            {
                name: 'Company A',
                 y: 59.2,
                color: '#01a698'
            },
            {
                name: 'Company B',
                 y: 30.4,
                color: '#77c646'
            },
            {
                name: 'Company C',
                 y: 10.4,
                color: '#fd4c01'
            }
         ]
      }]
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<div id="container"></div></code>```

答:
Add the tooltip object with enabled : false as shown below.

```<code>tooltip : {enabled : false }
</code>```

Highcharts.chart('container', {
      chart: {
         renderTo: 'container',
         plotBackgroundColor: null,
         plotBorderWidth: null,
         plotShadow: null
      },
      title: {
         text: 'Ideas por Estado',
         align: 'center',
         style:
         {
             color: '#000000',
            fontWeight: 'bold'
         }
      },
      credits: {
       enabled: false
    },
      legend: {
        align: 'center',
        verticalAlign: 'bottom',
        layout: 'vertical',
        itemStyle: {
            color: '#000000',
            fontSize: 12
        },
        x: 0,
        y: -50

      },
      plotOptions: {
         pie: {
            allowPointSelect: true,
            cursor: 'pointer',
            size: '80%',
            center: [ '50%', '45%' ],
            dataLabels: {
               enabled: true,
               distance: -35,
               color: '#ffffff',
               style: {
                   fontWeight: 'bold',
                   fontSize: 13
               },
               formatter: function() {
                  if(this.point.color=='#fd4c01'){
                      return '' + this.y +' %';
                  }
                  if(this.point.color=='#77c646'){
                      return '' + this.y +' %';
                  }
                  if(this.point.color=='#01a698'){
                      return '' + this.y +' %';
                  }

               }
            },
            showInLegend: true
         },
      },
      series: [{
         type: 'pie',
         data: [
            {
                name: 'Company A',
                 y: 59.2,
                color: '#01a698'
            },
            {
                name: 'Company B',
                 y: 30.4,
                color: '#77c646'
            },
            {
                name: 'Company C',
                 y: 10.4,
                color: '#fd4c01'
            }
         ]
      }],
      tooltip : {enabled : false }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<div id="container"></div></code>```

Body:
Add the tooltip object with enabled : false as shown below.

tooltip : {enabled : false }

Highcharts.chart('container', {
      chart: {
         renderTo: 'container',
         plotBackgroundColor: null,
         plotBorderWidth: null,
         plotShadow: null
      },
      title: {
         text: 'Ideas por Estado',
         align: 'center',
         style:
         {
             color: '#000000',
            fontWeight: 'bold'
         }
      },
      credits: {
       enabled: false
    },
      legend: {
        align: 'center',
        verticalAlign: 'bottom',
        layout: 'vertical',
        itemStyle: {
            color: '#000000',
            fontSize: 12
        },
        x: 0,
        y: -50

      },
      plotOptions: {
         pie: {
            allowPointSelect: true,
            cursor: 'pointer',
            size: '80%',
            center: [ '50%', '45%' ],
            dataLabels: {
               enabled: true,
               distance: -35,
               color: '#ffffff',
               style: {
                   fontWeight: 'bold',
                   fontSize: 13
               },
               formatter: function() {
                  if(this.point.color=='#fd4c01'){
                      return '<span>' + this.y +' %</span>';
                  }
                  if(this.point.color=='#77c646'){
                      return '<span>' + this.y +' %</span>';
                  }
                  if(this.point.color=='#01a698'){
                      return '<span>' + this.y +' %</span>';
                  }

               }
            },
            showInLegend: true
         },
      },
      series: [{
         type: 'pie',
         data: [
            {
                name: 'Company A',
                 y: 59.2,
                color: '#01a698'
            },
            {
                name: 'Company B',
                 y: 30.4,
                color: '#77c646'
            },
            {
                name: 'Company C',
                 y: 10.4,
                color: '#fd4c01'
            }
         ]
      }],
      tooltip : {enabled : false }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<div id="container"></div>


问:
Solr 6.5: Change function query field name (alias name)
I am a newbie of Solr using version 6.5.0. How can i change name of function query field like alias name in mysql. In below response hsin field showing data in a field name as "hsin(6371, true, latitude, longitude, 0, 0)" i want to change that field name into a "distance". How can i do that?

http://localhost:8983/solr/tellWorld/select?indent=on&q=car&fl=hsin(6371,%20true,%20latitude,%20longitude,%200,%200)%20&wt=json&sort=hsin(6371,%20true,%20latitude,%20longitude,%200,%200)%20desc

Response:

```<code>{
  "responseHeader":{
    "status":0,
    "QTime":0,
    "params":{
      "q":"car",
      "indent":"on",
      "fl":"hsin(6371, true, latitude, longitude, 0, 0) ",
      "sort":"hsin(6371, true, latitude, longitude, 0, 0) desc",
      "wt":"json"}},
  "response":{"numFound":2,"start":0,"docs":[
      {
        "hsin(6371, true, latitude, longitude, 0, 0) ":8679.458682079623},
      {
        "hsin(6371, true, latitude, longitude, 0, 0) ":7560.780673825484}]
  }}
</code>```

答:
The only thing that you need to change is the fl parameter, since Solr 4.0 (if I don't remember incorrectly) you can rename fields that you request using the fl parameter, so you just need something like:

```<code>fl=distance:hsin(6371, true, latitude, longitude, 0, 0)
</code>```

This would return then the result of the calculation in the distance field.

Body:
I am a newbie of Solr using version 6.5.0. How can i change name of function query field like alias name in mysql. In below response hsin field showing data in a field name as "hsin(6371, true, latitude, longitude, 0, 0)" i want to change that field name into a "distance". How can i do that?

http://localhost:8983/solr/tellWorld/select?indent=on&q=car&fl=hsin(6371,%20true,%20latitude,%20longitude,%200,%200)%20&wt=json&sort=hsin(6371,%20true,%20latitude,%20longitude,%200,%200)%20desc

Response:

{
  "responseHeader":{
    "status":0,
    "QTime":0,
    "params":{
      "q":"car",
      "indent":"on",
      "fl":"hsin(6371, true, latitude, longitude, 0, 0) ",
      "sort":"hsin(6371, true, latitude, longitude, 0, 0) desc",
      "wt":"json"}},
  "response":{"numFound":2,"start":0,"docs":[
      {
        "hsin(6371, true, latitude, longitude, 0, 0) ":8679.458682079623},
      {
        "hsin(6371, true, latitude, longitude, 0, 0) ":7560.780673825484}]
  }}

Body:
The only thing that you need to change is the fl parameter, since Solr 4.0 (if I don't remember incorrectly) you can rename fields that you request using the fl parameter, so you just need something like:

fl=distance:hsin(6371, true, latitude, longitude, 0, 0)

This would return then the result of the calculation in the distance field.


问:
Can't update cached Ebean Entity
We have a play-application (2.5.10) using the ebean sbt-play-ebean plugin in version 3.1.0 which provides ebean 8.2.3

We have Model which (simplyfied) looks like this:

```<code>@Entity
@Cache
public class User extends Model {
  @Id
  public Long id;

  @Version
  public Timestamp lastUpdated;

  public String name;
}
</code>```

In a Controller we have the following lines:

```<code>User user = User.find.setUseCache(true).setId(id).findUnique();
user.name = "something";
user.update();
</code>```

After executing this, the field "name" is not updated in the database. The only field that's changed is "lastUpdated".
With query logging, we can see that even the update query only contains the "lastUpdated" field to updated, but not the "name".

Now if we change the line which selects the User to

```<code>User user = User.find.setUseCache(false).setId(id).findUnique();
</code>```

it works.

So only if we don't use the L2 Cache, we can perfrom updates. In an older ebean Version (bundled with play 2.3) this worked fine.

Using no L2 Cache is not an option, because we have this problem on much more complex constellations which would rely on caching.

Is there something we are missing to update beans loaded from the cache?

答:
So, for the few people who will also stumble upon this issue: it's a bug in ebean.

Here's more information and the steps to reproduce

https://github.com/ebean-orm/ebean/pull/1039

https://github.com/ebean-orm/ebean/issues/1040

Hopefully, this will get fixed in the future, so we can manually update to the latest ebean version.

edit: the issue has been solve in the following release: http://mvnrepository.com/artifact/com.typesafe.play/play-ebean_2.11/3.2.0

Title: Can't update cached Ebean Entity

Body:
We have a play-application (2.5.10) using the ebean sbt-play-ebean plugin in version 3.1.0 which provides ebean 8.2.3

We have Model which (simplyfied) looks like this:

@Entity
@Cache
public class User extends Model {
  @Id
  public Long id;

  @Version
  public Timestamp lastUpdated;

  public String name;
}

In a Controller we have the following lines:

User user = User.find.setUseCache(true).setId(id).findUnique();
user.name = "something";
user.update();

After executing this, the field "name" is not updated in the database. The only field that's changed is "lastUpdated".
With query logging, we can see that even the update query only contains the "lastUpdated" field to updated, but not the "name".

Now if we change the line which selects the User to

User user = User.find.setUseCache(false).setId(id).findUnique();

it works.

So only if we don't use the L2 Cache, we can perfrom updates. In an older ebean Version (bundled with play 2.3) this worked fine.

Using no L2 Cache is not an option, because we have this problem on much more complex constellations which would rely on caching.

Is there something we are missing to update beans loaded from the cache?


问:
get the most two recent dates for each customer
basically, I need to retrieve the last two dates for customers who purchased in at least two different dates, implying there are some customer who had purchased only in one date, the data has the following form

```<code>client_id  date
1          2016-07-02
1          2016-07-02
1          2016-06-01
2          2015-06-01
</code>```

and I would like to get it in the following form

```<code>client_id      previous_date     last_date
1              2016-06-01        2016-07-02
</code>```

remarques:

a client can have multiple entries for the same date

a client can have entries only for one date, such customer should be discarded

答:
build up:

```<code>t=# create table s153 (c int,  d date);
CREATE TABLE
t=# insert into s153 values (1,'2016-07-02'), (1,'2016-07-02'),(1,'2016-06-01'),(2,'2016-06-01');
INSERT 0 4
</code>```

query:

```<code>t=# with a as (
select distinct c,d from s153
)
, b as (
select c,nth_value(d,1) over (partition by c order by d) last_date, nth_value(d,2) over (partition by c order by d) prev_date
from a
)
select * from b where prev_date is not null
;
 c | last_date  | prev_date
---+------------+------------
 1 | 2016-06-01 | 2016-07-02
(1 row)
</code>```

Body:
basically, I need to retrieve the last two dates for customers who purchased in at least two different dates, implying there are some customer who had purchased only in one date, the data has the following form

client_id  date
1          2016-07-02
1          2016-07-02
1          2016-06-01
2          2015-06-01

and I would like to get it in the following form

client_id      previous_date     last_date
1              2016-06-01        2016-07-02

remarques:

a client can have multiple entries for the same date

a client can have entries only for one date, such customer should be discarded

Body:
build up:

t=# create table s153 (c int,  d date);
CREATE TABLE
t=# insert into s153 values (1,'2016-07-02'), (1,'2016-07-02'),(1,'2016-06-01'),(2,'2016-06-01');
INSERT 0 4

query:

t=# with a as (
select distinct c,d from s153
)
, b as (
select c,nth_value(d,1) over (partition by c order by d) last_date, nth_value(d,2) over (partition by c order by d) prev_date
from a
)
select * from b where prev_date is not null
;
 c | last_date  | prev_date
---+------------+------------
 1 | 2016-06-01 | 2016-07-02
(1 row)


问:
its it possible to have two ELSEIF clauses in a IF ternary?
can this be made into an IF ternary to shorten the code? I don't know how to do it with multiple elseif clause

```<code>if ($ext == "m") {
 $extype = "mp3";
}elseif ($ext == "w") {
 $extype = "wav";
}elseif ($ext == "a"){
 $extype = "aac";
}
</code>```

the is the full function

```<code>function loc($id,$type,$ext) //loc($id,'n',$ext)
{
  if (($query = mysql_query("SELECT loc FROM names WHERE id = '".(int)$id."'")) !== false)
  {
    if (mysql_num_rows($query) > 0)
     if ($ext == "m") {
     $extype = ".mp3";
     }elseif ($ext == "w") {
     $extype = ".wav";
     }elseif ($ext == "a") {
     $extype = ".aac";
     }
      return '/rec/'.mysql_result($query,0,'loc').$id.'-'.($type=='n'?'n':'s').$extype);

  }
  return 'Error Not Found';
}
</code>```

答:
Looks like you'd be best off with a switch rather than IF/ELSE's

```<code>switch ($ext) {
    case 'm':
        $extype = '.mp3';
        break;
    case 'w':
        $extype = '.wav';
        break;
    case 'a':
        $extype = '.aac';
        break;
    default:
        $extype = '.wma';
        break;
}
</code>```

Also, it sounds like you need to read the documentation on arrays and control structures at php.net.

Body:
can this be made into an IF ternary to shorten the code? I don't know how to do it with multiple elseif clause

if ($ext == "m") {
 $extype = "mp3";
}elseif ($ext == "w") {
 $extype = "wav";
}elseif ($ext == "a"){
 $extype = "aac";
}

the is the full function

function loc($id,$type,$ext) //loc($id,'n',$ext)
{
  if (($query = mysql_query("SELECT loc FROM names WHERE id = '".(int)$id."'")) !== false)
  {
    if (mysql_num_rows($query) > 0)
     if ($ext == "m") {
     $extype = ".mp3";
     }elseif ($ext == "w") {
     $extype = ".wav";
     }elseif ($ext == "a") {
     $extype = ".aac";
     }
      return '/rec/'.mysql_result($query,0,'loc').$id.'-'.($type=='n'?'n':'s').$extype);

  }
  return 'Error Not Found';
}

Body:
Looks like you'd be best off with a switch rather than IF/ELSE's

switch ($ext) {
    case 'm':
        $extype = '.mp3';
        break;
    case 'w':
        $extype = '.wav';
        break;
    case 'a':
        $extype = '.aac';
        break;
    default:
        $extype = '.wma';
        break;
}

Also, it sounds like you need to read the documentation on arrays and control structures at php.net.


问:
Minitest for get request with params
I'm having trouble with one of my tests, even though the controller is working perfectly.

So, I have a form to change the VIP status of an user.

```<code><%= form_tag("/activate/#{@user.id}", method: :get, class: "form-inline space-bottom") do |f| %>
    <%= hidden_field_tag :vip, false %>
    <%= check_box_tag :vip, type:"checkbox" %>
    <%= date_field_tag(:vip_expiration_date, @user.vip_expiration_date) %>
    <button type="submit">
        Change
    </button>
</code>```

This form sends to this route:

```<code>get  '/activate/:id',           to: 'users#activate_vip'
</code>```

and gets to this controller action:

```<code>def activate_vip
  @user = User.find(params[:id])
  if @user.update_attributes(activate_vip_params)
    flash[:success] = "VIP status updated"
    redirect_to @user
  else
    render show
  end
end
</code>```

also:

```<code>def activate_vip_params
  params.permit(:vip_expiration_date, :vip)
end
</code>```

And this action works just fine, no problems, so I wanted to make a test for it using minitest:

```<code>  test "Admin should be able to change vip status" do
    log_in_as(@user)
    get "/activate/#{@other_user.id}", params: {:vip => true}
    assert @other_user.vip
  end
</code>```

I was sure this test would simply pass, but I'm getting the error "Expected false to be truthy."

My intuition said it's related to how I pass the parameters, so I tried several variations on params: but all without success. Can someone help me on this one?

I'm using gem 'minitest', '~> 5.10', '!= 5.10.2' and rails 5

EDIT:

Changed the code so I could "require" the user.

```<code>    <%= form_for @user, url: "/activate/#{@user.id}", class: "form-inline" do |f| %>
    <%= hidden_field_tag :vip, false %>
    <%= f.check_box :vip, type:"checkbox" %>
    <%= f.date_field :vip_expiration_date %>
    <%= f.submit "Change" %>
    <% end %>
</code>```

and the controller

```<code>def activate_vip_params
  params.require(:user).permit(:vip_expiration_date, :vip)
end
</code>```

and the test:

```<code>test "Admin should be able to change vip status" do
  log_in_as(@user)
  patch "/activate/#{@other_user.id}", user: { vip: true }
  assert @other_user.vip
end
</code>```

Still no success. The controller works but can't make the test.

------ EDIT ------

Nevermind. It was a stupid mistake.

I just had to add "vip:false" in the fixture for @other_user do initialise the variable.

答:
It was a simple mistake.

Everything was indeed correct, but the fixture for @another_user needed a vip: false status so the variable could be initialized.

Title: Minitest for get request with params

Body:
I'm having trouble with one of my tests, even though the controller is working perfectly.

So, I have a form to change the VIP status of an user.

<%= form_tag("/activate/#{@user.id}", method: :get, class: "form-inline space-bottom") do |f| %>
    <%= hidden_field_tag :vip, false %>
    <%= check_box_tag :vip, type:"checkbox" %>
    <%= date_field_tag(:vip_expiration_date, @user.vip_expiration_date) %>
    <button type="submit">
        Change
    </button>

This form sends to this route:

get  '/activate/:id',           to: 'users#activate_vip'

and gets to this controller action:

def activate_vip
  @user = User.find(params[:id])
  if @user.update_attributes(activate_vip_params)
    flash[:success] = "VIP status updated"
    redirect_to @user
  else
    render show
  end
end

also:

def activate_vip_params
  params.permit(:vip_expiration_date, :vip)
end

And this action works just fine, no problems, so I wanted to make a test for it using minitest:

  test "Admin should be able to change vip status" do
    log_in_as(@user)
    get "/activate/#{@other_user.id}", params: {:vip => true}
    assert @other_user.vip
  end

I was sure this test would simply pass, but I'm getting the error "Expected false to be truthy."

My intuition said it's related to how I pass the parameters, so I tried several variations on params: but all without success. Can someone help me on this one?

I'm using gem 'minitest', '~> 5.10', '!= 5.10.2' and rails 5

EDIT:

Changed the code so I could "require" the user.

    <%= form_for @user, url: "/activate/#{@user.id}", class: "form-inline" do |f| %>
    <%= hidden_field_tag :vip, false %>
    <%= f.check_box :vip, type:"checkbox" %>
    <%= f.date_field :vip_expiration_date %>
    <%= f.submit "Change" %>
    <% end %>

and the controller

def activate_vip_params
  params.require(:user).permit(:vip_expiration_date, :vip)
end

and the test:

test "Admin should be able to change vip status" do
  log_in_as(@user)
  patch "/activate/#{@other_user.id}", user: { vip: true }
  assert @other_user.vip
end

Still no success. The controller works but can't make the test.

------ EDIT ------

Nevermind. It was a stupid mistake.

I just had to add "vip:false" in the fixture for @other_user do initialise the variable.