问:
display recyclerview checkbox as selected and un-selected based on boolean values android
Let me tell you what exactly I needed. I need to load 20 questions from my MySql DB to recyclerview. Questions are saved in a table that has two columns ie, id and question. I can successfully load these questions to my recyclerview with the help of an adapter. Here is the twist, I need to mark these questions as "Yes" or "No" in my recyclerview by using checkboxes for each based on what exactly logged in user answered before this questions from his profile. Also, I expect good database and object class design solution in order to achieve this.

Here what I have tried,

Adapter Class:

```<code>public class MyHealthInfoAdapter extends RecyclerView.Adapter<MyHealthInfoAdapter.MyHealthViewHolder> {

private Context context;
private ArrayList<DonorHealthStatusQuestionare> listQuestions;

public MyHealthInfoAdapter(Context context, ArrayList<DonorHealthStatusQuestionare> listQuestions) {
    this.context = context;
    this.listQuestions = listQuestions;
}

@Override
public MyHealthViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.rv_my_health_info, parent, false);
    return new MyHealthViewHolder(view);
}

@Override
public void onBindViewHolder(final MyHealthViewHolder holder, int position) {

    DonorHealthStatusQuestionare donorHealthStatusQuestionare = listQuestions.get(position);
    holder.tvQuestion.setText(donorHealthStatusQuestionare.getQuestions());

}

@Override
public int getItemCount() {
    return listQuestions.size();
}

public class MyHealthViewHolder extends RecyclerView.ViewHolder{

    CardView cvParent;
    TextView tvQuestion;
    CheckBox cbYes, cbNo;

    public MyHealthViewHolder(View itemView) {
        super(itemView);
        cvParent = itemView.findViewById(R.id.card_view_my_health_status_rv);
        tvQuestion = itemView.findViewById(R.id.tv_eligibility_question_my_info);
        cbYes = itemView.findViewById(R.id.checkBoxYes_my_health_info);
        cbNo = itemView.findViewById(R.id.checkBoxNo_my_health_info);

    }
}
}
</code>```

Fragment:

```<code>public class DonorHealthStatus extends Fragment {

private static final int MY_SOCKET_TIMEOUT_MS = 100000;
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private DonorHealthStatusAdapter donorHealthStatusAdapter;
private ArrayList<DonorHealthStatusQuestionare> donorHealthStatusQuestionares = new ArrayList<>();
private HealthStatusCheck statusCheck = new HealthStatusCheck();
private String donorID;
private Donor donor;
private boolean checked;

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

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_donor_health_status, container, false);
}

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    donor = ((DisplayDonorDetails)getActivity()).getDonor();
    donorID = donor.getUserID();

    getHealthStatus(new HealthStatusCallBack() {
        @Override
        public void onSuccess(HealthStatusCheck healthStatusCheck) {
            statusCheck = healthStatusCheck;
            setHealthStatusView();
        }

        @Override
        public void onFail(String msg) {}
    });

}

// SETTING HEALTH STATUS POJO CLASS FROM DATABASE.
private void getHealthStatus(final HealthStatusCallBack healthStatusCallBack) {
    Utility.checkNetworkConnectionBoolean(getActivity());

    if(Utility.isNetworkEnabled){
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constants.GET_HEALTH_STATUS,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        try {

                            JSONArray jsonArray = new JSONArray(response);
                            JSONObject jsonObject = jsonArray.getJSONObject(0);
                            String code = jsonObject.getString("code");

                            if(code.equals("0001")){

                                statusCheck.setId(Integer.valueOf(jsonObject.getString("id")));
                                statusCheck.setDonorID(Integer.valueOf(jsonObject.getString("donorID")));

                                if(jsonObject.getString("q1").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q1").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q2").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q2").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q3").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q3").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q4").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q4").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q5").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q5").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q6").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q6").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q7").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q7").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q8").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q8").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q9").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q9").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q10").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q10").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q11").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q11").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q12").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q12").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q13").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q13").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q14").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q14").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q15").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q15").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q16").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q16").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q17").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q17").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q18").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q18").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q19").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q19").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q20").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q20").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }

                            }

                            healthStatusCallBack.onSuccess(statusCheck);

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

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {}
                }
        ){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<>();
                params.put("donorID", donorID);
                return params;
            }
        };

        stringRequest.setRetryPolicy(new DefaultRetryPolicy(MY_SOCKET_TIMEOUT_MS, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        NetworkRequestSingleTon.getOurInstance(getActivity()).addToRequestQue(stringRequest);
    }else {
        Utility.checkNetworkConnectionAlert(getActivity());
    }

}

// SETTING RECYCLER VIEW OF QUESTIONARE FROM DATABASE.
private void setHealthStatusView() {

    recyclerView = getActivity().findViewById(R.id.rv_donor_health_info);
    layoutManager = new LinearLayoutManager(getActivity());

    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setItemAnimator(new DefaultItemAnimator());

    donorHealthStatusAdapter = new DonorHealthStatusAdapter(getActivity(),
            donorHealthStatusQuestionares, statusCheck);

    recyclerView.setAdapter(donorHealthStatusAdapter);

    Utility.checkGpsConnectionBoolean(getActivity());
    if(Utility.isNetworkEnabled){

        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constants.GET_HEALTH_QUESTIONARE,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        try {

                            JSONArray jsonArray = new JSONArray(response);

                            int count = 0;

                            while (count < jsonArray.length()){
                                JSONObject jsonObject = jsonArray.getJSONObject(count);

                                DonorHealthStatusQuestionare donorHealthStatusQuestionare =
                                        new DonorHealthStatusQuestionare();

                                donorHealthStatusQuestionare.setId(Integer.valueOf(jsonObject.getString("id")));
                                donorHealthStatusQuestionare.setQuestions(jsonObject.getString("questions"));

                                donorHealthStatusQuestionares.add(donorHealthStatusQuestionare);
                                count ++;

                            }

                            donorHealthStatusAdapter.notifyDataSetChanged();

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

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                }
        );
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(MY_SOCKET_TIMEOUT_MS, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        NetworkRequestSingleTon.getOurInstance(getActivity()).addToRequestQue(stringRequest);

    }else {
        Utility.checkNetworkConnectionAlert(getActivity());
    }

}

// CALL BACK INTERFACE TO GET POJO CLASS FROM VOLLEY BACKGROUND ACTIVITY.
public interface HealthStatusCallBack{

    void onSuccess(HealthStatusCheck healthStatusCheck);

    void onFail(String msg);
}
}
</code>```

LAYOUT XML:

```<code><android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/card_view_health_status_rv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="1dp">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:baselineAligned="false"
    android:orientation="horizontal"
    android:padding="12dp">

    <RelativeLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:layout_weight="1">

        <TextView
            android:id="@+id/tv_eligibility_question"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/health_status_radio_group"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="0">

        <CheckBox
            android:id="@+id/checkBoxYes"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginEnd="16dp"
            android:layout_marginRight="16dp"
            android:text="@string/yes" />

        <CheckBox
            android:layout_toRightOf="@+id/checkBoxYes"
            android:layout_toEndOf="@+id/checkBoxYes"
            android:id="@+id/checkBoxNo"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/no" />

    </RelativeLayout>

</LinearLayout>
</code>```

Result Check POJO Class:

```<code>public class HealthStatusCheck {
private int id;
private int donorID;
private boolean q1;
private boolean q2;
private boolean q3;
private boolean q4;
private boolean q5;
private boolean q6;
private boolean q7;
private boolean q8;
private boolean q9;
private boolean q10;
private boolean q11;
private boolean q12;
private boolean q13;
private boolean q14;
private boolean q15;
private boolean q16;
private boolean q17;
private boolean q18;
private boolean q19;
private boolean q20;

public HealthStatusCheck() {}

public HealthStatusCheck(int id, int donorID, boolean q1, boolean q2, boolean q3, boolean q4, boolean q5, boolean q6,
                         boolean q7, boolean q8, boolean q9, boolean q10, boolean q11, boolean q12, boolean q13,
                         boolean q14, boolean q15, boolean q16, boolean q17, boolean q18, boolean q19, boolean q20) {
    this.id = id;
    this.donorID = donorID;
    this.q1 = q1;
    this.q2 = q2;
    this.q3 = q3;
    this.q4 = q4;
    this.q5 = q5;
    this.q6 = q6;
    this.q7 = q7;
    this.q8 = q8;
    this.q9 = q9;
    this.q10 = q10;
    this.q11 = q11;
    this.q12 = q12;
    this.q13 = q13;
    this.q14 = q14;
    this.q15 = q15;
    this.q16 = q16;
    this.q17 = q17;
    this.q18 = q18;
    this.q19 = q19;
    this.q20 = q20;
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public int getDonorID() {
    return donorID;
}

public void setDonorID(int donorID) {
    this.donorID = donorID;
}

public boolean isQ1() {
    return q1;
}

public void setQ1(boolean q1) {
    this.q1 = q1;
}

public boolean isQ2() {
    return q2;
}

public void setQ2(boolean q2) {
    this.q2 = q2;
}

public boolean isQ3() {
    return q3;
}

public void setQ3(boolean q3) {
    this.q3 = q3;
}

public boolean isQ4() {
    return q4;
}

public void setQ4(boolean q4) {
    this.q4 = q4;
}

public boolean isQ5() {
    return q5;
}

public void setQ5(boolean q5) {
    this.q5 = q5;
}

public boolean isQ6() {
    return q6;
}

public void setQ6(boolean q6) {
    this.q6 = q6;
}

public boolean isQ7() {
    return q7;
}

public void setQ7(boolean q7) {
    this.q7 = q7;
}

public boolean isQ8() {
    return q8;
}

public void setQ8(boolean q8) {
    this.q8 = q8;
}

public boolean isQ9() {
    return q9;
}

public void setQ9(boolean q9) {
    this.q9 = q9;
}

public boolean isQ10() {
    return q10;
}

public void setQ10(boolean q10) {
    this.q10 = q10;
}

public boolean isQ11() {
    return q11;
}

public void setQ11(boolean q11) {
    this.q11 = q11;
}

public boolean isQ12() {
    return q12;
}

public void setQ12(boolean q12) {
    this.q12 = q12;
}

public boolean isQ13() {
    return q13;
}

public void setQ13(boolean q13) {
    this.q13 = q13;
}

public boolean isQ14() {
    return q14;
}

public void setQ14(boolean q14) {
    this.q14 = q14;
}

public boolean isQ15() {
    return q15;
}

public void setQ15(boolean q15) {
    this.q15 = q15;
}

public boolean isQ16() {
    return q16;
}

public void setQ16(boolean q16) {
    this.q16 = q16;
}

public boolean isQ17() {
    return q17;
}

public void setQ17(boolean q17) {
    this.q17 = q17;
}

public boolean isQ18() {
    return q18;
}

public void setQ18(boolean q18) {
    this.q18 = q18;
}

public boolean isQ19() {
    return q19;
}

public void setQ19(boolean q19) {
    this.q19 = q19;
}

public boolean isQ20() {
    return q20;
}

public void setQ20(boolean q20) {
    this.q20 = q20;
}
}
</code>```

Questions POJO class:

```<code>public class DonorHealthStatusQuestionare {
private int id;
private String questions;
boolean isSelected;

public DonorHealthStatusQuestionare() {}

public DonorHealthStatusQuestionare(int id, String questions) {
    this.id = id;
    this.questions = questions;
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getQuestions() {
    return questions;
}

public void setQuestions(String questions) {
    this.questions = questions;
}

public boolean isSelected() {
    return isSelected;
}

public void setSelected(boolean selected) {
    isSelected = selected;
}
}
</code>```

答: You can use the boolean variable in the pojo to set the state of the checkbox. Add this code in your onBindViewHolder ,checkbox.setchecked(yourBooleanVariable); and set the checkbox as disabled in xml(android:enabled="false") or in code (checkbox.setEnabled(false);)

Body:
Let me tell you what exactly I needed. I need to load 20 questions from my MySql DB to recyclerview. Questions are saved in a table that has two columns ie, id and question. I can successfully load these questions to my recyclerview with the help of an adapter. Here is the twist, I need to mark these questions as "Yes" or "No" in my recyclerview by using checkboxes for each based on what exactly logged in user answered before this questions from his profile. Also, I expect good database and object class design solution in order to achieve this.

Here what I have tried,

Adapter Class:

public class MyHealthInfoAdapter extends RecyclerView.Adapter<MyHealthInfoAdapter.MyHealthViewHolder> {

private Context context;
private ArrayList<DonorHealthStatusQuestionare> listQuestions;

public MyHealthInfoAdapter(Context context, ArrayList<DonorHealthStatusQuestionare> listQuestions) {
    this.context = context;
    this.listQuestions = listQuestions;
}

@Override
public MyHealthViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.rv_my_health_info, parent, false);
    return new MyHealthViewHolder(view);
}

@Override
public void onBindViewHolder(final MyHealthViewHolder holder, int position) {

    DonorHealthStatusQuestionare donorHealthStatusQuestionare = listQuestions.get(position);
    holder.tvQuestion.setText(donorHealthStatusQuestionare.getQuestions());

}

@Override
public int getItemCount() {
    return listQuestions.size();
}

public class MyHealthViewHolder extends RecyclerView.ViewHolder{

    CardView cvParent;
    TextView tvQuestion;
    CheckBox cbYes, cbNo;

    public MyHealthViewHolder(View itemView) {
        super(itemView);
        cvParent = itemView.findViewById(R.id.card_view_my_health_status_rv);
        tvQuestion = itemView.findViewById(R.id.tv_eligibility_question_my_info);
        cbYes = itemView.findViewById(R.id.checkBoxYes_my_health_info);
        cbNo = itemView.findViewById(R.id.checkBoxNo_my_health_info);

    }
}
}

Fragment:

public class DonorHealthStatus extends Fragment {

private static final int MY_SOCKET_TIMEOUT_MS = 100000;
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private DonorHealthStatusAdapter donorHealthStatusAdapter;
private ArrayList<DonorHealthStatusQuestionare> donorHealthStatusQuestionares = new ArrayList<>();
private HealthStatusCheck statusCheck = new HealthStatusCheck();
private String donorID;
private Donor donor;
private boolean checked;

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

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_donor_health_status, container, false);
}

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    donor = ((DisplayDonorDetails)getActivity()).getDonor();
    donorID = donor.getUserID();

    getHealthStatus(new HealthStatusCallBack() {
        @Override
        public void onSuccess(HealthStatusCheck healthStatusCheck) {
            statusCheck = healthStatusCheck;
            setHealthStatusView();
        }

        @Override
        public void onFail(String msg) {}
    });

}

// SETTING HEALTH STATUS POJO CLASS FROM DATABASE.
private void getHealthStatus(final HealthStatusCallBack healthStatusCallBack) {
    Utility.checkNetworkConnectionBoolean(getActivity());

    if(Utility.isNetworkEnabled){
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constants.GET_HEALTH_STATUS,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        try {

                            JSONArray jsonArray = new JSONArray(response);
                            JSONObject jsonObject = jsonArray.getJSONObject(0);
                            String code = jsonObject.getString("code");

                            if(code.equals("0001")){

                                statusCheck.setId(Integer.valueOf(jsonObject.getString("id")));
                                statusCheck.setDonorID(Integer.valueOf(jsonObject.getString("donorID")));

                                if(jsonObject.getString("q1").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q1").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q2").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q2").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q3").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q3").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q4").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q4").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q5").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q5").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q6").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q6").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q7").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q7").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q8").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q8").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q9").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q9").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q10").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q10").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q11").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q11").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q12").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q12").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q13").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q13").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q14").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q14").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q15").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q15").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q16").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q16").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q17").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q17").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q18").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q18").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q19").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q19").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q20").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q20").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }

                            }

                            healthStatusCallBack.onSuccess(statusCheck);

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

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {}
                }
        ){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<>();
                params.put("donorID", donorID);
                return params;
            }
        };

        stringRequest.setRetryPolicy(new DefaultRetryPolicy(MY_SOCKET_TIMEOUT_MS, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        NetworkRequestSingleTon.getOurInstance(getActivity()).addToRequestQue(stringRequest);
    }else {
        Utility.checkNetworkConnectionAlert(getActivity());
    }

}

// SETTING RECYCLER VIEW OF QUESTIONARE FROM DATABASE.
private void setHealthStatusView() {

    recyclerView = getActivity().findViewById(R.id.rv_donor_health_info);
    layoutManager = new LinearLayoutManager(getActivity());

    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setItemAnimator(new DefaultItemAnimator());

    donorHealthStatusAdapter = new DonorHealthStatusAdapter(getActivity(),
            donorHealthStatusQuestionares, statusCheck);

    recyclerView.setAdapter(donorHealthStatusAdapter);

    Utility.checkGpsConnectionBoolean(getActivity());
    if(Utility.isNetworkEnabled){

        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constants.GET_HEALTH_QUESTIONARE,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        try {

                            JSONArray jsonArray = new JSONArray(response);

                            int count = 0;

                            while (count < jsonArray.length()){
                                JSONObject jsonObject = jsonArray.getJSONObject(count);

                                DonorHealthStatusQuestionare donorHealthStatusQuestionare =
                                        new DonorHealthStatusQuestionare();

                                donorHealthStatusQuestionare.setId(Integer.valueOf(jsonObject.getString("id")));
                                donorHealthStatusQuestionare.setQuestions(jsonObject.getString("questions"));

                                donorHealthStatusQuestionares.add(donorHealthStatusQuestionare);
                                count ++;

                            }

                            donorHealthStatusAdapter.notifyDataSetChanged();

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

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                }
        );
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(MY_SOCKET_TIMEOUT_MS, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        NetworkRequestSingleTon.getOurInstance(getActivity()).addToRequestQue(stringRequest);

    }else {
        Utility.checkNetworkConnectionAlert(getActivity());
    }

}

// CALL BACK INTERFACE TO GET POJO CLASS FROM VOLLEY BACKGROUND ACTIVITY.
public interface HealthStatusCallBack{

    void onSuccess(HealthStatusCheck healthStatusCheck);

    void onFail(String msg);
}
}

LAYOUT XML:

<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/card_view_health_status_rv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="1dp">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:baselineAligned="false"
    android:orientation="horizontal"
    android:padding="12dp">

    <RelativeLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:layout_weight="1">

        <TextView
            android:id="@+id/tv_eligibility_question"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/health_status_radio_group"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="0">

        <CheckBox
            android:id="@+id/checkBoxYes"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginEnd="16dp"
            android:layout_marginRight="16dp"
            android:text="@string/yes" />

        <CheckBox
            android:layout_toRightOf="@+id/checkBoxYes"
            android:layout_toEndOf="@+id/checkBoxYes"
            android:id="@+id/checkBoxNo"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/no" />

    </RelativeLayout>

</LinearLayout>

Result Check POJO Class:

public class HealthStatusCheck {
private int id;
private int donorID;
private boolean q1;
private boolean q2;
private boolean q3;
private boolean q4;
private boolean q5;
private boolean q6;
private boolean q7;
private boolean q8;
private boolean q9;
private boolean q10;
private boolean q11;
private boolean q12;
private boolean q13;
private boolean q14;
private boolean q15;
private boolean q16;
private boolean q17;
private boolean q18;
private boolean q19;
private boolean q20;

public HealthStatusCheck() {}

public HealthStatusCheck(int id, int donorID, boolean q1, boolean q2, boolean q3, boolean q4, boolean q5, boolean q6,
                         boolean q7, boolean q8, boolean q9, boolean q10, boolean q11, boolean q12, boolean q13,
                         boolean q14, boolean q15, boolean q16, boolean q17, boolean q18, boolean q19, boolean q20) {
    this.id = id;
    this.donorID = donorID;
    this.q1 = q1;
    this.q2 = q2;
    this.q3 = q3;
    this.q4 = q4;
    this.q5 = q5;
    this.q6 = q6;
    this.q7 = q7;
    this.q8 = q8;
    this.q9 = q9;
    this.q10 = q10;
    this.q11 = q11;
    this.q12 = q12;
    this.q13 = q13;
    this.q14 = q14;
    this.q15 = q15;
    this.q16 = q16;
    this.q17 = q17;
    this.q18 = q18;
    this.q19 = q19;
    this.q20 = q20;
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public int getDonorID() {
    return donorID;
}

public void setDonorID(int donorID) {
    this.donorID = donorID;
}

public boolean isQ1() {
    return q1;
}

public void setQ1(boolean q1) {
    this.q1 = q1;
}

public boolean isQ2() {
    return q2;
}

public void setQ2(boolean q2) {
    this.q2 = q2;
}

public boolean isQ3() {
    return q3;
}

public void setQ3(boolean q3) {
    this.q3 = q3;
}

public boolean isQ4() {
    return q4;
}

public void setQ4(boolean q4) {
    this.q4 = q4;
}

public boolean isQ5() {
    return q5;
}

public void setQ5(boolean q5) {
    this.q5 = q5;
}

public boolean isQ6() {
    return q6;
}

public void setQ6(boolean q6) {
    this.q6 = q6;
}

public boolean isQ7() {
    return q7;
}

public void setQ7(boolean q7) {
    this.q7 = q7;
}

public boolean isQ8() {
    return q8;
}

public void setQ8(boolean q8) {
    this.q8 = q8;
}

public boolean isQ9() {
    return q9;
}

public void setQ9(boolean q9) {
    this.q9 = q9;
}

public boolean isQ10() {
    return q10;
}

public void setQ10(boolean q10) {
    this.q10 = q10;
}

public boolean isQ11() {
    return q11;
}

public void setQ11(boolean q11) {
    this.q11 = q11;
}

public boolean isQ12() {
    return q12;
}

public void setQ12(boolean q12) {
    this.q12 = q12;
}

public boolean isQ13() {
    return q13;
}

public void setQ13(boolean q13) {
    this.q13 = q13;
}

public boolean isQ14() {
    return q14;
}

public void setQ14(boolean q14) {
    this.q14 = q14;
}

public boolean isQ15() {
    return q15;
}

public void setQ15(boolean q15) {
    this.q15 = q15;
}

public boolean isQ16() {
    return q16;
}

public void setQ16(boolean q16) {
    this.q16 = q16;
}

public boolean isQ17() {
    return q17;
}

public void setQ17(boolean q17) {
    this.q17 = q17;
}

public boolean isQ18() {
    return q18;
}

public void setQ18(boolean q18) {
    this.q18 = q18;
}

public boolean isQ19() {
    return q19;
}

public void setQ19(boolean q19) {
    this.q19 = q19;
}

public boolean isQ20() {
    return q20;
}

public void setQ20(boolean q20) {
    this.q20 = q20;
}
}

Questions POJO class:

public class DonorHealthStatusQuestionare {
private int id;
private String questions;
boolean isSelected;

public DonorHealthStatusQuestionare() {}

public DonorHealthStatusQuestionare(int id, String questions) {
    this.id = id;
    this.questions = questions;
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getQuestions() {
    return questions;
}

public void setQuestions(String questions) {
    this.questions = questions;
}

public boolean isSelected() {
    return isSelected;
}

public void setSelected(boolean selected) {
    isSelected = selected;
}
}


来源: stackexchange

问:
unable to resolve class issue with Executing Grrovy Scripts in Java in Wildfly with Camel CDI
Background :

I'm invoking a Groovy script using GrrovyShell as this.

```<code>@GET
@Path("/endpoint/{param}")
public Response getEndpointService(@PathParam("param") String messageId) {

    String scriptPath = "/path/to/Grrovyfile.gsh";

    Binding binding = new Binding();
    binding.setProperty("in", inParams);

    GroovyShell shell = new GroovyShell(binding);
    shell.evaluate(new File(scriptPath));

}
</code>```

Groovy Script File :

```<code>def condition = "good"
def severity = "N/A"
def detail = ""

import net.sf.json.JSONObject
import java.util.Random

try{

    def detailMap = [
        condition: condition,
        success: false,
        severity: severity,
    ]

    JSONObject jsonObject = JSONObject.fromObject(detailMap)
    detail = jsonObject.toString()
}
</code>```

And there is a seperate camel router implementation in this war and it is get initialized with camel cdi.

```<code>import javax.enterprise.context.ApplicationScoped;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.cdi.ContextName;

@ApplicationScoped
@ContextName("camel-cdi-context")
public class MiscRouter extends RouteBuilder {

    @Override
    public void configure() throws Exception {
      // router dsl
    }

}
</code>```

Problem :

Above groovy code is getting failed with below error when the router is stared with the camel cdi. But is succeeded with no errors when the @ApplicationScoped, @ContextName("camel-cdi-context") lines are commented.

```<code>12:47:28,108 ERROR [stderr] (default task-11) org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
12:47:28,109 ERROR [stderr] (default task-11) /path/to/Grrovyfile.gsh: 9: unable to resolve class net.sf.json.JSONObject
12:47:28,109 ERROR [stderr] (default task-11)  @ line 9, column 1.
12:47:28,109 ERROR [stderr] (default task-11)    import net.sf.json.JSONObject
12:47:28,109 ERROR [stderr] (default task-11)    ^
12:47:28,109 ERROR [stderr] (default task-11)
12:47:28,109 ERROR [stderr] (default task-11) 1 error
12:47:28,109 ERROR [stderr] (default task-11)
12:47:28,110 ERROR [stderr] (default task-11)   at org.codehaus.groovy.control.ErrorCollector.failIfErrors(ErrorCollector.java:310)
12:47:28,110 ERROR [stderr] (default task-11)   at org.codehaus.groovy.control.CompilationUnit.applyToSourceUnits(CompilationUnit.java:958)
12:47:28,110 ERROR [stderr] (default task-11)   at org.codehaus.groovy.control.CompilationUnit.doPhaseOperation(CompilationUnit.java:605)
12:47:28,113 ERROR [stderr] (default task-11)   at org.codehaus.groovy.control.CompilationUnit.compile(CompilationUnit.java:554)
12:47:28,113 ERROR [stderr] (default task-11)   at groovy.lang.GroovyClassLoader.doParseClass(GroovyClassLoader.java:298)
12:47:28,113 ERROR [stderr] (default task-11)   at groovy.lang.GroovyClassLoader.parseClass(GroovyClassLoader.java:268)
12:47:28,113 ERROR [stderr] (default task-11)   at groovy.lang.GroovyShell.parseClass(GroovyShell.java:688)
12:47:28,113 ERROR [stderr] (default task-11)   at groovy.lang.GroovyShell.parse(GroovyShell.java:700)
12:47:28,113 ERROR [stderr] (default task-11)   at groovy.lang.GroovyShell.evaluate(GroovyShell.java:584)
12:47:28,114 ERROR [stderr] (default task-11)   at groovy.lang.GroovyShell.evaluate(GroovyShell.java:632)
12:47:28,114 ERROR [stderr] (default task-11)   at TestGroovy.getEndpointService(TestGroovy.java:91)
12:47:28,114 ERROR [stderr] (default task-11)   at org.jboss.weld.proxies.TestGroovy$Proxy$_$$_WeldClientProxy.getEndpointService(Unknown Source)
</code>```

I assume this is an class loading issue and I'm trying to resolve this. Expect a little help here.

Already tried :

Provided these dependant jars as modules using jboss-deployment-structure.xml.

Provided imports to GroovyShell using ImportCustomizer in CompilerConfiguration

Tried to load this using a Startup Singleton EJB also.

Tried to load this using a seperate injection

Tried to load the JSONObject in seperate static class

Note :

Please note that the relevant jars are already in the war file (WEB-INF/lib).

This same issue happens for other third party artifacts like  com.fasterxml.jackson.databind.node.ObjectNode,  com.fasterxml.jackson.databind.ObjectMapper also.

But this issue doesn't happen for third party artifacts like org.apache.log4j.Logger. (may be they are already loaded through wildfly)

Update :

I'm one step closer to the answer.As per the forums / artiles classLoader returns all classes on the CLASSPATH when the JVM started.
So, I tried adding the related artifacts manually and invoke the script using the classloaders rather than GroovyShell. And it worked! Now need to find a way to load these classes in these artifacts at the JVM start / add them to the class path within wildfly.

```<code>URL[] classLoaderUrls = new URL[] {
        new URL("file:///path/to/repo/net/sf/json-lib/json-lib/2.4/json-lib-2.4-jdk15.jar"),
        new URL("file:///path/to/repo/commons-beanutils-1.8.0.jar"),
        new URL("file:///path/to/repo/commons-collections-3.2.1.jar"),
        new URL("file:///path/to/repo/commons-lang-2.5.jar"),
        new URL("file:///path/to/repo/commons-logging-1.1.1.jar"),
        new URL("file:///path/to/repo/groovy-all-2.4.11.jar"),
        new URL("file:///path/to/repo/net/sf/json/main/ezmorph-1.0.6.jar") };

URLClassLoader urlClassLoader = new URLClassLoader(classLoaderUrls);

//GroovyClassLoader groovyClassLoader = new GroovyClassLoader(urlClassLoader);
GroovyClassLoader groovyClassLoader = new GroovyClassLoader();

Script script = InvokerHelper.createScript(groovyClassLoader.parseClass(new
        File(scripts)), binding);
System.out.println("getEndpointService().script : " + script);

Object responseObj = script.run();
</code>```

Versions :

Wildfly version : 10.1.0

Wildfly Camle Patch : 4.9.0

Groovy version : groovy-all-2.4.7

答:
I found the answer by my self.

This issue can be resolved when you are using GroovyClassLoader instead of GroovyShell. Actually I dig into the GroovyShell by decompiling it and I saw this is used in there also.

Note :  if the jars in the classpath you don't need to import them manually using URLClassLoader as mentoned in the above post.

So with the below implementation it works fine now.

```<code>GroovyClassLoader groovyClassLoader = new GroovyClassLoader();

Script script = InvokerHelper.createScript(groovyClassLoader.parseClass(new
        File(scriptPath)), binding);
logger.info("getEndpointService().script : " + script);

Object responseObj = script.run();

logger.info("getEndpointService().responseObj : " + responseObj);
</code>```

Further you can use GroovyCodeSource also if you need to play with codeBase like additional attributes.

```<code>GroovyCodeSource groovyCodeSource = new GroovyCodeSource(new File(scriptPath));

GroovyClassLoader groovyClassLoader = new GroovyClassLoader();

Script script = InvokerHelper.createScript(groovyClassLoader.parseClass(groovyCodeSource), binding);
logger.info("getEndpointService().script : " + script);

Object responseObj = script.run();

logger.info("getEndpointService().responseObj : " + responseObj);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Background :

I'm invoking a Groovy script using GrrovyShell as this.

@GET
@Path("/endpoint/{param}")
public Response getEndpointService(@PathParam("param") String messageId) {

    String scriptPath = "/path/to/Grrovyfile.gsh";

    Binding binding = new Binding();
    binding.setProperty("in", inParams);

    GroovyShell shell = new GroovyShell(binding);
    shell.evaluate(new File(scriptPath));

}

Groovy Script File :

def condition = "good"
def severity = "N/A"
def detail = ""

import net.sf.json.JSONObject
import java.util.Random

try{

    def detailMap = [
        condition: condition,
        success: false,
        severity: severity,
    ]

    JSONObject jsonObject = JSONObject.fromObject(detailMap)
    detail = jsonObject.toString()
}

And there is a seperate camel router implementation in this war and it is get initialized with camel cdi.

import javax.enterprise.context.ApplicationScoped;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.cdi.ContextName;

@ApplicationScoped
@ContextName("camel-cdi-context")
public class MiscRouter extends RouteBuilder {

    @Override
    public void configure() throws Exception {
      // router dsl
    }

}

Problem :

Above groovy code is getting failed with below error when the router is stared with the camel cdi. But is succeeded with no errors when the @ApplicationScoped, @ContextName("camel-cdi-context") lines are commented.

12:47:28,108 ERROR [stderr] (default task-11) org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
12:47:28,109 ERROR [stderr] (default task-11) /path/to/Grrovyfile.gsh: 9: unable to resolve class net.sf.json.JSONObject
12:47:28,109 ERROR [stderr] (default task-11)  @ line 9, column 1.
12:47:28,109 ERROR [stderr] (default task-11)    import net.sf.json.JSONObject
12:47:28,109 ERROR [stderr] (default task-11)    ^
12:47:28,109 ERROR [stderr] (default task-11)
12:47:28,109 ERROR [stderr] (default task-11) 1 error
12:47:28,109 ERROR [stderr] (default task-11)
12:47:28,110 ERROR [stderr] (default task-11)   at org.codehaus.groovy.control.ErrorCollector.failIfErrors(ErrorCollector.java:310)
12:47:28,110 ERROR [stderr] (default task-11)   at org.codehaus.groovy.control.CompilationUnit.applyToSourceUnits(CompilationUnit.java:958)
12:47:28,110 ERROR [stderr] (default task-11)   at org.codehaus.groovy.control.CompilationUnit.doPhaseOperation(CompilationUnit.java:605)
12:47:28,113 ERROR [stderr] (default task-11)   at org.codehaus.groovy.control.CompilationUnit.compile(CompilationUnit.java:554)
12:47:28,113 ERROR [stderr] (default task-11)   at groovy.lang.GroovyClassLoader.doParseClass(GroovyClassLoader.java:298)
12:47:28,113 ERROR [stderr] (default task-11)   at groovy.lang.GroovyClassLoader.parseClass(GroovyClassLoader.java:268)
12:47:28,113 ERROR [stderr] (default task-11)   at groovy.lang.GroovyShell.parseClass(GroovyShell.java:688)
12:47:28,113 ERROR [stderr] (default task-11)   at groovy.lang.GroovyShell.parse(GroovyShell.java:700)
12:47:28,113 ERROR [stderr] (default task-11)   at groovy.lang.GroovyShell.evaluate(GroovyShell.java:584)
12:47:28,114 ERROR [stderr] (default task-11)   at groovy.lang.GroovyShell.evaluate(GroovyShell.java:632)
12:47:28,114 ERROR [stderr] (default task-11)   at TestGroovy.getEndpointService(TestGroovy.java:91)
12:47:28,114 ERROR [stderr] (default task-11)   at org.jboss.weld.proxies.TestGroovy$Proxy$_$$_WeldClientProxy.getEndpointService(Unknown Source)

I assume this is an class loading issue and I'm trying to resolve this. Expect a little help here.

Already tried :

Provided these dependant jars as modules using jboss-deployment-structure.xml.

Provided imports to GroovyShell using ImportCustomizer in CompilerConfiguration

Tried to load this using a Startup Singleton EJB also.

Tried to load this using a seperate injection

Tried to load the JSONObject in seperate static class

Note :

Please note that the relevant jars are already in the war file (WEB-INF/lib).

This same issue happens for other third party artifacts like  com.fasterxml.jackson.databind.node.ObjectNode,  com.fasterxml.jackson.databind.ObjectMapper also.

But this issue doesn't happen for third party artifacts like org.apache.log4j.Logger. (may be they are already loaded through wildfly)

Update :

I'm one step closer to the answer.As per the forums / artiles classLoader returns all classes on the CLASSPATH when the JVM started.
So, I tried adding the related artifacts manually and invoke the script using the classloaders rather than GroovyShell. And it worked! Now need to find a way to load these classes in these artifacts at the JVM start / add them to the class path within wildfly.

URL[] classLoaderUrls = new URL[] {
        new URL("file:///path/to/repo/net/sf/json-lib/json-lib/2.4/json-lib-2.4-jdk15.jar"),
        new URL("file:///path/to/repo/commons-beanutils-1.8.0.jar"),
        new URL("file:///path/to/repo/commons-collections-3.2.1.jar"),
        new URL("file:///path/to/repo/commons-lang-2.5.jar"),
        new URL("file:///path/to/repo/commons-logging-1.1.1.jar"),
        new URL("file:///path/to/repo/groovy-all-2.4.11.jar"),
        new URL("file:///path/to/repo/net/sf/json/main/ezmorph-1.0.6.jar") };

URLClassLoader urlClassLoader = new URLClassLoader(classLoaderUrls);

//GroovyClassLoader groovyClassLoader = new GroovyClassLoader(urlClassLoader);
GroovyClassLoader groovyClassLoader = new GroovyClassLoader();

Script script = InvokerHelper.createScript(groovyClassLoader.parseClass(new
        File(scripts)), binding);
System.out.println("getEndpointService().script : " + script);

Object responseObj = script.run();

Versions :

Wildfly version : 10.1.0

Wildfly Camle Patch : 4.9.0

Groovy version : groovy-all-2.4.7

Body:
I found the answer by my self.

This issue can be resolved when you are using GroovyClassLoader instead of GroovyShell. Actually I dig into the GroovyShell by decompiling it and I saw this is used in there also.

Note :  if the jars in the classpath you don't need to import them manually using URLClassLoader as mentoned in the above post.

So with the below implementation it works fine now.

GroovyClassLoader groovyClassLoader = new GroovyClassLoader();

Script script = InvokerHelper.createScript(groovyClassLoader.parseClass(new
        File(scriptPath)), binding);
logger.info("getEndpointService().script : " + script);

Object responseObj = script.run();

logger.info("getEndpointService().responseObj : " + responseObj);

Further you can use GroovyCodeSource also if you need to play with codeBase like additional attributes.

GroovyCodeSource groovyCodeSource = new GroovyCodeSource(new File(scriptPath));

GroovyClassLoader groovyClassLoader = new GroovyClassLoader();

Script script = InvokerHelper.createScript(groovyClassLoader.parseClass(groovyCodeSource), binding);
logger.info("getEndpointService().script : " + script);

Object responseObj = script.run();

logger.info("getEndpointService().responseObj : " + responseObj);


问:
setting empty value inside select if is empty select AngularJS
can someone tell me how can I make empty value, that if nothing is in list of select, show "n/a"

```<code>demo
</code>```

https://codepen.io/Turqus/pen/wPrKrr?editors=1010

template

```<code>    <div ng-app="test" ng-controller="select">
  <select class="form-control" ng-model="selectedBoard" ng-change="changeBoard(selectedBoard)">
     <option ng-repeat="item in boards" value="{{$index}}">{{$index}}</option>
 </select>

 <select class="form-control" ng-model="selectedList">
   <option ng-repeat="item in downloadedLists" value="{{$index}}">{{$index}}</option>
 </select>
</div>
</code>```

答:
```<code> <option value="">N/A </option>
 <option ng-repeat="item in boards" value="{{$index}}">{{$index}}</option>
</code>```

Body:
can someone tell me how can I make empty value, that if nothing is in list of select, show "n/a"

demo

https://codepen.io/Turqus/pen/wPrKrr?editors=1010

template

  <select class="form-control" ng-model="selectedBoard" ng-change="changeBoard(selectedBoard)">
     <option ng-repeat="item in boards" value="{{$index}}">{{$index}}</option>
 </select>

 <select class="form-control" ng-model="selectedList">
   <option ng-repeat="item in downloadedLists" value="{{$index}}">{{$index}}</option>
 </select>


问:
Submit form confirm alert sweet_alert.min.js
I am using the library js / sweet_alert.min.js, I need that when confirming the alert the form is sent and I can not do this.form.submit(); is not working

JS:

```<code>$('#sweet_warning').on('click', function() {
    e.preventDefault();
    var form = $(this).parents('form');
    swal({
        title: "¿Está seguro que desea cargar esta mesa?",
        text: "",
        type: "warning",
        showCancelButton: true,
        cancelButtonText: "Cancelar",
        confirmButtonColor: "#FF7043",
        confirmButtonText: "Aceptar"
    },
    function(isConfirm){
         form.submit();
    }
    );
});
</code>```

HTML:

```<code><form method="post" action="">
  <button type="button" name="submiti" id="sweet_warning" class="btn bg-warning">
    Ingresar <i class="icon-circle-right2 position-right"></i>
  </button>
</form>
</code>```

答:
Forget previous version and use this snippet in latest version version 2:

$('#sweet_warning').on('click', function(e) {
  e.preventDefault();
  swal({
    title: "¿Está seguro que desea cargar esta mesa?",
    text: "",
    buttons: {
      text: "Aceptar!",
      cancel: "Cancelar!"
    }
  }).then(
    function(isConfirm) {
      alert(isConfirm)
      if(isConfirm){
        $('#your_form').submit();
      }
    }
  );
});```
<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://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>

<form method="post" action="" id="your_form">
  <button type="button" name="submiti" id="sweet_warning" class="btn bg-warning">
    Ingresar <i class="icon-circle-right2 position-right"></i>
  </button>
</form></code>```

Body:
I am using the library js / sweet_alert.min.js, I need that when confirming the alert the form is sent and I can not do this.form.submit(); is not working

JS:

$('#sweet_warning').on('click', function() {
    e.preventDefault();
    var form = $(this).parents('form');
    swal({
        title: "¿Está seguro que desea cargar esta mesa?",
        text: "",
        type: "warning",
        showCancelButton: true,
        cancelButtonText: "Cancelar",
        confirmButtonColor: "#FF7043",
        confirmButtonText: "Aceptar"
    },
    function(isConfirm){
         form.submit();
    }
    );
});

HTML:

<form method="post" action="">
  <button type="button" name="submiti" id="sweet_warning" class="btn bg-warning">
    Ingresar
  </button>
</form>

Body:
Forget previous version and use this snippet in latest version version 2:

$('#sweet_warning').on('click', function(e) {
  e.preventDefault();
  swal({
    title: "¿Está seguro que desea cargar esta mesa?",
    text: "",
    buttons: {
      text: "Aceptar!",
      cancel: "Cancelar!"
    }
  }).then(
    function(isConfirm) {
      alert(isConfirm)
      if(isConfirm){
        $('#your_form').submit();
      }
    }
  );
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>

<form method="post" action="" id="your_form">
  <button type="button" name="submiti" id="sweet_warning" class="btn bg-warning">
    Ingresar <i class="icon-circle-right2 position-right"></i>
  </button>
</form>


问:
How to get a stack trace for C++ using gcc with line number information?
We use stack traces in proprietary assert like macro to catch developer mistakes - when error is caught, stack trace is printed.

I find gcc's pair backtrace()/backtrace_symbols() methods insufficient:

Names are mangled

No line information

1st problem can be resolved by abi::__cxa_demangle.

However 2nd problem s more tough. I found replacement for backtrace_symbols().
This is better than gcc's backtrace_symbols(), since it can retrieve line numbers (if compiled with -g) and you don't need to compile with -rdynamic.

Hoverer the code is GNU licenced, so IMHO I can't use it in commercial code.

Any proposal?

P.S.

gdb is capable to print out arguments passed to functions.
     Probably it's already too much to ask for :)

PS 2

Similar question (thanks nobar)

答:
So you want a stand-alone function that prints a stack trace with all of the features that gdb stack traces have and that doesn't terminate your application.  The answer is to automate the launch of gdb in a non-interactive mode to perform just the tasks that you want.

This is done by executing gdb in a child process, using fork(), and scripting it to display a stack-trace while your application waits for it to complete.  This can be performed without the use of a core-dump and without aborting the application.  I learned how to do this from looking at this question: How it's better to invoke gdb from program to print it's stacktrace?

The example posted with that question didn't work for me exactly as written, so here's my "fixed" version (I ran this on Ubuntu 9.04).

```<code>#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
#include <sys/prctl.h>

void print_trace() {
    char pid_buf[30];
    sprintf(pid_buf, "%d", getpid());
    char name_buf[512];
    name_buf[readlink("/proc/self/exe", name_buf, 511)]=0;
    prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY, 0, 0, 0);
    int child_pid = fork();
    if (!child_pid) {
        dup2(2,1); // redirect output to stderr - edit: unnecessary?
        execl("/usr/bin/gdb", "gdb", "--batch", "-n", "-ex", "thread", "-ex", "bt", name_buf, pid_buf, NULL);
        abort(); /* If gdb failed to start */
    } else {
        waitpid(child_pid,NULL,0);
    }
}
</code>```

As shown in the referenced question, gdb provides additional options that you could use.  For example, using "bt full" instead of "bt" produces an even more detailed report (local variables are included in the output).  The manpages for gdb are kind of light, but complete documentation is available here.

Since this is based on gdb, the output includes demangled names, line-numbers, function arguments, and optionally even local variables.  Also, gdb is thread-aware, so you should be able to extract some thread-specific metadata.

Here's an example of the kind of stack traces that I see with this method.

```<code>0x00007f97e1fc2925 in waitpid () from /lib/libc.so.6
[Current thread is 0 (process 15573)]
#0  0x00007f97e1fc2925 in waitpid () from /lib/libc.so.6
#1  0x0000000000400bd5 in print_trace () at ./demo3b.cpp:496
2  0x0000000000400c09 in recursive (i=2) at ./demo3b.cpp:636
3  0x0000000000400c1a in recursive (i=1) at ./demo3b.cpp:646
4  0x0000000000400c1a in recursive (i=0) at ./demo3b.cpp:646
5  0x0000000000400c46 in main (argc=1, argv=0x7fffe3b2b5b8) at ./demo3b.cpp:70
</code>```

Note: I found this to be incompatible with the use of valgrind (probably due to Valgrind's use of a virtual machine).  It also doesn't work when you are running the program inside of a gdb session (can't apply a second instance of "ptrace" to a process).

Body:
So you want a stand-alone function that prints a stack trace with all of the features that gdb stack traces have and that doesn't terminate your application.  The answer is to automate the launch of gdb in a non-interactive mode to perform just the tasks that you want.

This is done by executing gdb in a child process, using fork(), and scripting it to display a stack-trace while your application waits for it to complete.  This can be performed without the use of a core-dump and without aborting the application.  I learned how to do this from looking at this question: How it's better to invoke gdb from program to print it's stacktrace?

The example posted with that question didn't work for me exactly as written, so here's my "fixed" version (I ran this on Ubuntu 9.04).

#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
#include <sys/prctl.h>

void print_trace() {
    char pid_buf[30];
    sprintf(pid_buf, "%d", getpid());
    char name_buf[512];
    name_buf[readlink("/proc/self/exe", name_buf, 511)]=0;
    prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY, 0, 0, 0);
    int child_pid = fork();
    if (!child_pid) {
        dup2(2,1); // redirect output to stderr - edit: unnecessary?
        execl("/usr/bin/gdb", "gdb", "--batch", "-n", "-ex", "thread", "-ex", "bt", name_buf, pid_buf, NULL);
        abort(); /* If gdb failed to start */
    } else {
        waitpid(child_pid,NULL,0);
    }
}

As shown in the referenced question, gdb provides additional options that you could use.  For example, using "bt full" instead of "bt" produces an even more detailed report (local variables are included in the output).  The manpages for gdb are kind of light, but complete documentation is available here.

Since this is based on gdb, the output includes demangled names, line-numbers, function arguments, and optionally even local variables.  Also, gdb is thread-aware, so you should be able to extract some thread-specific metadata.

Here's an example of the kind of stack traces that I see with this method.

0x00007f97e1fc2925 in waitpid () from /lib/libc.so.6
[Current thread is 0 (process 15573)]
#0  0x00007f97e1fc2925 in waitpid () from /lib/libc.so.6
#1  0x0000000000400bd5 in print_trace () at ./demo3b.cpp:496
2  0x0000000000400c09 in recursive (i=2) at ./demo3b.cpp:636
3  0x0000000000400c1a in recursive (i=1) at ./demo3b.cpp:646
4  0x0000000000400c1a in recursive (i=0) at ./demo3b.cpp:646
5  0x0000000000400c46 in main (argc=1, argv=0x7fffe3b2b5b8) at ./demo3b.cpp:70

Note: I found this to be incompatible with the use of valgrind (probably due to Valgrind's use of a virtual machine).  It also doesn't work when you are running the program inside of a gdb session (can't apply a second instance of "ptrace" to a process).

ContentLicense: CC BY-SA 4.0


问:
How do I make it so that when I click on a button in Html How do I make it so the web page redirects itself to the place its supposed to go

 <!DOCTYPE html>

    <title>______</title>
    <button class="btn about">About</button>
    <button class="btn socialmedia">Social Media</button></button>
    <button class="btn profile">Profile</button>
    <button class="btn contact">Contact</button>
    <button class="btn homepage">Homepage</button>```

I want it to be that when they click on contact it brings them to a page that I make that has all the contact info on it.  Please explain in the simplist way possible.

答:
Use the anchor tag:

```<code><a href="http://yourdestination.com">About</a>
</code>```

You can put the button or anything between the anchor tags and it will create the link. Say you wanted an image in there, you would put:

```<code><a href="http://yourdestination.com"><img src="yourimage.png" /></a>
</code>```

If you want to do buttons, I would make a css class on the anchor tag and style it like this:

```<code><a class="button_class" href="http://yourdestination.com">About</a>
</code>```

but you can also put the button right between the anchor:

```<code><a href="http://yourdestination.com"><button class="btn about">About</button></a>
</code>```

Body:
 <!DOCTYPE html>

    <title>______</title>
    <button class="btn about">About</button>
    <button class="btn socialmedia">Social Media</button></button>
    <button class="btn profile">Profile</button>
    <button class="btn contact">Contact</button>
    <button class="btn homepage">Homepage</button>

I want it to be that when they click on contact it brings them to a page that I make that has all the contact info on it.  Please explain in the simplist way possible.

Body:
Use the anchor tag:

<a href="http://yourdestination.com">About</a>

You can put the button or anything between the anchor tags and it will create the link. Say you wanted an image in there, you would put:

<a href="http://yourdestination.com"><img src="yourimage.png" /></a>

If you want to do buttons, I would make a css class on the anchor tag and style it like this:

<a class="button_class" href="http://yourdestination.com">About</a>

but you can also put the button right between the anchor:

<a href="http://yourdestination.com"><button class="btn about">About</button></a>


问:
Javascript local variable technique
I have a simple question related to one-line programming. First an example:

```<code>function test(a)
{
   var b=a.toString();
   return b.replace("a","b");
}
</code>```

It's very simple (this function is, of course, useless), but the question here is little more complicated: What if I was to do this in one line? I have my thoughts, but tell me does this work properly with respect to memory cleanup:

```<code>function test(a)
{
   return (arguments[1]=a.toString()).doSomething().doSomethingMore(arguments[1]);
}
</code>```

This is, of course, an example, but the idea is simple: use arguments as a container for local variables - I'm not sure, but from what I know, when a function is over, arguments are deleted also? Or does create new elements in arguments makes this element defined globally? From my tests, it seems that I'm correct, but I'm curious to see if anyone has tried this? Is this a safe and clean solution?:) Thanks for any comments.

Here are a more real problem with One-Line script problem:

```<code>function (number,limiter)
{
return ((arguments[2] = number.toString().replace(
         new RegExp("(\\d+)(\\d{3})($|"+limiter+")"),
         '$1'+limiter+'$2$3')) == number) ?
            arguments[2] :
            arguments.callee(arguments[2],limiter);
}
</code>```

This one line function do things with given string and return it or parse it recursively to the same function. (on other thread I show how this could be done without recursion, but this is not a case of a problem).

答:
I think you only have to try reading it to realise it's not a "clean" solution!
I'd especially avoid chaining an assignment like that:</p>

```<code>return (arguments[1]=a.toString()).doSomething().doSomethingMore(arguments[1]);
// is this a or a.toString()? it's not clear at a glance -------------^
</code>```

Title: Javascript local variable technique

Body:
I have a simple question related to one-line programming. First an example:

function test(a)
{
   var b=a.toString();
   return b.replace("a","b");
}

It's very simple (this function is, of course, useless), but the question here is little more complicated: What if I was to do this in one line? I have my thoughts, but tell me does this work properly with respect to memory cleanup:

function test(a)
{
   return (arguments[1]=a.toString()).doSomething().doSomethingMore(arguments[1]);
}

This is, of course, an example, but the idea is simple: use arguments as a container for local variables - I'm not sure, but from what I know, when a function is over, arguments are deleted also? Or does create new elements in arguments makes this element defined globally? From my tests, it seems that I'm correct, but I'm curious to see if anyone has tried this? Is this a safe and clean solution?:) Thanks for any comments.

Here are a more real problem with One-Line script problem:

function (number,limiter)
{
return ((arguments[2] = number.toString().replace(
         new RegExp("(\\d+)(\\d{3})($|"+limiter+")"),
         '$1'+limiter+'$2$3')) == number) ?
            arguments[2] :
            arguments.callee(arguments[2],limiter);
}

This one line function do things with given string and return it or parse it recursively to the same function. (on other thread I show how this could be done without recursion, but this is not a case of a problem).

Body:
I think you only have to try reading it to realise it's not a "clean" solution!
I'd especially avoid chaining an assignment like that:

return (arguments[1]=a.toString()).doSomething().doSomethingMore(arguments[1]);
// is this a or a.toString()? it's not clear at a glance -------------^

OwnerDisplayName: RoBorg

ContentLicense: CC BY-SA 2.5


问:
C# + WPF : how should I do proper checks/guards/casts when accessing control values?
This is probably pretty basic, but I'm just picking up C# after many years working with other languages, and I've unfortunately grown used to loose and dynamic typing.  Now, in building a WPF form with a lot of checkboxes, I notice that my code to do simple things like determine whether a checkbox is checked is actually quite complicated due to the need to check for nulls and cast the results.  I end up with helper functions like:

```<code>    private bool isChecked(CheckBox control) {
        return control != null && control.IsChecked != null && control.IsChecked.HasValue && (bool)control.IsChecked;
    }
</code>```

so that in my logic code, I can just do

```<code>    if (isChecked(opticsCheckBox))
    {
        // whatever I need to do if opticsCheckBox is checked
    }
</code>```

Is this the normal way of doing things in C# (with WPF), or am I missing something simple?  Basically I'm finding the nested layers of conditionals to check every object for null all the time to be a warning sign of bad code (and the fact that I could forget a check).  Not sure what I should be doing though.

Should I be using try ... catch everywhere even though the control not being present or checked isn't really an exceptional condition?  That seems to me like it would end up being just as cluttered.

Another example to clarify:
When I would like to write something like:

```<code>    maxWeight = (int)maxWeightComboBox.SelectedItem;
</code>```

I find myself instead writing:

```<code>    if (maxWeightComboBox != null && maxWeightComboBox.SelectedItem != null)
    {
        ComboBoxItem item = (ComboBoxItem)maxWeightComboBox.SelectedItem;
        maxWeight = Int32.Parse(item.Content.ToString());
    }
</code>```

答:
A less verbose form is

```<code>control != null && control.IsChecked == true
</code>```

Remember, a bool?  has three values, true, false, and null, and it's always sufficient to check against a single value. For example, a == true and a != false are the checks, respectively, for when the null works like a false or when the null works like a true.

For your combobox example, I'd use a strongly typed collection to begin with. See wpf: how to make ComboBoxItems hold integers in xaml for an example of how to bind directly to integers, (or if you want separate Content/Value, bind it to a list of KeyValuePairs [for example]) Then use SelectedValue and SelectedValuePath to reduce your value-retrieval code.

Body:
This is probably pretty basic, but I'm just picking up C# after many years working with other languages, and I've unfortunately grown used to loose and dynamic typing.  Now, in building a WPF form with a lot of checkboxes, I notice that my code to do simple things like determine whether a checkbox is checked is actually quite complicated due to the need to check for nulls and cast the results.  I end up with helper functions like:

    private bool isChecked(CheckBox control) {
        return control != null && control.IsChecked != null && control.IsChecked.HasValue && (bool)control.IsChecked;
    }

so that in my logic code, I can just do

    if (isChecked(opticsCheckBox))
    {
        // whatever I need to do if opticsCheckBox is checked
    }

Is this the normal way of doing things in C# (with WPF), or am I missing something simple?  Basically I'm finding the nested layers of conditionals to check every object for null all the time to be a warning sign of bad code (and the fact that I could forget a check).  Not sure what I should be doing though.

Should I be using try ... catch everywhere even though the control not being present or checked isn't really an exceptional condition?  That seems to me like it would end up being just as cluttered.

Another example to clarify:
When I would like to write something like:

    maxWeight = (int)maxWeightComboBox.SelectedItem;

I find myself instead writing:

    if (maxWeightComboBox != null && maxWeightComboBox.SelectedItem != null)
    {
        ComboBoxItem item = (ComboBoxItem)maxWeightComboBox.SelectedItem;
        maxWeight = Int32.Parse(item.Content.ToString());
    }

Body:
A less verbose form is

control != null && control.IsChecked == true

Remember, a bool?  has three values, true, false, and null, and it's always sufficient to check against a single value. For example, a == true and a != false are the checks, respectively, for when the null works like a false or when the null works like a true.

For your combobox example, I'd use a strongly typed collection to begin with. See wpf: how to make ComboBoxItems hold integers in xaml for an example of how to bind directly to integers, (or if you want separate Content/Value, bind it to a list of KeyValuePairs [for example]) Then use SelectedValue and SelectedValuePath to reduce your value-retrieval code.


问:
How to get Sql Temp Table Join with column values that are not in table, replaced by 0
I have 5 temp tables that I want to combine into a new temp table via the month_year column and the prod_id. Where the columns are not prod_id or month_year and values are not available, I want that column's value(e.g. job_amt or received_qty) to be 0.

```<code>#tmp_spoilt_good_job_amt
month_year  job_amt     spoil   good    prod_id
07-2017         40      10        20    2
08-2017         827     0         210   3
09-2017         27      1         27    2
09-2017         732     22        345   3
10-2017         50      0         6     2
10-2017         1130    55        50    3
11-2017         300     0         0     4

#tmp_received_qty
month_year  received_qty    prod_id
 08-2017    32                 2
 08-2017    2500               3
 09-2017    2200               2
 11-2017    2500               4

#tmp_purchase_qty
month_year  purchase_qty    prod_id
 09-2017    11                 2

#tmp_opening_balance
month_year  opening_balance   prod_id
08-2017              32         2
08-2017             2500        3
09-2017               22        2
09-2017             2300        3
10-2017             2163        2
10-2017             2023        3
11-2017             2500        4

#tmp_closing_balance
month_year  closing_balance     prod_id
08-2017         2300                3
08-2017         32                  2
09-2017         2213                2
09-2017         1998                3
10-2017         1687                3
10-2017         2163                2
11-2017         2400                4
</code>```

I tried some inner joins but the values were repeating or some were not reflecting. what query could I use to get these combined?

I am looking for the following output:

答:
Personally, I think you should go with @influent's suggest: derive a template table on to which you can left the values you're looking for.

In the eventuality that you don't have the required logic or data to accurately derive such a template table, there is another option.

  1. Pad out each table with dummy 0 values, so that they all have the same fields

  2. UNION all the tables together

  3. GROUP all the results back down to one row per month per product

```<code>WITH
    padded_combined
AS
(

    SELECT month_year, prod_id, job_amt, spoil, good, 0 AS received_qty, 0 AS purchase_qty, 0 AS opening_balance, 0 AS closing_balance FROM #tmp_spoilt_good_job_amt
    UNION ALL
    SELECT month_year, prod_id, 0, 0, 0, received_qty, 0, 0, 0 FROM #tmp_received_qty
    UNION ALL
    SELECT month_year, prod_id, 0, 0, 0, 0, purchase_qty, 0, 0 FROM #tmp_purchase_qty
    UNION ALL
    SELECT month_year, prod_id, 0, 0, 0, 0, 0, opening_balance, 0 FROM #tmp_opening_balance
    UNION ALL
    SELECT month_year, prod_id, 0, 0, 0, 0, 0, 0, closing_balance FROM #tmp_closing_balance
)
SELECT
    month_year,
    prod_id,
    SUM(job_amt)            AS job_amt,
    SUM(spoil)              AS spoil,
    SUM(good)               AS good,
    SUM(received_qty)       AS received_qty,
    SUM(purchase_qty)       AS purchase_qty,
    SUM(opening_balance)    AS opening_balance,
    SUM(closing_balance)    AS closing_balance
FROM
    padded_combined
GROUP BY
    month_year,
    prod_id
ORDER BY
    month_year,
    prod_id
</code>```

Body:
I have 5 temp tables that I want to combine into a new temp table via the month_year column and the prod_id. Where the columns are not prod_id or month_year and values are not available, I want that column's value(e.g. job_amt or received_qty) to be 0.

#tmp_spoilt_good_job_amt
month_year  job_amt     spoil   good    prod_id
07-2017         40      10        20    2
08-2017         827     0         210   3
09-2017         27      1         27    2
09-2017         732     22        345   3
10-2017         50      0         6     2
10-2017         1130    55        50    3
11-2017         300     0         0     4

#tmp_received_qty
month_year  received_qty    prod_id
 08-2017    32                 2
 08-2017    2500               3
 09-2017    2200               2
 11-2017    2500               4

#tmp_purchase_qty
month_year  purchase_qty    prod_id
 09-2017    11                 2

#tmp_opening_balance
month_year  opening_balance   prod_id
08-2017              32         2
08-2017             2500        3
09-2017               22        2
09-2017             2300        3
10-2017             2163        2
10-2017             2023        3
11-2017             2500        4

#tmp_closing_balance
month_year  closing_balance     prod_id
08-2017         2300                3
08-2017         32                  2
09-2017         2213                2
09-2017         1998                3
10-2017         1687                3
10-2017         2163                2
11-2017         2400                4

I tried some inner joins but the values were repeating or some were not reflecting. what query could I use to get these combined?

I am looking for the following output:

Body:
Personally, I think you should go with @influent's suggest: derive a template table on to which you can left the values you're looking for.

In the eventuality that you don't have the required logic or data to accurately derive such a template table, there is another option.

  1. Pad out each table with dummy 0 values, so that they all have the same fields

  2. UNION all the tables together

  3. GROUP all the results back down to one row per month per product

WITH
    padded_combined
AS
(

    SELECT month_year, prod_id, job_amt, spoil, good, 0 AS received_qty, 0 AS purchase_qty, 0 AS opening_balance, 0 AS closing_balance FROM #tmp_spoilt_good_job_amt
    UNION ALL
    SELECT month_year, prod_id, 0, 0, 0, received_qty, 0, 0, 0 FROM #tmp_received_qty
    UNION ALL
    SELECT month_year, prod_id, 0, 0, 0, 0, purchase_qty, 0, 0 FROM #tmp_purchase_qty
    UNION ALL
    SELECT month_year, prod_id, 0, 0, 0, 0, 0, opening_balance, 0 FROM #tmp_opening_balance
    UNION ALL
    SELECT month_year, prod_id, 0, 0, 0, 0, 0, 0, closing_balance FROM #tmp_closing_balance
)
SELECT
    month_year,
    prod_id,
    SUM(job_amt)            AS job_amt,
    SUM(spoil)              AS spoil,
    SUM(good)               AS good,
    SUM(received_qty)       AS received_qty,
    SUM(purchase_qty)       AS purchase_qty,
    SUM(opening_balance)    AS opening_balance,
    SUM(closing_balance)    AS closing_balance
FROM
    padded_combined
GROUP BY
    month_year,
    prod_id
ORDER BY
    month_year,
    prod_id


问:
Full-width image with aspect ratio in React Native
I want to require() a static image in a Home screen component I've written, and I want that image to be the full width of the display (which here happens to also be the full width of the container) while maintaining the aspect ratio.

Here is what I have so far. The Home component:

```<code>import React, { Component } from "react";
import {
    StatusBar,
} from "react-native";

import Container from "../components/Container/Container";
import Header from "../components/Header/Header";
import FullWidthImage from "../components/Images/FullWidthImage";

export default class Home extends Component {
    render() {
        return (
            <Container>
                <FullWidthImage source={require("./lifting.jpg")}/>
                <Header/>
                <StatusBar translucent={false}/>
            </Container>
        );
    }
}
</code>```

And the FullWidthImage component:

```<code>import React, { Component } from "react";
import { View, Image, StyleSheet } from "react-native";

import Proptypes from "prop-types";

export default class FullWidthImage extends Component {
    render() {
        return (
            <Image source={this.props.source} style={style.image} resizeMode="contain"/>
        );
    }
}

const style = StyleSheet.create({
    image: {
        flex: 1,
        width: "100%",
        borderColor: "red", borderWidth: 2,
    }
});
</code>```

I've been trying for a while and looking around on SO for a good answer but I can't find one (for an example some of them assume you have an uri and are not using require()). Greatly appreciate the help!

答:
You can use the not so well documented library resolveAssetSource.

Like this:

```<code>import {
  Platform,
  StyleSheet,
  Text,
  Image,
  View,
  Dimensions,
} from 'react-native';
var resolveAssetSource = require('resolveAssetSource');
var imgSrc = resolveAssetSource(require('./200x150.png'));
console.log(imgSrc.width, imgSrc.height);
const SCREEN_WIDTH = Dimensions.get('window').width;
const IMAGE_RATIO = imgSrc.height/imgSrc.width;
...
<Image source={imgSrc}
style={{width:SCREEN_WIDTH, height:SCREEN_WIDTH*IMAGE_RATIO}}/>
...
</code>```

The important being:  var imgSrc = resolveAssetSource(require('./200x150.png'));

I used this issue to get the answer, and then I went and try it ; )
https://github.com/facebook/react-native/issues/4025

Body:
I want to require() a static image in a Home screen component I've written, and I want that image to be the full width of the display (which here happens to also be the full width of the container) while maintaining the aspect ratio.

Here is what I have so far. The Home component:

import React, { Component } from "react";
import {
    StatusBar,
} from "react-native";

import Container from "../components/Container/Container";
import Header from "../components/Header/Header";
import FullWidthImage from "../components/Images/FullWidthImage";

export default class Home extends Component {
    render() {
        return (
            <Container>
                <FullWidthImage source={require("./lifting.jpg")}/>

                <StatusBar translucent={false}/>
            </Container>
        );
    }
}

And the FullWidthImage component:

import React, { Component } from "react";
import { View, Image, StyleSheet } from "react-native";

import Proptypes from "prop-types";

export default class FullWidthImage extends Component {
    render() {
        return (
            <Image source={this.props.source} style={style.image} resizeMode="contain"/>
        );
    }
}

const style = StyleSheet.create({
    image: {
        flex: 1,
        width: "100%",
        borderColor: "red", borderWidth: 2,
    }
});

I've been trying for a while and looking around on SO for a good answer but I can't find one (for an example some of them assume you have an uri and are not using require()). Greatly appreciate the help!

Body:
You can use the not so well documented library resolveAssetSource.

Like this:

import {
  Platform,
  StyleSheet,
  Text,
  Image,
  View,
  Dimensions,
} from 'react-native';
var resolveAssetSource = require('resolveAssetSource');
var imgSrc = resolveAssetSource(require('./200x150.png'));
console.log(imgSrc.width, imgSrc.height);
const SCREEN_WIDTH = Dimensions.get('window').width;
const IMAGE_RATIO = imgSrc.height/imgSrc.width;
...
<Image source={imgSrc}
style={{width:SCREEN_WIDTH, height:SCREEN_WIDTH*IMAGE_RATIO}}/>
...

The important being:  var imgSrc = resolveAssetSource(require('./200x150.png'));

I used this issue to get the answer, and then I went and try it ; )
https://github.com/facebook/react-native/issues/4025


问:
How do I move fields of data from all documents in one collection into new documents of a different collection?
My Situation: I created an Mongo (mongoose), Express, and Node app and now that I'm building additional features, I've realized my models won't handle the new features, so I built a new model that's future proof, but I need to move some fields of data from my old model, User, to my new model, List.

What is the best way of moving document data from all of a specific field within one collection of documents into a new document within a new collection? Can I create a script with JavaScript and run it against my server or database?

I don't want to disrupt my users' experience, if all possible. Also, I know there is the db.collection.update method, but I need to move all this data all at once, not whenever I run that method in my app.

答:
You can script it in many ways, but it's probably simplest to:

Use aggregate with an $out stage at the end of the pipeline to populate a new collection from the original documents. Use a $project stage in the pipeline to structure the output documents as desired.

Use updateMany on the original collection to remove the "moved" fields using the $unset operator.

Depending on the specifics of your system, you may still need to take the users offline while you do this.


问:
Can't seem to center two floated tags
I'm trying to float two items within a div next to each, an  and an
. I'm trying inline-block but it doesn't seem to work. I want the  and
 to be centered within its div. Also, if it can be done, I want the
 to be even with the center of the  on the left. Equal distance from the top as from the below.

body {
  background-color: #FDFDFD;
  font-family: 'Audiowide', cursive;
  margin: 0;
}

.yaboi,
.hd2 {
  background-color: white;
  width: 80%;
  margin: auto;
  height: 100%;
}

.plswork {
  margin-left: auto;
  margin-right: auto;
  /* display:inline-block; */
}

.yaboi .plswork h1 {
  display: inline-block;
  text-align: center;
  float: left;
}

.yaboi .plswork img {
  display: inline-block;
  width: 50%;
  float: left;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body style="background-color: #f2f2f2;">
  <div class="yaboi">
    <div class="plswork">
      <img src="188104.jpg" alt="PC with keyboard and mouse" />
      <h1>Falcon Tech</h1>
    </div>
  </div>
  <div class="hd2">
  </div>
</body></code>```

答:
There are a few ways to do this. Since you mentioned that you are attempting to achieve this using inline-block elements I will show how to do that first:

```<code>.plswork {
    text-align: center;
}
.plswork img,
.plswork h1 {
    display: inline-block;
    vertical-align: middle;
}

<div class="plswork">
    <img src="http://via.placeholder.com/100x10">
    <h1>Falcon Tech</h1>
</div>
</code>```

Fiddle: https://jsfiddle.net/4s4Lmhnn/

Floats are not typically suitable for horizontal centering, so you will notice that my solution does not make use of floats.

It is unclear from your question whether you want horizontal or vertical centering within the containing element . I have assumed that you only want horizontal centering, though my solution does align the img and h1 vertically relative to one another.

If, instead, you need both elements to be vertically centered inside a container of unknown height then flexbox is a good option:

```<code>.plswork {
  display: flex;
  height: 200px;
  align-items: center;
  justify-content: center;
}
</code>```

Fiddle: https://jsfiddle.net/3hxb2xo3/2/

Title: Can't seem to center two floated tags

Body:
I'm trying to float two items within a div next to each, an  and an
. I'm trying inline-block but it doesn't seem to work. I want the  and
 to be centered within its div. Also, if it can be done, I want the
 to be even with the center of the  on the left. Equal distance from the top as from the below.

body {
  background-color: #FDFDFD;
  font-family: 'Audiowide', cursive;
  margin: 0;
}

.yaboi,
.hd2 {
  background-color: white;
  width: 80%;
  margin: auto;
  height: 100%;
}

.plswork {
  margin-left: auto;
  margin-right: auto;
  /* display:inline-block; */
}

.yaboi .plswork h1 {
  display: inline-block;
  text-align: center;
  float: left;
}

.yaboi .plswork img {
  display: inline-block;
  width: 50%;
  float: left;
}

Falcon Tech

Body:
There are a few ways to do this. Since you mentioned that you are attempting to achieve this using inline-block elements I will show how to do that first:

.plswork {
    text-align: center;
}
.plswork img,
.plswork h1 {
    display: inline-block;
    vertical-align: middle;
}

<div class="plswork">
    <img src="http://via.placeholder.com/100x10">
    <h1>Falcon Tech</h1>
</div>

Fiddle: https://jsfiddle.net/4s4Lmhnn/

Floats are not typically suitable for horizontal centering, so you will notice that my solution does not make use of floats.

It is unclear from your question whether you want horizontal or vertical centering within the containing element . I have assumed that you only want horizontal centering, though my solution does align the img and h1 vertically relative to one another.

If, instead, you need both elements to be vertically centered inside a container of unknown height then flexbox is a good option:

.plswork {
  display: flex;
  height: 200px;
  align-items: center;
  justify-content: center;
}

Fiddle: https://jsfiddle.net/3hxb2xo3/2/