问:
Unable to center content using margin auto
When the screen size is less than 768px, the 3 boxes are aligned to the left. I'm having a hard time trying to make them appear center.

I managed to center it by setting margin-left to some value however, it isn't responsive afterwards.

Here's the code:

HTML

```<code><meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<body>
      <div class="row bg_color">
            <div class="col-xs-12 col-sm-4 col-md-4 stats_box">
               <h3>2015/16</h3>
               <hr>
               <ul>
                  <li>The Best FIFA Men's Player 2016</li>
                  <li>FIFA Club World Cup</li>
                  <li>France Football Ballon D'Or 2016</li>
                  <li>UEFA Best Player in Europe</li>
                  <li>UEFA Euro 2016 (Portugal)</li>
                  <li>UEFA Champions League (Real Madrid)</li>
               </ul>
            </div>
            <div class="col-xs-12 col-sm-4 col-md-4 stats_box">
               <h3>2014/15</h3>
               <hr>
               <ul>
                  <li>Pichichi Award</li>
                  <li>European Golden Boot 2015</li>
                  <li>FIFA Ballon D'Or 2014</li>
                  <li>Globe Soccer Best Player of the Year</li>
                  <li>Globe Soccer Fan's Favourite Player Award</li>
                  <li>IFFHS Trophy for Best Striker  on the planet</li>
               </ul>
            </div>
            <div class="col-xs-12 col-sm-4 col-md-4 stats_box">
               <h3>2013/14</h3>
               <hr>
               <ul>
                  <li>Club World Cup</li>
                  <li>BBC Overseas Sports  Personality Award</li>
                  <li>World's Top  Goalscorer 2013</li>
                  <li>Pichichi Award</li>
                  <li>Best Player, Best Forward in La Liga</li>
                  <li>UEFA Best Player in Europe</li>
               </ul>
            </div>
         </div>

</body>
</code>```

CSS:

```<code> .bg_color {
    background: #ECFEAA;
}

.stats_box {
    margin: 20px;
    padding: 20px 40px 40px;
    max-width: 400px;
    text-align: left;
    background: #fff;
    border-bottom: 4px solid #ccc;
    border-radius: 6px;

}

@media only screen and (max-width: 768px) {
  .stats_box {
    width: 100%;
    margin-left: 200px;
  }
}
</code>```

Any possible solution for this? And why isn't margin:0 auto not working here?

Link to the code: CodePen

答:
Add the following to your CSS to center the 3 boxes.</p>

```<code>.row.bg_color {
  display: flex;
  justify-content: center;
}
</code>```

Body:
When the screen size is less than 768px, the 3 boxes are aligned to the left. I'm having a hard time trying to make them appear center.

I managed to center it by setting margin-left to some value however, it isn't responsive afterwards.

Here's the code:

HTML

<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

2015/16

The Best FIFA Men's Player 2016

FIFA Club World Cup

France Football Ballon D'Or 2016

UEFA Best Player in Europe

UEFA Euro 2016 (Portugal)

UEFA Champions League (Real Madrid)

2014/15

Pichichi Award

European Golden Boot 2015

FIFA Ballon D'Or 2014

Globe Soccer Best Player of the Year

Globe Soccer Fan's Favourite Player Award

IFFHS Trophy for Best Striker  on the planet

2013/14

Club World Cup

BBC Overseas Sports  Personality Award

World's Top  Goalscorer 2013

Pichichi Award

Best Player, Best Forward in La Liga

UEFA Best Player in Europe

CSS:

 .bg_color {
    background: #ECFEAA;
}

.stats_box {
    margin: 20px;
    padding: 20px 40px 40px;
    max-width: 400px;
    text-align: left;
    background: #fff;
    border-bottom: 4px solid #ccc;
    border-radius: 6px;

}

@media only screen and (max-width: 768px) {
  .stats_box {
    width: 100%;
    margin-left: 200px;
  }
}

Any possible solution for this? And why isn't margin:0 auto not working here?

Link to the code: CodePen

Body:
Add the following to your CSS to center the 3 boxes.

.row.bg_color {
  display: flex;
  justify-content: center;
}


来源: stackexchange

问:
$(window).height() not working in iPad fullscreen web app
I'm working on a web application that is nicely displayed in mobile Safari for iPad.

It eventually plays well when a shortcut is saved to the springboard, having put together the right metatags for displaying a springboard icon, splash screen and so on.

Unfortunately the app uses $(window).width() and $(window).height() and often (not always, and no, I cannot say when, I'm going crazy about that) the $(window).height() invocation returns 0.

I have to know the size for setting images width and height dynamically according to the viewport size and orientation. The application also use jQuery-ui and jQGrid and, when the height evaluates to 0, they both break.

The jq-ui dialogs displayed on top of the screen instead of in the middle, and the tables are not displaying correctly either.

答:
It's because of the viewport. On a regular screen, it's a basic X by Y coordinate plane. On touch screen, think of the viewport a small piece of paper that you move around ontop of a large piece of paper (the website). Here's a blurb from a post that might help:

Mobile Safari uses a viewport to show you websites. Imagine a book in front of you. Take a piece of paper, cut a 320×416 square in it, and lay it over the book. To read the book, move the paper around and position the hole over the words you want to see. This is exactly what Mobile Safari’s viewport is doing. When you flick and scroll, you’re moving the viewport around while the website behind it stays static.

Because of this issue, you may have trouble obtaining the values you need. Below is a link to that post. Hopefully this will shed some light on positioning in regards to touch screen applications

http://doctyper.com/archives/200808/fixed-positioning-on-mobile-safari/

Additionally, Lee is correct that you need to make sure that you're document is ready.

ContentLicense: CC BY-SA 2.5


问:
How to load more data in recycler view from server?
I have a recycler view in which I load some data from the server when user scroll to bottom I want to show a progress bar and send another request to the server for more data. I have tried below code but it not able to load more data from the server. please help</p>

```<code>   private RecyclerView mRecyclerView;
    private List<User> mUsers = new ArrayList<>();
    private UserAdapter mUserAdapter;
    private static String sz_RecordCount;
    private static String sz_LastCount;
    private final int m_n_DefaultRecordCount = m_kDEFAULT_RECORD_COUNT;
    private static final int m_kDEFAULT_RECORD_COUNT = 5;
    private ArrayList<CDealAppDatastorage> s_oDataset;
    private String TAG = MainActivity.class.getSimpleName();
    private CDealAppDatastorage item;
    private static int arrayCount;
    private Context context;
    private PreferenceHelper m_oPreferenceHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context = MainActivity.this;
        m_oPreferenceHelper = new PreferenceHelper(context);

        sz_RecordCount = String.valueOf(m_n_DefaultRecordCount);// increment of record count
        int intialLastCount = 0;
        sz_LastCount = String.valueOf(intialLastCount);// increment of last count...

        s_oDataset = new ArrayList<>();// making object of Arraylist
        //initial request for data
        initalDealListing();

        mRecyclerView = (RecyclerView) findViewById(R.id.recycleView);

        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mUserAdapter = new UserAdapter();

        mUserAdapter.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                Log.e("haint", "Load More");
                mUsers.add(null);
                mUserAdapter.notifyItemInserted(mUsers.size() - 1);

                //Load more data for reyclerview
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Log.e("haint", "Load More 2");

                        //Remove loading item
                        mUsers.remove(mUsers.size() - 1);
                        mUserAdapter.notifyItemRemoved(mUsers.size());
                        //sending request to server for more data
                        moreDealsRequest();

                        mUserAdapter.notifyDataSetChanged();
                        mUserAdapter.setLoaded();
                    }
                }, 5000);
            }
        });
    }

    private void initalDealListing() {
        String m = "9565656565";
        String p = "D55A8077E0208A5C5B25176608EF84BD";
        // 3. build jsonObject
        try {
            final JSONObject jsonObject = new JSONObject();// making object of Jsons.
            jsonObject.put("agentCode", m.trim());// put mobile number
            jsonObject.put("pin", p.trim());// put password
            jsonObject.put("recordcount", sz_RecordCount.trim());// put record count
            jsonObject.put("lastcountvalue", sz_LastCount.trim());// put last count
            Log.e("CAppList:", sz_RecordCount);
            Log.e("Capplist:", sz_LastCount);
            Log.d(TAG, "Server Request:-" + jsonObject.toString());
            final String m_DealListingURL = APIStorage.IREWARDS_URL + APIStorage.DEALLISTING_URL;
            JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, m_DealListingURL, jsonObject, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    Log.d(TAG, "Server Response:-" + response);

                    try {
                        int nResultCodeFromServer = Integer.parseInt(response.getString(ServerResponseStorage.s_szRESULT_CODE));
                        if (nResultCodeFromServer == ConstantInt.m_kTRANSACTION_SUCCESS) {

                            JSONArray posts = response.optJSONArray(ServerResponseStorage.s_szDEAL_ARRAY);// get Deal list in array from response
                            s_oDataset.clear();
                            for (int i = 0; i < posts.length(); i++) {// loop for counting deals from server
                                try {
                                    JSONObject post = posts.getJSONObject(i);// counting deal based on index
                                    item = new CDealAppDatastorage();// creating object of DealAppdata storage
                                    item.setM_szHeaderText(post.getString(ServerResponseStorage.s_szDEAL_NAME));// get deal name from response
                                    item.setM_szsubHeaderText(post.getString(ServerResponseStorage.s_szDEAL_CODE));// get dealcode from response
                                    s_oDataset.add(item);// add all items in ArrayList
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                            arrayCount = posts.length();
                            Log.d(TAG, "ArrayCount::" + arrayCount);
                            /*here we are storing no. of deals coming from server*/
                            // write
                            m_oPreferenceHelper.saveIntegerValue("LastCountLength", arrayCount);
                            if (!s_oDataset.isEmpty()) {// condition if data in arraylist is not empty
                                mRecyclerView.setAdapter(mUserAdapter);
                            }

                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.d(TAG, "Server error:-" + error);
                }
            });
            RequestQueue requestQueue = Volley.newRequestQueue(context);
            jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(ConstantInt.INITIAL_TIMEOUT_MS, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
            requestQueue.add(jsonObjectRequest);
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    /*This method send request to server for more deals*/
    private void moreDealsRequest() {
        try {
            // 3. build jsonObject
            final JSONObject jsonObject = new JSONObject();// making object of Jsons.
            jsonObject.put(ServerRequestKeyStorage.s_szAGENT_CODE, "9565656565");// put mobile number
            jsonObject.put(ServerRequestKeyStorage.s_szPASSWORD, "D55A8077E0208A5C5B25176608EF84BD");// put password
            jsonObject.put(ServerRequestKeyStorage.s_szRECORD_COUNT, sz_RecordCount.trim());// put record count
            jsonObject.put(ServerRequestKeyStorage.s_szLAST_COUNT, sz_LastCount.trim());// put last count
            Log.e("CAppList:", sz_RecordCount);
            Log.e("Capplist:", sz_LastCount);
            // 4. convert JSONObject to JSON to String

            Log.e(TAG, "Server Request:-" + jsonObject.toString());
            RequestQueue requestQueue = Volley.newRequestQueue(context);
            final String imgPath = APIStorage.IREWARDS_URL + APIStorage.DEAL_IMAGE_PATH;
            final String m_DealListingURL = APIStorage.IREWARDS_URL + APIStorage.DEALLISTING_URL;
            JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, m_DealListingURL, jsonObject, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    Log.e(TAG, "Server Response:-" + response);
                    try {
                        int nResultCodeFromServer = Integer.parseInt(response.getString(ServerResponseStorage.s_szRESULT_CODE));

                        if (nResultCodeFromServer == ConstantInt.m_kTRANSACTION_SUCCESS) {
                            // Select the last row so it will scroll into view...
                            JSONArray posts = response.optJSONArray(ServerResponseStorage.s_szDEAL_ARRAY);// GETTING DEAL LIST
                            for (int i = 0; i < posts.length(); i++) {
                                try {
                                    JSONObject post = posts.getJSONObject(i);// GETTING DEAL AT POSITION AT I
                                    item = new CDealAppDatastorage();// object create of DealAppdatastorage
                                    item.setM_szHeaderText(post.getString(ServerResponseStorage.s_szDEAL_NAME));//getting deal name
                                    item.setM_szsubHeaderText(post.getString(ServerResponseStorage.s_szDEAL_CODE));// getting deal code
                                    s_oDataset.add(item);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }

                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.d(TAG, "Server Error::" + error);
                }
            });
            jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(ConstantInt.INITIAL_TIMEOUT_MS, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
            requestQueue.add(jsonObjectRequest);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    static class UserViewHolder extends RecyclerView.ViewHolder {
        public TextView tvName;
        public TextView tvEmailId;

        public UserViewHolder(View itemView) {
            super(itemView);
            tvName = (TextView) itemView.findViewById(R.id.tvName);

            tvEmailId = (TextView) itemView.findViewById(R.id.tvEmailId);
        }
    }

    static class LoadingViewHolder extends RecyclerView.ViewHolder {
        public ProgressBar progressBar;

        public LoadingViewHolder(View itemView) {
            super(itemView);
            progressBar = (ProgressBar) itemView.findViewById(R.id.progressBar1);
        }
    }

    class UserAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

        private final int VIEW_TYPE_ITEM = 0;
        private final int VIEW_TYPE_LOADING = 1;

        private OnLoadMoreListener mOnLoadMoreListener;

        private boolean isLoading;
        private int visibleThreshold = 5;
        private int lastVisibleItem, totalItemCount;

        public UserAdapter() {
            final LinearLayoutManager linearLayoutManager = (LinearLayoutManager) mRecyclerView.getLayoutManager();
            mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
                @Override
                public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                    super.onScrolled(recyclerView, dx, dy);

                    totalItemCount = linearLayoutManager.getItemCount();
                    lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition();

                    if (!isLoading && totalItemCount <= (lastVisibleItem + visibleThreshold)) {
                        if (mOnLoadMoreListener != null) {
                            mOnLoadMoreListener.onLoadMore();
                        }
                        isLoading = true;
                    }
                }
            });
        }

        public void setOnLoadMoreListener(OnLoadMoreListener mOnLoadMoreListener) {
            this.mOnLoadMoreListener = mOnLoadMoreListener;
        }

        @Override
        public int getItemViewType(int position) {
            return s_oDataset.get(position) == null ? VIEW_TYPE_LOADING : VIEW_TYPE_ITEM;
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            if (viewType == VIEW_TYPE_ITEM) {
                View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.layout_user_item, parent, false);
                return new UserViewHolder(view);
            } else if (viewType == VIEW_TYPE_LOADING) {
                View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.layout_loading_item, parent, false);
                return new LoadingViewHolder(view);
            }
            return null;
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
            if (holder instanceof UserViewHolder) {
                CDealAppDatastorage user = s_oDataset.get(position);
                UserViewHolder userViewHolder = (UserViewHolder) holder;
                userViewHolder.tvName.setText(user.getM_szHeaderText());
                userViewHolder.tvEmailId.setText(user.getM_szsubHeaderText());
            } else if (holder instanceof LoadingViewHolder) {
                LoadingViewHolder loadingViewHolder = (LoadingViewHolder) holder;
                loadingViewHolder.progressBar.setIndeterminate(true);
            }
        }

        @Override
        public int getItemCount() {
            return s_oDataset == null ? 0 : s_oDataset.size();
        }

        public void setLoaded() {
            isLoading = false;
        }
    }
}
</code>```

答:
Fetching the data from server is a Async Task. So you need to enclose the
updation code in a runOnUiThread runnable. to change UI.</p>

```<code>runOnUiThread(new Runnable() {
   @Override
   public void run() {
      mUsers.remove(mUsers.size() - 1);
      mUserAdapter.notifyItemRemoved(mUsers.size());
      //sending request to server for more data
      moreDealsRequest();
      mUserAdapter.notifyDataSetChanged();
      mUserAdapter.setLoaded();
}});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a recycler view in which I load some data from the server when user scroll to bottom I want to show a progress bar and send another request to the server for more data. I have tried below code but it not able to load more data from the server. please help

   private RecyclerView mRecyclerView;
    private List<User> mUsers = new ArrayList<>();
    private UserAdapter mUserAdapter;
    private static String sz_RecordCount;
    private static String sz_LastCount;
    private final int m_n_DefaultRecordCount = m_kDEFAULT_RECORD_COUNT;
    private static final int m_kDEFAULT_RECORD_COUNT = 5;
    private ArrayList<CDealAppDatastorage> s_oDataset;
    private String TAG = MainActivity.class.getSimpleName();
    private CDealAppDatastorage item;
    private static int arrayCount;
    private Context context;
    private PreferenceHelper m_oPreferenceHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context = MainActivity.this;
        m_oPreferenceHelper = new PreferenceHelper(context);

        sz_RecordCount = String.valueOf(m_n_DefaultRecordCount);// increment of record count
        int intialLastCount = 0;
        sz_LastCount = String.valueOf(intialLastCount);// increment of last count...

        s_oDataset = new ArrayList<>();// making object of Arraylist
        //initial request for data
        initalDealListing();

        mRecyclerView = (RecyclerView) findViewById(R.id.recycleView);

        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mUserAdapter = new UserAdapter();

        mUserAdapter.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                Log.e("haint", "Load More");
                mUsers.add(null);
                mUserAdapter.notifyItemInserted(mUsers.size() - 1);

                //Load more data for reyclerview
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Log.e("haint", "Load More 2");

                        //Remove loading item
                        mUsers.remove(mUsers.size() - 1);
                        mUserAdapter.notifyItemRemoved(mUsers.size());
                        //sending request to server for more data
                        moreDealsRequest();

                        mUserAdapter.notifyDataSetChanged();
                        mUserAdapter.setLoaded();
                    }
                }, 5000);
            }
        });
    }

    private void initalDealListing() {
        String m = "9565656565";
        String p = "D55A8077E0208A5C5B25176608EF84BD";
        // 3. build jsonObject
        try {
            final JSONObject jsonObject = new JSONObject();// making object of Jsons.
            jsonObject.put("agentCode", m.trim());// put mobile number
            jsonObject.put("pin", p.trim());// put password
            jsonObject.put("recordcount", sz_RecordCount.trim());// put record count
            jsonObject.put("lastcountvalue", sz_LastCount.trim());// put last count
            Log.e("CAppList:", sz_RecordCount);
            Log.e("Capplist:", sz_LastCount);
            Log.d(TAG, "Server Request:-" + jsonObject.toString());
            final String m_DealListingURL = APIStorage.IREWARDS_URL + APIStorage.DEALLISTING_URL;
            JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, m_DealListingURL, jsonObject, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    Log.d(TAG, "Server Response:-" + response);

                    try {
                        int nResultCodeFromServer = Integer.parseInt(response.getString(ServerResponseStorage.s_szRESULT_CODE));
                        if (nResultCodeFromServer == ConstantInt.m_kTRANSACTION_SUCCESS) {

                            JSONArray posts = response.optJSONArray(ServerResponseStorage.s_szDEAL_ARRAY);// get Deal list in array from response
                            s_oDataset.clear();
                            for (int i = 0; i < posts.length(); i++) {// loop for counting deals from server
                                try {
                                    JSONObject post = posts.getJSONObject(i);// counting deal based on index
                                    item = new CDealAppDatastorage();// creating object of DealAppdata storage
                                    item.setM_szHeaderText(post.getString(ServerResponseStorage.s_szDEAL_NAME));// get deal name from response
                                    item.setM_szsubHeaderText(post.getString(ServerResponseStorage.s_szDEAL_CODE));// get dealcode from response
                                    s_oDataset.add(item);// add all items in ArrayList
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                            arrayCount = posts.length();
                            Log.d(TAG, "ArrayCount::" + arrayCount);
                            /*here we are storing no. of deals coming from server*/
                            // write
                            m_oPreferenceHelper.saveIntegerValue("LastCountLength", arrayCount);
                            if (!s_oDataset.isEmpty()) {// condition if data in arraylist is not empty
                                mRecyclerView.setAdapter(mUserAdapter);
                            }

                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.d(TAG, "Server error:-" + error);
                }
            });
            RequestQueue requestQueue = Volley.newRequestQueue(context);
            jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(ConstantInt.INITIAL_TIMEOUT_MS, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
            requestQueue.add(jsonObjectRequest);
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    /*This method send request to server for more deals*/
    private void moreDealsRequest() {
        try {
            // 3. build jsonObject
            final JSONObject jsonObject = new JSONObject();// making object of Jsons.
            jsonObject.put(ServerRequestKeyStorage.s_szAGENT_CODE, "9565656565");// put mobile number
            jsonObject.put(ServerRequestKeyStorage.s_szPASSWORD, "D55A8077E0208A5C5B25176608EF84BD");// put password
            jsonObject.put(ServerRequestKeyStorage.s_szRECORD_COUNT, sz_RecordCount.trim());// put record count
            jsonObject.put(ServerRequestKeyStorage.s_szLAST_COUNT, sz_LastCount.trim());// put last count
            Log.e("CAppList:", sz_RecordCount);
            Log.e("Capplist:", sz_LastCount);
            // 4. convert JSONObject to JSON to String

            Log.e(TAG, "Server Request:-" + jsonObject.toString());
            RequestQueue requestQueue = Volley.newRequestQueue(context);
            final String imgPath = APIStorage.IREWARDS_URL + APIStorage.DEAL_IMAGE_PATH;
            final String m_DealListingURL = APIStorage.IREWARDS_URL + APIStorage.DEALLISTING_URL;
            JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, m_DealListingURL, jsonObject, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    Log.e(TAG, "Server Response:-" + response);
                    try {
                        int nResultCodeFromServer = Integer.parseInt(response.getString(ServerResponseStorage.s_szRESULT_CODE));

                        if (nResultCodeFromServer == ConstantInt.m_kTRANSACTION_SUCCESS) {
                            // Select the last row so it will scroll into view...
                            JSONArray posts = response.optJSONArray(ServerResponseStorage.s_szDEAL_ARRAY);// GETTING DEAL LIST
                            for (int i = 0; i < posts.length(); i++) {
                                try {
                                    JSONObject post = posts.getJSONObject(i);// GETTING DEAL AT POSITION AT I
                                    item = new CDealAppDatastorage();// object create of DealAppdatastorage
                                    item.setM_szHeaderText(post.getString(ServerResponseStorage.s_szDEAL_NAME));//getting deal name
                                    item.setM_szsubHeaderText(post.getString(ServerResponseStorage.s_szDEAL_CODE));// getting deal code
                                    s_oDataset.add(item);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }

                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.d(TAG, "Server Error::" + error);
                }
            });
            jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(ConstantInt.INITIAL_TIMEOUT_MS, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
            requestQueue.add(jsonObjectRequest);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    static class UserViewHolder extends RecyclerView.ViewHolder {
        public TextView tvName;
        public TextView tvEmailId;

        public UserViewHolder(View itemView) {
            super(itemView);
            tvName = (TextView) itemView.findViewById(R.id.tvName);

            tvEmailId = (TextView) itemView.findViewById(R.id.tvEmailId);
        }
    }

    static class LoadingViewHolder extends RecyclerView.ViewHolder {
        public ProgressBar progressBar;

        public LoadingViewHolder(View itemView) {
            super(itemView);
            progressBar = (ProgressBar) itemView.findViewById(R.id.progressBar1);
        }
    }

    class UserAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

        private final int VIEW_TYPE_ITEM = 0;
        private final int VIEW_TYPE_LOADING = 1;

        private OnLoadMoreListener mOnLoadMoreListener;

        private boolean isLoading;
        private int visibleThreshold = 5;
        private int lastVisibleItem, totalItemCount;

        public UserAdapter() {
            final LinearLayoutManager linearLayoutManager = (LinearLayoutManager) mRecyclerView.getLayoutManager();
            mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
                @Override
                public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                    super.onScrolled(recyclerView, dx, dy);

                    totalItemCount = linearLayoutManager.getItemCount();
                    lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition();

                    if (!isLoading && totalItemCount <= (lastVisibleItem + visibleThreshold)) {
                        if (mOnLoadMoreListener != null) {
                            mOnLoadMoreListener.onLoadMore();
                        }
                        isLoading = true;
                    }
                }
            });
        }

        public void setOnLoadMoreListener(OnLoadMoreListener mOnLoadMoreListener) {
            this.mOnLoadMoreListener = mOnLoadMoreListener;
        }

        @Override
        public int getItemViewType(int position) {
            return s_oDataset.get(position) == null ? VIEW_TYPE_LOADING : VIEW_TYPE_ITEM;
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            if (viewType == VIEW_TYPE_ITEM) {
                View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.layout_user_item, parent, false);
                return new UserViewHolder(view);
            } else if (viewType == VIEW_TYPE_LOADING) {
                View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.layout_loading_item, parent, false);
                return new LoadingViewHolder(view);
            }
            return null;
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
            if (holder instanceof UserViewHolder) {
                CDealAppDatastorage user = s_oDataset.get(position);
                UserViewHolder userViewHolder = (UserViewHolder) holder;
                userViewHolder.tvName.setText(user.getM_szHeaderText());
                userViewHolder.tvEmailId.setText(user.getM_szsubHeaderText());
            } else if (holder instanceof LoadingViewHolder) {
                LoadingViewHolder loadingViewHolder = (LoadingViewHolder) holder;
                loadingViewHolder.progressBar.setIndeterminate(true);
            }
        }

        @Override
        public int getItemCount() {
            return s_oDataset == null ? 0 : s_oDataset.size();
        }

        public void setLoaded() {
            isLoading = false;
        }
    }
}

Body:
Fetching the data from server is a Async Task. So you need to enclose the
updation code in a runOnUiThread runnable. to change UI.

runOnUiThread(new Runnable() {
   @Override
   public void run() {
      mUsers.remove(mUsers.size() - 1);
      mUserAdapter.notifyItemRemoved(mUsers.size());
      //sending request to server for more data
      moreDealsRequest();
      mUserAdapter.notifyDataSetChanged();
      mUserAdapter.setLoaded();
}});


问:
document.getElementById not working on jquery load
I've loaded an  html file with jquery load function

in my profile.blade.php

```<code> <script type="text/javascript">
      $(document).ready(function(){
         $("#newJob").load('/company/new-job');
      });
    </script>
   <script src="js/location.js"></script>
</code>```

in my location.js  i am  using

document.getElementById('autocomplete') for getting an html element

but this element is in company/new-job file

the problem i got undefined error in document.getElementById('autocomplete') this part

when i directly include the location.js its working fine

答:
your script   load before $(document).ready(function() and your element will load after document is ready and .load mehtod.

So here need to do is that have to add your script after your element render. otherwise  document.getElementById('autocomplete') cant't find element and generate error.

```<code>$(document).ready(function(){
$("#newJob").load("/company/new-job", function(responseTxt, statusTxt, xhr){
        if(statusTxt == "success")
           $.getScript('js/location.js');
        if(statusTxt == "error")
            alert("Error: " + xhr.status + ": " + xhr.statusText);
    });
});
</code>```

Body:
I've loaded an  html file with jquery load function

in my profile.blade.php

in my location.js  i am  using

document.getElementById('autocomplete') for getting an html element

but this element is in company/new-job file

the problem i got undefined error in document.getElementById('autocomplete') this part

when i directly include the location.js its working fine

Body:
your script  <script src="js/location.js"></script> load before $(document).ready(function() and your element will load after document is ready and .load mehtod.

So here need to do is that have to add your script after your element render. otherwise  document.getElementById('autocomplete') cant't find element and generate error.

$(document).ready(function(){
$("#newJob").load("/company/new-job", function(responseTxt, statusTxt, xhr){
        if(statusTxt == "success")
           $.getScript('js/location.js');
        if(statusTxt == "error")
            alert("Error: " + xhr.status + ": " + xhr.statusText);
    });
});


问:
using numpy arrays for integer and array inputs
I am a Matlab user, and trying to move into Python. I tried to code a minimal example of de2bi function (which converts a decimal into binary as right-msb) in Python which I had before in Matlab. But, I am confused with numpy arrays.

Python code:

```<code>import numpy as np

def de2bi(d, n)
    d = np.array(d)
    power = 2**np.arange(n)
    d = d * np.ones((1,n))
    b = np.floor((d%(2*power))/power)
    return b
</code>```

Python output:

```<code>>>> print(de2bi(13,8))
[[ 1.  0.  1.  1.  0.  0.  0.  0.]]

print(de2bi([13,15],8)) #This line fails
</code>```

Matlab code:

```<code>function b = d2b( d, n )
    d = d(:);
    power = ones(length(d), 1)*(2.^(0 : n-1));
    d = d * ones(1, n);
    b = floor(rem(d, 2*power)./power);
end
</code>```

Matlab output:

```<code>>> d2b(13,8)

ans =

     1     0     1     1     0     0     0     0

>> d2b([13,15],8)

ans =

     1     0     1     1     0     0     0     0
     1     1     1     1     0     0     0     0
</code>```

Matlab code is working both for integer inputs and array of integers. But python code works for integer inputs, but keeps failing for arrays. How to manage operations both for integers and integer arrays in Python automatically? It may be a very easy question, excuse me, but I am a very newbie in python.

Thanks in advance.

答:
Does this help?

```<code>In [439]: d=np.array([13,15])
In [440]: power=np.ones((d.shape[0],1))*(2**np.arange(8))
In [441]: power
Out[441]:
array([[   1.,    2.,    4.,    8.,   16.,   32.,   64.,  128.],
       [   1.,    2.,    4.,    8.,   16.,   32.,   64.,  128.]])
In [442]: np.floor((d[:,None]%(2*power))/power)
Out[442]:
array([[ 1.,  0.,  1.,  1.,  0.,  0.,  0.,  0.],
       [ 1.,  1.,  1.,  1.,  0.,  0.,  0.,  0.]])
</code>```

we don't even need the ones:

```<code>In [443]: power = 2**np.arange(8)
In [444]: np.floor((d[:,None]%(2*power))/power)
Out[444]:
array([[ 1.,  0.,  1.,  1.,  0.,  0.,  0.,  0.],
       [ 1.,  1.,  1.,  1.,  0.,  0.,  0.,  0.]])
</code>```

When broadcasting d against power, the dimension expansion for power is automatic: d[:,None]%(2*power[None,:]).  The ones in MATLAB accomplish the same dimension expansion (to (2,8) shaped arrays).

May want to start with d=np.atleast_1d(d), so it treats the scalar case like a 1 element array.  We could refine things so it returns a 1d array when given a scalar, and 2d when given a list or 1d array.  In MATLAB everything is 2d or higher.

Better yet, use ellipsis when expanding d.  Then d can be 0d, 1d, or even nd.

```<code>np.floor((d[...,None]%(2*power))/power)
</code>```

Body:
I am a Matlab user, and trying to move into Python. I tried to code a minimal example of de2bi function (which converts a decimal into binary as right-msb) in Python which I had before in Matlab. But, I am confused with numpy arrays.

Python code:

import numpy as np

def de2bi(d, n)
    d = np.array(d)
    power = 2**np.arange(n)
    d = d * np.ones((1,n))
    b = np.floor((d%(2*power))/power)
    return b

Python output:

>>> print(de2bi(13,8))
[[ 1.  0.  1.  1.  0.  0.  0.  0.]]

print(de2bi([13,15],8)) #This line fails

Matlab code:

function b = d2b( d, n )
    d = d(:);
    power = ones(length(d), 1)*(2.^(0 : n-1));
    d = d * ones(1, n);
    b = floor(rem(d, 2*power)./power);
end

Matlab output:

>> d2b(13,8)

ans =

     1     0     1     1     0     0     0     0

>> d2b([13,15],8)

ans =

     1     0     1     1     0     0     0     0
     1     1     1     1     0     0     0     0

Matlab code is working both for integer inputs and array of integers. But python code works for integer inputs, but keeps failing for arrays. How to manage operations both for integers and integer arrays in Python automatically? It may be a very easy question, excuse me, but I am a very newbie in python.

Thanks in advance.

Body:
Does this help?

In [439]: d=np.array([13,15])
In [440]: power=np.ones((d.shape[0],1))*(2**np.arange(8))
In [441]: power
Out[441]:
array([[   1.,    2.,    4.,    8.,   16.,   32.,   64.,  128.],
       [   1.,    2.,    4.,    8.,   16.,   32.,   64.,  128.]])
In [442]: np.floor((d[:,None]%(2*power))/power)
Out[442]:
array([[ 1.,  0.,  1.,  1.,  0.,  0.,  0.,  0.],
       [ 1.,  1.,  1.,  1.,  0.,  0.,  0.,  0.]])

we don't even need the ones:

In [443]: power = 2**np.arange(8)
In [444]: np.floor((d[:,None]%(2*power))/power)
Out[444]:
array([[ 1.,  0.,  1.,  1.,  0.,  0.,  0.,  0.],
       [ 1.,  1.,  1.,  1.,  0.,  0.,  0.,  0.]])

When broadcasting d against power, the dimension expansion for power is automatic: d[:,None]%(2*power[None,:]).  The ones in MATLAB accomplish the same dimension expansion (to (2,8) shaped arrays).

May want to start with d=np.atleast_1d(d), so it treats the scalar case like a 1 element array.  We could refine things so it returns a 1d array when given a scalar, and 2d when given a list or 1d array.  In MATLAB everything is 2d or higher.

Better yet, use ellipsis when expanding d.  Then d can be 0d, 1d, or even nd.

np.floor((d[...,None]%(2*power))/power)


问:
Splitting a list element by a separator | 'Can't convert 'list' object to str implicitly' error (Python)
I have a list json_data:

```<code>> print(json_data)
> ['abc', 'bcd/chg', 'sdf', 'bvd', 'wer/ewe', 'sbc & osc']
</code>```

I need to split those elements with '/', '&' or 'and' into two different elements. The result I am looking for should look like this:

```<code>>['abc', 'bcd', 'chg', 'sdf', 'bvd', 'wer', 'ewe', 'sbc' , 'osc']
</code>```

The code is:

```<code>separators = ['/', 'and', '&']

titles = []
for i in json_data:
    titles.extend([t.strip() for t in i.split(separators)
                  if i.strip() != ''])
</code>```

When running it, I am getting an error:

```<code>---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-15-d0db85078f05> in <module>()
      5 titles = []
      6 for i in json_data:
----> 7     titles.extend([t.strip() for t in i.split(separators)
      8                   if i.strip() != ''])

TypeError: Can't convert 'list' object to str implicitly
</code>```

How can this be fixed?

答:
```<code>json_data = ["abc", "bcd/chg", "sdf", "bvd", "wer/ewe", "sbc & osc"]
separators = ['/', '&', 'and']
title = []

for i in json_data:
    k = 0
    while k < len(separators):
        if separators[k] in i:
            t = i.split(separators[k])
            title.extend(t)
            break
        else:
            k += 1
        if k == 3:
            title.append(i)
print(title)
</code>```

Body:
I have a list json_data:

> print(json_data)
> ['abc', 'bcd/chg', 'sdf', 'bvd', 'wer/ewe', 'sbc & osc']

I need to split those elements with '/', '&' or 'and' into two different elements. The result I am looking for should look like this:

>['abc', 'bcd', 'chg', 'sdf', 'bvd', 'wer', 'ewe', 'sbc' , 'osc']

The code is:

separators = ['/', 'and', '&']

titles = []
for i in json_data:
    titles.extend([t.strip() for t in i.split(separators)
                  if i.strip() != ''])

When running it, I am getting an error:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-15-d0db85078f05> in <module>()
      5 titles = []
      6 for i in json_data:
----> 7     titles.extend([t.strip() for t in i.split(separators)
      8                   if i.strip() != ''])

TypeError: Can't convert 'list' object to str implicitly

How can this be fixed?


问:
Using beginning regex characters in python
I'm trying to implement regular expressions in python so that I will only print part of a string and not a whole string. I'm trying to print the characters that are numbers and also precede the letter characters of this string. I'm getting an error with the beginning of string character here

Heres my code
    import re

```<code>var = "20cw"
var2 = re.compile(^[0-9]?[0-9], var)
print var2
</code>```

Here is the error I'm getting

```<code>  File "./temp.py", line 5
    var2 = re.compile(^[0-9]?[0-9], var)
                      ^
SyntaxError: invalid syntax
</code>```

Expected output is

```<code>20
</code>```

答:
Enclose the regex as string (with quotation marks):</p>

```<code>var2 = re.findall('^\d{2}', var)
</code>```

Body:
I'm trying to implement regular expressions in python so that I will only print part of a string and not a whole string. I'm trying to print the characters that are numbers and also precede the letter characters of this string. I'm getting an error with the beginning of string character here

Heres my code
    import re

var = "20cw"
var2 = re.compile(^[0-9]?[0-9], var)
print var2

Here is the error I'm getting

  File "./temp.py", line 5
    var2 = re.compile(^[0-9]?[0-9], var)
                      ^
SyntaxError: invalid syntax

Expected output is

20

Body:
Enclose the regex as string (with quotation marks):

var2 = re.findall('^\d{2}', var)


问:
How Can I Get Admin Id and Use it across the application?
In codeigniter I want to add the product on admin Id which is required in DB Table. when Admin log in his ID must be catch. whenever and where Id is needed it must be available.

here is my VIEW in which

```<code>    <?php echo form_open_multipart('admin/add_product');?>

<!------------------Product Name------------------------>
 <div class="row form-group">
       <div class="col-sm-10">

      <label>Product Name: *</label>
  <?php echo form_input(['name'=>'name','class'=>'form-
    control','placeholder'=>'Product name..','value'=>
   set_value('name')])?>
      <div>
          <?php echo form_error('name');?>
      </div>
      </div></div>
      <!------------------Product Cat---------------------------->
 <div class="row form-group">
       <div class="col-sm-12">
  <label>Category: *</label> <br>
 <select class="selectpicker" name="pro_cat_id">
<option label="Select Category">Category</option>
<?php
 foreach($product_cat as $cat)
  {?>
  <option value="<?= $cat['pro_cat_id'] ?>"><?= $cat['category'] ?>
 </option>
     <?php }?>
</select>
 <div>

   <!------------------Product Price---------------------------->
 <div class="row form-group">
       <div class="col-md-10">
    <label>Product Price: *</label>
<?php echo form_input(['name'=>'price','class'=>'form-

   control','placeholder'=>'Product Price..','value'=>
     set_value('price')])?>

   <div>
    <?php echo form_error('price');?>
 </div>
  </div></div>

     <!------------------Product Location---------------------------->
      <div class="row form-group">
       <div class="col-md-10">
      <label>Product Location: *</label>
    <?php //echo form_input(['name'=>'location','class'=>'form-
        control','placeholder'=>'Product Location'])?>

       </div></div>

    </div></div>
        <!-----------End of body---------------->
       </div>
     <div class="modal-footer">
     <input name="" type="submit" value="ADD" class="btn btn-success">

     </div>

         <?php echo form_close();?>
     </div>
 </div>
  </div>
</code>```

Here is my Controller

```<code>            function add_product(){
       $data['product_size'] = $this->show->show_product_size();
      $data['product_cat']= $this->show->show_product_category();
      $data['product_color'] = $this->show->show_product_color();
   $data['pr']= $this->show->show_provider();

    $post= $this->input->post();
  $ =this->form_validation->set_error_delimiters("<p class='text-danger'>","
  </p>");
if($this->form_validation->run('add_product')){
if($this->add->add_product($post)==TRUE){

     $this->db->close();
     $this->session->set_flashdata('success','Product has been added
       successfully');
    return redirect('admins/pages/add_product_page');
     //$this->load->admin_template('admin/add_product',$data);

}
}
else
{
    $this->session->set_flashdata('failled','Sorry, fail to add product');
    //return redirect('admins/pages/add_product_page');
    $upload_error= $this->upload->display_errors();

     $this->load->admin_template('admin/add_product',$data);
   }
  }
</code>```

答:
Use this query, preferably in your controller:</p>

```<code>$this->session->userdata('id');
</code>```

Body:
In codeigniter I want to add the product on admin Id which is required in DB Table. when Admin log in his ID must be catch. whenever and where Id is needed it must be available.

here is my VIEW in which

    <?php echo form_open_multipart('admin/add_product');?>

      Product Name: *
  <?php echo form_input(['name'=>'name','class'=>'form-
    control','placeholder'=>'Product name..','value'=>
   set_value('name')])?>

          <?php echo form_error('name');?>

  Category: *

 <select class="selectpicker" name="pro_cat_id">
<option label="Select Category">Category</option>
<?php
 foreach($product_cat as $cat)
  {?>
  <option value="<?= $cat['pro_cat_id'] ?>"><?= $cat['category'] ?>
 </option>
     <?php }?>
</select>

    Product Price: *
<?php echo form_input(['name'=>'price','class'=>'form-

   control','placeholder'=>'Product Price..','value'=>
     set_value('price')])?>

    <?php echo form_error('price');?>

      Product Location: *
    <?php //echo form_input(['name'=>'location','class'=>'form-
        control','placeholder'=>'Product Location'])?>

     <input name="" type="submit" value="ADD" class="btn btn-success">

         <?php echo form_close();?>

Here is my Controller

            function add_product(){
       $data['product_size'] = $this->show->show_product_size();
      $data['product_cat']= $this->show->show_product_category();
      $data['product_color'] = $this->show->show_product_color();
   $data['pr']= $this->show->show_provider();

    $post= $this->input->post();
  $ =this->form_validation->set_error_delimiters("
","

");
if($this->form_validation->run('add_product')){
if($this->add->add_product($post)==TRUE){

     $this->db->close();
     $this->session->set_flashdata('success','Product has been added
       successfully');
    return redirect('admins/pages/add_product_page');
     //$this->load->admin_template('admin/add_product',$data);

}
}
else
{
    $this->session->set_flashdata('failled','Sorry, fail to add product');
    //return redirect('admins/pages/add_product_page');
    $upload_error= $this->upload->display_errors();

     $this->load->admin_template('admin/add_product',$data);
   }
  }

Body:
Use this query, preferably in your controller:

$this->session->userdata('id');


问:
PHP - get object parent
I have a function that is called like this:

```<code>foo($object->ID);
</code>```

and in the function I need to somehow select $object if $object->ID is passed as a variable.

```<code>function foo($id = NULL){
  if($id != NULL) ... // here I want to get $object
  else ...
}
</code>```

How can I do this?

答:
why not:

```<code>foo($object);
</code>```

and

```<code>function  foo($localObject){
  if(isset($localObject->id)){
  }
}
</code>```

Title: PHP - get object parent

Body:
I have a function that is called like this:

foo($object->ID);

and in the function I need to somehow select $object if $object->ID is passed as a variable.

function foo($id = NULL){
  if($id != NULL) ... // here I want to get $object
  else ...
}

How can I do this?

Body:
why not:

foo($object);

and

function  foo($localObject){
  if(isset($localObject->id)){
  }
}


问:
Java Swing - How to stack Username textfield and Password textfield
I'm using a gridbaglayout for my layout, and I'm wondering how to go about rearranging it so that the username textfield goes directly above the password textfield, and the login button goes under the password textfield.

Currently my code outputs:

However I want something like this:

My code:

```<code>import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class TestingJavaCode {

    public TestingJavaCode() {

        JFrame appFrame = new JFrame();
        JPanel loginPanel = new JPanel();
        appFrame.setSize(1200, 800);
        loginPanel = new JPanel(new GridBagLayout());

        // Button for logging in, with respective GridBagConstraint
        // setFocusable is set to false to take out the border around the text
        JButton loginButton = new JButton("Login");
        GridBagConstraints lButtonC = new GridBagConstraints();
        loginButton.setFocusable(false);

        // Username text-field and JLabel with respective GridBagConstraints
        JTextField tfUsername = new JTextField(15);
        GridBagConstraints tfUserC = new GridBagConstraints();
        JLabel txtUser = new JLabel("Username: ");
        GridBagConstraints txtUserC = new GridBagConstraints();

        // Password text-field and JLabel with respective GridBagConstraints
        JPasswordField tfPassword = new JPasswordField(15);
        GridBagConstraints tfPassC = new GridBagConstraints();
        JLabel txtPassword = new JLabel("Password: ");
        GridBagConstraints txtPassC = new GridBagConstraints();

        // Add all components to the JFrame
        // Making sure to add the text before the text-fields
        loginPanel.add(txtUser, txtUserC);
        loginPanel.add(tfUsername, tfUserC);
        loginPanel.add(txtPassword, txtPassC);
        loginPanel.add(tfPassword, tfPassC);
        loginPanel.add(loginButton, lButtonC);

        // Show the frame
        appFrame.add(loginPanel);
        appFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        appFrame.setVisible(true);
    }

    public static void main(String[] args) {
        new TestingJavaCode();
    }

}
</code>```

EDIT: I am open to using other layout managers.

答:
Since you don't want to use gridx/y constraints why don't you just use combination of BoxLayout and FlowLayout? I added new 2 new panels. One for username and one for password and since FlowLayout is the default layout for panel we can just leave it as it is.

FlowLayout is the default layout manager for every JPanel. It simply
  lays out components in a single row, starting a new row if its
  container is not sufficiently wide.

After that lets set BoxLayout to your loginPanel and just add username and password panel to it.

The BoxLayout class puts components in a single row or column. It
  respects the components' requested maximum sizes and also lets you
  align components.

Here is the complete updated source:

```<code>import javax.swing.*;

public class TestingJavaCode {

    public TestingJavaCode() {

        JFrame appFrame = new JFrame();
        JPanel loginPanel = new JPanel();
        appFrame.setSize(300, 130);
        loginPanel.setLayout(new BoxLayout(loginPanel, BoxLayout.PAGE_AXIS));

        // Button for logging in, with respective GridBagConstraint
        // setFocusable is set to false to take out the border around the text
        JButton loginButton = new JButton("Login");
        loginButton.setFocusable(false);

        JPanel usernamePanel = new JPanel();
        // Username text-field and JLabel with respective GridBagConstraints
        JTextField tfUsername = new JTextField(15);
        JLabel txtUser = new JLabel("Username: ");

        usernamePanel.add(txtUser);
        usernamePanel.add(tfUsername);

        JPanel passwordPanel = new JPanel();
        // Password text-field and JLabel with respective GridBagConstraints
        JPasswordField tfPassword = new JPasswordField(15);
        JLabel txtPassword = new JLabel("Password: ");

        passwordPanel.add(txtPassword);
        passwordPanel.add(tfPassword);

        // Add all components to the JFrame
        // Making sure to add the text before the text-fields
        loginPanel.add(usernamePanel);

        loginPanel.add(usernamePanel);
        loginPanel.add(passwordPanel);
        loginPanel.add(loginButton);
        // Show the frame
        appFrame.add(loginPanel);
        appFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        appFrame.setVisible(true);
    }

    public static void main(String[] args) {
        new TestingJavaCode();
    }

}
</code>```

Body:
I'm using a gridbaglayout for my layout, and I'm wondering how to go about rearranging it so that the username textfield goes directly above the password textfield, and the login button goes under the password textfield.

Currently my code outputs:

However I want something like this:

My code:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class TestingJavaCode {

    public TestingJavaCode() {

        JFrame appFrame = new JFrame();
        JPanel loginPanel = new JPanel();
        appFrame.setSize(1200, 800);
        loginPanel = new JPanel(new GridBagLayout());

        // Button for logging in, with respective GridBagConstraint
        // setFocusable is set to false to take out the border around the text
        JButton loginButton = new JButton("Login");
        GridBagConstraints lButtonC = new GridBagConstraints();
        loginButton.setFocusable(false);

        // Username text-field and JLabel with respective GridBagConstraints
        JTextField tfUsername = new JTextField(15);
        GridBagConstraints tfUserC = new GridBagConstraints();
        JLabel txtUser = new JLabel("Username: ");
        GridBagConstraints txtUserC = new GridBagConstraints();

        // Password text-field and JLabel with respective GridBagConstraints
        JPasswordField tfPassword = new JPasswordField(15);
        GridBagConstraints tfPassC = new GridBagConstraints();
        JLabel txtPassword = new JLabel("Password: ");
        GridBagConstraints txtPassC = new GridBagConstraints();

        // Add all components to the JFrame
        // Making sure to add the text before the text-fields
        loginPanel.add(txtUser, txtUserC);
        loginPanel.add(tfUsername, tfUserC);
        loginPanel.add(txtPassword, txtPassC);
        loginPanel.add(tfPassword, tfPassC);
        loginPanel.add(loginButton, lButtonC);

        // Show the frame
        appFrame.add(loginPanel);
        appFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        appFrame.setVisible(true);
    }

    public static void main(String[] args) {
        new TestingJavaCode();
    }

}

EDIT: I am open to using other layout managers.

Body:
Since you don't want to use gridx/y constraints why don't you just use combination of BoxLayout and FlowLayout? I added new 2 new panels. One for username and one for password and since FlowLayout is the default layout for panel we can just leave it as it is.

FlowLayout is the default layout manager for every JPanel. It simply
  lays out components in a single row, starting a new row if its
  container is not sufficiently wide.

After that lets set BoxLayout to your loginPanel and just add username and password panel to it.

The BoxLayout class puts components in a single row or column. It
  respects the components' requested maximum sizes and also lets you
  align components.

Here is the complete updated source:

import javax.swing.*;

public class TestingJavaCode {

    public TestingJavaCode() {

        JFrame appFrame = new JFrame();
        JPanel loginPanel = new JPanel();
        appFrame.setSize(300, 130);
        loginPanel.setLayout(new BoxLayout(loginPanel, BoxLayout.PAGE_AXIS));

        // Button for logging in, with respective GridBagConstraint
        // setFocusable is set to false to take out the border around the text
        JButton loginButton = new JButton("Login");
        loginButton.setFocusable(false);

        JPanel usernamePanel = new JPanel();
        // Username text-field and JLabel with respective GridBagConstraints
        JTextField tfUsername = new JTextField(15);
        JLabel txtUser = new JLabel("Username: ");

        usernamePanel.add(txtUser);
        usernamePanel.add(tfUsername);

        JPanel passwordPanel = new JPanel();
        // Password text-field and JLabel with respective GridBagConstraints
        JPasswordField tfPassword = new JPasswordField(15);
        JLabel txtPassword = new JLabel("Password: ");

        passwordPanel.add(txtPassword);
        passwordPanel.add(tfPassword);

        // Add all components to the JFrame
        // Making sure to add the text before the text-fields
        loginPanel.add(usernamePanel);

        loginPanel.add(usernamePanel);
        loginPanel.add(passwordPanel);
        loginPanel.add(loginButton);
        // Show the frame
        appFrame.add(loginPanel);
        appFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        appFrame.setVisible(true);
    }

    public static void main(String[] args) {
        new TestingJavaCode();
    }

}


问:
Make a JSON file from postgres database
I am using postgresql version 9.6. I am trying to make a JSON file from my database. I can worry about how to turn the SQL query into a file, but I am getting caught up on how to set up the query. Here are my tables and a few inserts:

```<code>create table careers
(
  career_id integer PRIMARY KEY,
  career_name text
);

create table career_types
(
  career_type_id integer PRIMARY KEY,
  career_id integer REFERENCES careers,
  career_type_name text
);

create table career_type_properties
(
  career_type_property_id serial PRIMARY KEY,
  career_id integer REFERENCES careers,
  career_type_id integer REFERENCES career_types,
  property_name character varying(255),
  property_value character varying(255)
);

INSERT INTO careers (career_id, career_name)
VALUES
  (1, 'medical'),
  (2, 'hospitality'),
  (3, 'education');

INSERT INTO career_types(career_type_id, career_id, career_type_name)
VALUES
  (1, '1', 'surgeon'),
  (2, '1', 'nurse'),
  (3, '2', 'hotel_manager'),
  (4, '2', 'bartendar'),
  (5, '3', 'Middle_school_teacher'),
  (6, '3', 'Professor');

INSERT INTO career_type_properties(career_id, career_type_id, property_name, property_value)
VALUES
  ('1', '1', 'pay', 'salary'),
  ('1', '1', 'days_per_week', '5'),
  ('1', '1', 'on_call', 'yes'),
  ('1', '1', 'doctorate_degree', 'yes'),
  ('1', '2', 'pay', 'salary'),
  ('1', '2', 'days_per_week', '4'),
  ('1', '2', 'on_call', 'no'),
  ('1', '2', 'doctorate_degree', 'no'),
  ('2', '3', 'pay', 'salary'),
  ('2', '3', 'days_per_week', '5-6'),
  ('2', '3', 'on_call', 'no'),
  ('2', '4', 'pay', 'hourly'),
  ('2', '4', 'days_per_week', '3-6'),
  ('2', '4', 'on_call', 'no'),
  ('3', '5', 'pay', 'salary'),
  ('3', '5', 'year_round', 'yes'),
  ('3', '5', 'does_research', 'no'),
  ('3', '5', 'set_hours', 'yes'),
  ('3', '6', 'pay', 'salary'),
  ('3', '6', 'year_round', 'optional'),
  ('3', '6', 'does_research', 'yes'),
  ('3', '6', 'set_hours', 'no');
</code>```

Here is an example of what JSON I am trying produce.

```<code>  {
   "medical":{
       "surgeon":{
         "pay": "salary",
         "days_per_week": "5",
         "on_call": "yes",
         "doctorate_degree": "yes"
        },
       "nurse": {
         "pay": "salary",
         "days_per_week": "4",
         "on_call": "no",
         "doctorate_degree": "no"
        }
    },
    "hospitality": {
       "hotel_manager":{
          "pay": "salary",
          "days_per_week": "5-6",
          "on_call": "no"
       },
       "bartender": {
          "pay": "hourly",
          "days_per_week": "3-6",
          "on_call": "no"
       }
    },
     "education": {
        "middle_school_teacher":{
          "pay":"salary",
          "year_round": "yes",
          "does_research": "no",
          "set_hours": "yes"
      },
        "professor":{
          "pay":"salary",
          "year_round": "optional",
          "does_research": "yes",
          "set_hours": "no"
      }
   }
 }
</code>```

I have been able to get close using queries like:

```<code>    select json_object_agg(property_name, property_value) from
    career_type_properties group by career_type_id
</code>```

I am pretty new to using SQL so any help would be appreciated.

答:
You need to nest the grouping for this:

```<code>select json_object_agg(career_name, c)
from (
  select c.career_name, json_object_agg(ct.career_type_name,  ctp.props) c
  from careers c
    join career_types ct ON c.career_id = ct.career_id
    join (
      select career_type_id, json_object_agg(property_name, property_value) as props
      from career_type_properties
      group by career_type_id
    ) ctp on ctp.career_type_id = ct.career_type_id
  group by c.career_name
) t;
</code>```

Online example: http://rextester.com/LLNQ72750

Title: Make a JSON file from postgres database

Body:
I am using postgresql version 9.6. I am trying to make a JSON file from my database. I can worry about how to turn the SQL query into a file, but I am getting caught up on how to set up the query. Here are my tables and a few inserts:

create table careers
(
  career_id integer PRIMARY KEY,
  career_name text
);

create table career_types
(
  career_type_id integer PRIMARY KEY,
  career_id integer REFERENCES careers,
  career_type_name text
);

create table career_type_properties
(
  career_type_property_id serial PRIMARY KEY,
  career_id integer REFERENCES careers,
  career_type_id integer REFERENCES career_types,
  property_name character varying(255),
  property_value character varying(255)
);

INSERT INTO careers (career_id, career_name)
VALUES
  (1, 'medical'),
  (2, 'hospitality'),
  (3, 'education');

INSERT INTO career_types(career_type_id, career_id, career_type_name)
VALUES
  (1, '1', 'surgeon'),
  (2, '1', 'nurse'),
  (3, '2', 'hotel_manager'),
  (4, '2', 'bartendar'),
  (5, '3', 'Middle_school_teacher'),
  (6, '3', 'Professor');

INSERT INTO career_type_properties(career_id, career_type_id, property_name, property_value)
VALUES
  ('1', '1', 'pay', 'salary'),
  ('1', '1', 'days_per_week', '5'),
  ('1', '1', 'on_call', 'yes'),
  ('1', '1', 'doctorate_degree', 'yes'),
  ('1', '2', 'pay', 'salary'),
  ('1', '2', 'days_per_week', '4'),
  ('1', '2', 'on_call', 'no'),
  ('1', '2', 'doctorate_degree', 'no'),
  ('2', '3', 'pay', 'salary'),
  ('2', '3', 'days_per_week', '5-6'),
  ('2', '3', 'on_call', 'no'),
  ('2', '4', 'pay', 'hourly'),
  ('2', '4', 'days_per_week', '3-6'),
  ('2', '4', 'on_call', 'no'),
  ('3', '5', 'pay', 'salary'),
  ('3', '5', 'year_round', 'yes'),
  ('3', '5', 'does_research', 'no'),
  ('3', '5', 'set_hours', 'yes'),
  ('3', '6', 'pay', 'salary'),
  ('3', '6', 'year_round', 'optional'),
  ('3', '6', 'does_research', 'yes'),
  ('3', '6', 'set_hours', 'no');

Here is an example of what JSON I am trying produce.

  {
   "medical":{
       "surgeon":{
         "pay": "salary",
         "days_per_week": "5",
         "on_call": "yes",
         "doctorate_degree": "yes"
        },
       "nurse": {
         "pay": "salary",
         "days_per_week": "4",
         "on_call": "no",
         "doctorate_degree": "no"
        }
    },
    "hospitality": {
       "hotel_manager":{
          "pay": "salary",
          "days_per_week": "5-6",
          "on_call": "no"
       },
       "bartender": {
          "pay": "hourly",
          "days_per_week": "3-6",
          "on_call": "no"
       }
    },
     "education": {
        "middle_school_teacher":{
          "pay":"salary",
          "year_round": "yes",
          "does_research": "no",
          "set_hours": "yes"
      },
        "professor":{
          "pay":"salary",
          "year_round": "optional",
          "does_research": "yes",
          "set_hours": "no"
      }
   }
 }

I have been able to get close using queries like:

    select json_object_agg(property_name, property_value) from
    career_type_properties group by career_type_id

I am pretty new to using SQL so any help would be appreciated.

Body:
You need to nest the grouping for this:

select json_object_agg(career_name, c)
from (
  select c.career_name, json_object_agg(ct.career_type_name,  ctp.props) c
  from careers c
    join career_types ct ON c.career_id = ct.career_id
    join (
      select career_type_id, json_object_agg(property_name, property_value) as props
      from career_type_properties
      group by career_type_id
    ) ctp on ctp.career_type_id = ct.career_type_id
  group by c.career_name
) t;

Online example: http://rextester.com/LLNQ72750


问:
Change SharedAssembly Info Jenkins

I'm trying to use Change Assembly Version Plugin to stamp my SharedAssemblyInfo.cs with the latest build number. At the moment its not doing anything the Assembly version remains the same as in git, doesn't report any errors and there's nothing much in the build log either. i have attached the screen shots of my SharedAssemblyInfo.cs and console output below. Am I missing something here ?

Thanks in advance

答:
Please try adding **/ in front of the file name as follows.

**/SharedAssemblyInfo.cs

Title: Change SharedAssembly Info Jenkins


问:
navbar change when scrolled with materialize css
I'm trying to replicate a navbar similar to this website. so there is a non-sticky navbar when user opens the website and after user scrolled down a little bit the non-sticky navbar gone and replaced by a sticky navbar. how can I achieve something like this with materialize css ? so far i've only made the non-sticky navbar part</p>

```<code><nav class="nav-extended">
    <div class="nav-wrapper">
        <a href="#" class="brand-logo"><img src="viva.png" alt="" id="logo"></a>
        <ul id="nav-mobile" class="right hide-on-med-and-down">
            <li>
                <form>
                    <div class="input-field">
                        <input id="search" type="search" required>
                        <label class="label-icon" for="search"><i class="material-icons"></i></label>
                        <i class="material-icons">close</i>
                    </div>
                </form>
            </li>
            <li><a href="#">Register</a></li>
            <li>|</li>
            <li><a href="#">Login</a></li>
        </ul>
    </div>
    <hr>
    <div class="nav-content">
        <ul class="tabs tabs-transparent">
            <li class="tab"><a href="#">Test 1</a></li>
            <li class="tab"><a href="#">Test 2</a></li>
            <li class="tab"><a href="#">Test 3</a></li>
        </ul>
    </div>
</nav>
</code>```

答:
Try this:

HTML

```<code><div class="header">Header Example</div>
<div class="content">
<p>
Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur.
</p>
</div>
</code>```

CSS

```<code>body {
    margin:0;
    padding:0;
    font-family: Arial, sans-serif;
}

header {
    position: relative;
    width: 100%;
    height: 80px;
    line-height: 80px;
    background: #CCCCCC;
    color: #333333;
    padding-left: 25px;
}
header.fixed {
    position:fixed;
    top:-80px;
    left: 0;
    right: 0;
    z-index:8888;
    transition:0.3s top cubic-bezier(.3,.73,.3,.74);
}
body.on-scroll header.fixed {
    top:0;
}
.content {
    padding: 25px;
    background: #fff;
    line-height: 1.4;
    color: #333;
    min-height: 2700px; /* You can remove this,is just for demo purpose */
}
</code>```

jquery:

```<code>  (function($){
   $(document).ready(function() {
        var $header = $(".header"),
            $clone = $header.before($header.clone().addClass("fixed"));

        $(window).on("scroll", function() {
            var fromTop = $(window).scrollTop();
            $("body").toggleClass("on-scroll", (fromTop > 200));
        });
    });
 })(jQuery);
</code>```

Here's a jsfiddle example.

Body:
I'm trying to replicate a navbar similar to this website. so there is a non-sticky navbar when user opens the website and after user scrolled down a little bit the non-sticky navbar gone and replaced by a sticky navbar. how can I achieve something like this with materialize css ? so far i've only made the non-sticky navbar part

                <form>

                        <input id="search" type="search" required>

                        close

                </form>

Register

|

Login

Test 1

Test 2

Test 3

Body:
Try this:

HTML

<div class="header">Header Example</div>
<div class="content">
<p>
Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur.
</p>
</div>

CSS

body {
    margin:0;
    padding:0;
    font-family: Arial, sans-serif;
}

header {
    position: relative;
    width: 100%;
    height: 80px;
    line-height: 80px;
    background: #CCCCCC;
    color: #333333;
    padding-left: 25px;
}
header.fixed {
    position:fixed;
    top:-80px;
    left: 0;
    right: 0;
    z-index:8888;
    transition:0.3s top cubic-bezier(.3,.73,.3,.74);
}
body.on-scroll header.fixed {
    top:0;
}
.content {
    padding: 25px;
    background: #fff;
    line-height: 1.4;
    color: #333;
    min-height: 2700px; /* You can remove this,is just for demo purpose */
}

jquery:

  (function($){
   $(document).ready(function() {
        var $header = $(".header"),
            $clone = $header.before($header.clone().addClass("fixed"));

        $(window).on("scroll", function() {
            var fromTop = $(window).scrollTop();
            $("body").toggleClass("on-scroll", (fromTop > 200));
        });
    });
 })(jQuery);

Here's a jsfiddle example.


问:
string is not getting exploded
Here is my code where explode function is not getting correctly.code looks like this

```<code> <div id="demo-1" data-zs-src='[<?php foreach( $slides as $slide ){?>"<?php echo base_url();?>uploads/<?php echo $slide->image;?>"<?php }?>]' data-zs-overlay="dots">
<div class="demo-inner-content">
  <h1><span>Tasty</span> & <span>Healthy</span></h1>
  <p>For those who have taste for life.</p>
</div>
</code>```

my result looks like this

```<code><div id="demo-1" data-zs-src='["http://localhost/fahiz_kitchen/uploads/upload-file1496902770.jpg""http://localhost/fahiz_kitchen/uploads/upload-file1496901910.gif""http://localhost/fahiz_kitchen/uploads/upload-file1496901900.jpg""http://localhost/fahiz_kitchen/uploads/upload-file1496901887.jpg"]' data-zs-overlay="dots">
<div class="demo-inner-content">
  <h1><span>Tasty</span> & <span>Healthy</span></h1>
  <p>For those who have taste for life.</p>
</div>
</div>
</code>```

i want to get comma in between the result that means my result should be like this

```<code><div id="demo-1" data-zs-src='["http://localhost/fahiz_kitchen/uploads/upload-file1496902770.jpg",
"http://localhost/fahiz_kitchen/uploads/upload-file1496901910.gif",
"http://localhost/fahiz_kitchen/uploads/upload-file1496901900.jpg",
"http://localhost/fahiz_kitchen/uploads/upload-file1496901887.jpg"
</code>```

答:
Chnage it like.

```<code> $data = [<?php
    foreach( $slides as $slide ){
     ?>"<?php echo base_url();?>uploads/<?php echo $slide->image;?>",
   <?php }?>];
$finaldata = rtrim($data, ',');

<div id="demo-1" data-zs-src="'.$finaldata.'" data-zs-overlay="dots">
<div class="demo-inner-content">
  <h1><span>Tasty</span> & <span>Healthy</span></h1>
<p>For those who have taste for life.</p>
</div>
</code>```

You are starting php inside already started it.

Title: string is not getting exploded

Body:
Here is my code where explode function is not getting correctly.code looks like this

 <div id="demo-1" data-zs-src='[<?php foreach( $slides as $slide ){?>"<?php echo base_url();?>uploads/<?php echo $slide->image;?>"<?php }?>]' data-zs-overlay="dots">

Tasty & Healthy

For those who have taste for life.

my result looks like this

Tasty & Healthy

For those who have taste for life.

i want to get comma in between the result that means my result should be like this

<div id="demo-1" data-zs-src='["http://localhost/fahiz_kitchen/uploads/upload-file1496902770.jpg",
"http://localhost/fahiz_kitchen/uploads/upload-file1496901910.gif",
"http://localhost/fahiz_kitchen/uploads/upload-file1496901900.jpg",
"http://localhost/fahiz_kitchen/uploads/upload-file1496901887.jpg"

Body:
Chnage it like.

 $data = [<?php
    foreach( $slides as $slide ){
     ?>"<?php echo base_url();?>uploads/<?php echo $slide->image;?>",
   <?php }?>];
$finaldata = rtrim($data, ',');

<div id="demo-1" data-zs-src="'.$finaldata.'" data-zs-overlay="dots">
<div class="demo-inner-content">
  <h1><span>Tasty</span> & <span>Healthy</span></h1>
<p>For those who have taste for life.</p>
</div>

You are starting php inside already started it.


问:
Join SQL tables
Suppose that in table "ab" I have the names of the students that get along from class "a" and class "b", identically I have table "ac" and "bc". What SQL query should I use in order to get all the combinations possible of students who can form groups (i.e. "get along together")? And how can i extend this to n classes?
For example: John from class a gets along with Jen from class b and Steff from class c, and Jen and Steff get along. Therefore John, Jen and Steff can form a group).</p>

答:
For this I would create two tables, a student table (id, name, class) and a relationship table (student1, student2). You might also want to add a class table for the time, location etc of the class.

A friendship would have two relationships (2,3) and (3,2) to describe it as two way. One way might be a follower or fan of another student.
This will scale up to a lot more than 3 classes.

Then you can use multiple joins to get friends of friends and so on to an arbitrary depth.

Here is a query to get friends of friends (fof):

```<code>SELECT fof_details.*
FROM relationships r
INNER JOIN relationships fof
ON r.student2 = fof.student1
INNER JOIN student fof_details
ON fof_details.id = fof.student2
WHERE r.student1 = '12';
</code>```

There are also database engines made specifically for doing graph modeling like this.

http://openquery.com/blog/graph-engine-mkii

Title: Join SQL tables

Body:
For this I would create two tables, a student table (id, name, class) and a relationship table (student1, student2). You might also want to add a class table for the time, location etc of the class.

A friendship would have two relationships (2,3) and (3,2) to describe it as two way. One way might be a follower or fan of another student.
This will scale up to a lot more than 3 classes.

Then you can use multiple joins to get friends of friends and so on to an arbitrary depth.

Here is a query to get friends of friends (fof):

SELECT fof_details.*
FROM relationships r
INNER JOIN relationships fof
ON r.student2 = fof.student1
INNER JOIN student fof_details
ON fof_details.id = fof.student2
WHERE r.student1 = '12';

There are also database engines made specifically for doing graph modeling like this.

http://openquery.com/blog/graph-engine-mkii


问:
C/C++ Windows or Linux map random memory blocks into consecutive order
My requirement is to emulate an old motorola memory controller.

Basically the controller maps 8 x 8Kbyte memory blocks into a 64Kbyte address space for subsequent access by a CPU.  The controller has access to upto 1024 such 8K blocks.

At the moment I have accomplished this by using a large flat array like so:

```<code>unsigned char Memory[1024][8192];
int MappedMemoryBank[8];
short int Address;
</code>```

Then to access any particular memory address I use something like this

```<code>unsigned char aByte = Memory[MappedMemoryBank[Address>>13]][Address&0x1FFF];
</code>```

This works fine but as memory references comprise 99% of processing time it is very inefficient.

Is there a memory mapping mechanism where I can allocate a number (1024) of memory blocks and then map them (in any order) into a consecutive memory space?

This would reduce my memory references to:

```<code>unsigned char *Memory;
Memory = pointed to first byte of (re-)mapped memory

unsigned char aByte = Memory[Address];
</code>```

Which would be an order of magnitude faster (I hope)

A solution for either Windows and/or Linux is OK.

答:
I managed to find in Linux there is the mremap() function.

And in Windows is the AWE Address Windowing Exextensions MapUserPhysicalPages function allows this.

I just tested the AWE functions and they work well.  Not sure how efficient they are but they work nicely.

Body:
My requirement is to emulate an old motorola memory controller.

Basically the controller maps 8 x 8Kbyte memory blocks into a 64Kbyte address space for subsequent access by a CPU.  The controller has access to upto 1024 such 8K blocks.

At the moment I have accomplished this by using a large flat array like so:

unsigned char Memory[1024][8192];
int MappedMemoryBank[8];
short int Address;

Then to access any particular memory address I use something like this

unsigned char aByte = Memory[MappedMemoryBank[Address>>13]][Address&0x1FFF];

This works fine but as memory references comprise 99% of processing time it is very inefficient.

Is there a memory mapping mechanism where I can allocate a number (1024) of memory blocks and then map them (in any order) into a consecutive memory space?

This would reduce my memory references to:

unsigned char *Memory;
Memory = pointed to first byte of (re-)mapped memory

unsigned char aByte = Memory[Address];

Which would be an order of magnitude faster (I hope)

A solution for either Windows and/or Linux is OK.


问:
Issues with existing from the navigation bar in android
I have a user login activity once the user logs in he is redirected to navigation bar activity.

Problem : When the user is on the navigation bar activity and press back button - in this case the login screen pops ups again.

What I want : When the user clicks on the back button in the navigation screen the app should exit and it should not open the login screen.

答:
once the user loges in he is redirected to navigation bar activity.

When you redirect to Navigation Activity from Login Activity on successful login, please add one line below you startActivity(intent), i.e. finish().

For Ex:

```<code>Intent intent = new Intent(this, NavigationActivity.class);
startActivity(intent);
finish();
</code>```

Body:
once the user loges in he is redirected to navigation bar activity.

When you redirect to Navigation Activity from Login Activity on successful login, please add one line below you startActivity(intent), i.e. finish().

For Ex:

Intent intent = new Intent(this, NavigationActivity.class);
startActivity(intent);
finish();


问:
Jquery Data Tables sorting issue
I am using datatable to show my data in a table and my code is like this:

```<code>$('#data_table').DataTable(data);
</code>```

Right now i want to apply the properties "order": [] to the data table.
I already tried below option but not working.

```<code>$('#data_table').DataTable( {
"order": [],
data:data,
} );
</code>```

答:
You have to specify which columns you need to apply ordering and what order(asc or desc)

```<code>"order": [[ 0, "asc" ]], where 0 is for first column
</code>```

in case you need more its

```<code>"order": [[ 0, "asc" ],[1 , "asc"]]
</code>```

Title: Jquery Data Tables sorting issue

Body:
I am using datatable to show my data in a table and my code is like this:

$('#data_table').DataTable(data);

Right now i want to apply the properties "order": [] to the data table.
I already tried below option but not working.

$('#data_table').DataTable( {
"order": [],
data:data,
} );

Body:
You have to specify which columns you need to apply ordering and what order(asc or desc)

"order": [[ 0, "asc" ]], where 0 is for first column

in case you need more its

"order": [[ 0, "asc" ],[1 , "asc"]]


问:
Shuffle ArrayList of objects
Read carefully before marking duplicate or downvoting.

My Requirement is to shuffle Arraylist of object keeping the list data same just changing the position.
I have an of type Dummydata :

```<code>List<DummyData> dataList = new ArrayList<>();
</code>```

My DummyData class has three String fields.

```<code>So adding some data for clarification:

dataList.add(new DummyData("Item1","Price1","Discount1"));
dataList.add(new DummyData("Item2","Price2","Discount2"));
dataList.add(new DummyData("Item3","Price3","Discount3"));
dataList.add(new DummyData("Item4","Price4","Discount4"));
dataList.add(new DummyData("Item5","Price5","Discount5"));
</code>```

When I use Collections.shuffle(dataList);

the output is :

```<code>Item5 Price3 Discount4
Item2 Price1 Discount2
and some random output like this everytime.
</code>```

My intended output is :

```<code>Item2 Price2 Discount2
Item5 Price5 Discount5
Item1 Price1 Discount1
</code>```

Just the position should change list data should not jumble.
so my question is this possible to achieve using Collections.shuffle or not??

答:
Hi Sumit i dont know why there are few downvote it is because you have not informed that you are new to Java Language
Please find my answer below</p>

```<code>import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

final class Product {
    private final String name;
    private final Double price;
    private final Double discount;

    Product(String name, Double price, Double discount) {
        this.name = name;
        this.price = price;
        this.discount = discount;
    }

    @Override
    public String toString() {
        return "{name=" + name + ", price=" + price + ", discount=" + discount + "}";
    }
}

public final class Main {

    public static void main(String[] args) {
        List<Product> products = new ArrayList<>();
        products.add(new Product("Watch", 45.99, 9.99));
        products.add(new Product("Keyboard", 21.99, 3.99));
        products.add(new Product("Mouse", 99.99, 4.99));

        System.out.println("Original items Before shuffle are");
        products.forEach(System.out::println);

        Collections.shuffle(products);
        System.out.println("Original items After shuffle are");
        products.forEach(System.out::println);
    }
}
</code>```

Title: Shuffle ArrayList of objects

Body:
Read carefully before marking duplicate or downvoting.

My Requirement is to shuffle Arraylist of object keeping the list data same just changing the position.
I have an of type Dummydata :

List<DummyData> dataList = new ArrayList<>();

My DummyData class has three String fields.

So adding some data for clarification:

dataList.add(new DummyData("Item1","Price1","Discount1"));
dataList.add(new DummyData("Item2","Price2","Discount2"));
dataList.add(new DummyData("Item3","Price3","Discount3"));
dataList.add(new DummyData("Item4","Price4","Discount4"));
dataList.add(new DummyData("Item5","Price5","Discount5"));

When I use Collections.shuffle(dataList);

the output is :

Item5 Price3 Discount4
Item2 Price1 Discount2
and some random output like this everytime.

My intended output is :

Item2 Price2 Discount2
Item5 Price5 Discount5
Item1 Price1 Discount1

Just the position should change list data should not jumble.
so my question is this possible to achieve using Collections.shuffle or not??

Body:
Hi Sumit i dont know why there are few downvote it is because you have not informed that you are new to Java Language
Please find my answer below

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

final class Product {
    private final String name;
    private final Double price;
    private final Double discount;

    Product(String name, Double price, Double discount) {
        this.name = name;
        this.price = price;
        this.discount = discount;
    }

    @Override
    public String toString() {
        return "{name=" + name + ", price=" + price + ", discount=" + discount + "}";
    }
}

public final class Main {

    public static void main(String[] args) {
        List<Product> products = new ArrayList<>();
        products.add(new Product("Watch", 45.99, 9.99));
        products.add(new Product("Keyboard", 21.99, 3.99));
        products.add(new Product("Mouse", 99.99, 4.99));

        System.out.println("Original items Before shuffle are");
        products.forEach(System.out::println);

        Collections.shuffle(products);
        System.out.println("Original items After shuffle are");
        products.forEach(System.out::println);
    }
}


问:
MPI Send is giving segmentation fault
I'm trying to run a genetic algorithm with MPI(boost), in which I have to send a serialized object from rank 0 to all other ranks. But I'm getting an error of segmentation fault when I try to send data.

Here's the code, output and the error I'm getting.

Code: the problem is exactly in world.send(0, 0, newP);

```<code>int main (int argc, char** argv)
{
    Population *pop = NULL;
    RuckSack r(true);
    int size, rank;
    Ga ga;
    namespace mpi = boost::mpi;
    mpi::environment env;
    mpi::communicator world;

    int countGeneration = 0;

    /* code */

    if (world.rank() == 0)
    {

        if (pop == NULL)
        {

            pop = new Population(60,true);
        }

    }

    for (int m = 0; m < 20; m++)
    {
        /* code */

        for (int i = 0; i< world.size(); i++)
        {
            world.send(i,0,pop);
        }

        world.recv(0, 0, pop);
        Population newP = *pop;

        newP = ga.evolvePopulation(newP, world.size());

        world.send(0, 0, newP);

    MPI_Finalize();

    return (EXIT_SUCCESS);
}
</code>```

Error:

```<code>mpirun noticed that process rank 0 with PID 10336 on node user exited on signal 11 (Segmentation fault).
</code>```

Output:

```<code>[user:10336] *** Process received signal ***
[user:10336] Signal: Segmentation fault (11)
[user:10336] Signal code: Address not mapped (1)
[user:10336] Failing at address: 0x31
[user:10336] [ 0] /lib/x86_64-linux-gnu/libc.so.6(+0x35860)[0x7f1e93064860]
[user:10336] [ 1] /usr/lib/x86_64-linux-gnu/libboost_serialization.so.1.61.0(+0x14a24)[0x7f1e9409da24]
[user:10336] [ 2] /usr/lib/x86_64-linux-gnu/libboost_serialization.so.1.61.0(+0x15d11)[0x7f1e9409ed11]
[user:10336] [ 3] ./teste(+0x1de7c)[0x55ab4c07ae7c]
[user:10336] [ 4] ./teste(+0x1dd2c)[0x55ab4c07ad2c]
[user:10336] [ 5] ./teste(+0x1db3a)[0x55ab4c07ab3a]
[user:10336] [ 6] ./teste(+0x1d8eb)[0x55ab4c07a8eb]
[user:10336] [ 7] ./teste(+0x1d2da)[0x55ab4c07a2da]
[user:10336] [ 8] ./teste(+0x1cb20)[0x55ab4c079b20]
[user:10336] [ 9] ./teste(+0x1bed0)[0x55ab4c078ed0]
[user:10336] [10] ./teste(+0x1b47c)[0x55ab4c07847c]
[user:10336] [11] ./teste(+0x19741)[0x55ab4c076741]
[user:10336] [12] /lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf1)[0x7f1e9304f3f1]
[user:10336] [13] ./teste(+0x112aa)[0x55ab4c06e2aa]
[user:10336] *** End of error message ***
</code>```

答:
Here are some wild guesses:

You should only do the initial send instruction on a rank0 process - right now you perform it an all of the processes which doesn't make sense (and might be a cause of the problem)

You should not send to "self". In the first iteration of you loop, the rank0 does a send to itself, which afaik will block the process waiting for a recv. But since the rank0 is blocked it will never reach the 'recv' line and will remain locked forever. Apart from that it again doesn't make sense for a process to send data to itself.

Those are just loose suggestions as i have a limited experience in using MPI. Hope it helps!

Title: MPI Send is giving segmentation fault

Body:
I'm trying to run a genetic algorithm with MPI(boost), in which I have to send a serialized object from rank 0 to all other ranks. But I'm getting an error of segmentation fault when I try to send data.

Here's the code, output and the error I'm getting.

Code: the problem is exactly in world.send(0, 0, newP);

int main (int argc, char** argv)
{
    Population *pop = NULL;
    RuckSack r(true);
    int size, rank;
    Ga ga;
    namespace mpi = boost::mpi;
    mpi::environment env;
    mpi::communicator world;

    int countGeneration = 0;

    /* code */

    if (world.rank() == 0)
    {

        if (pop == NULL)
        {

            pop = new Population(60,true);
        }

    }

    for (int m = 0; m < 20; m++)
    {
        /* code */

        for (int i = 0; i< world.size(); i++)
        {
            world.send(i,0,pop);
        }

        world.recv(0, 0, pop);
        Population newP = *pop;

        newP = ga.evolvePopulation(newP, world.size());

        world.send(0, 0, newP);

    MPI_Finalize();

    return (EXIT_SUCCESS);
}

Error:

mpirun noticed that process rank 0 with PID 10336 on node user exited on signal 11 (Segmentation fault).

Output:

[user:10336] *** Process received signal ***
[user:10336] Signal: Segmentation fault (11)
[user:10336] Signal code: Address not mapped (1)
[user:10336] Failing at address: 0x31
[user:10336] [ 0] /lib/x86_64-linux-gnu/libc.so.6(+0x35860)[0x7f1e93064860]
[user:10336] [ 1] /usr/lib/x86_64-linux-gnu/libboost_serialization.so.1.61.0(+0x14a24)[0x7f1e9409da24]
[user:10336] [ 2] /usr/lib/x86_64-linux-gnu/libboost_serialization.so.1.61.0(+0x15d11)[0x7f1e9409ed11]
[user:10336] [ 3] ./teste(+0x1de7c)[0x55ab4c07ae7c]
[user:10336] [ 4] ./teste(+0x1dd2c)[0x55ab4c07ad2c]
[user:10336] [ 5] ./teste(+0x1db3a)[0x55ab4c07ab3a]
[user:10336] [ 6] ./teste(+0x1d8eb)[0x55ab4c07a8eb]
[user:10336] [ 7] ./teste(+0x1d2da)[0x55ab4c07a2da]
[user:10336] [ 8] ./teste(+0x1cb20)[0x55ab4c079b20]
[user:10336] [ 9] ./teste(+0x1bed0)[0x55ab4c078ed0]
[user:10336] [10] ./teste(+0x1b47c)[0x55ab4c07847c]
[user:10336] [11] ./teste(+0x19741)[0x55ab4c076741]
[user:10336] [12] /lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf1)[0x7f1e9304f3f1]
[user:10336] [13] ./teste(+0x112aa)[0x55ab4c06e2aa]
[user:10336] *** End of error message ***


问:
Problems with rerouting requests to a specific ip and port in IIS?
I have the following scenario and would like to seek some advise. I have a web application that I wrote for my company. Its purely in C#. My company mainly uses dot net for their development. Now, I have hosted the application on the local network on a specific port. Here is the catch- my company has only one port open to the public where the Apache server is hosted for accepting incoming requests. They dont want to host my application on a different public port and they want me to do something such that I can host the java application on that specific public port which is not possible.
I was thinking of redirecting - a service that is hosted on that public port and redirects to the port where my application is hosted. Again, my boss doesnt want me to expose the url of the application to the public. He just wants me to redirect without exposing the ip and port.
Can someone suggest me some solution. I have worked on redirecting in Nginx before but I dont know if there is a way to configure something like that in IIS.

Thanks

答:
Let's presume if your Java website is hosted on local network (192.168.1.2) with port 8080. And it is accessible from the browser by this url:
http://192.168.1.2:8080 from IIS server.

And you want to make it accessible by this domain: http://example.com

You need to install URL Rewrite and ARR module for IIS

Enable ARR. On the Application Request Routing page, select Enable proxy

Add Website from applications Pools -> Site Name(example.com)

Physical path (C:\example.com)

Add binding for example.com and port 80

Create web.config in C:\example.com folder

<?xml version="1.0" encoding="UTF-8"?><configuration>

```<code><system.webServer>
    <rewrite>
        <rules>
           <rule name="rewrite to 8080" stopProcessing="true">
                <match url="(.*)" />
                <action type="Rewrite" url="http://192.168.1.2:8080/{R:1}" />
            </rule>
        </rules>
    </rewrite>
</system.webServer>
</code>```

</configuration>

Body:
Let's presume if your Java website is hosted on local network (192.168.1.2) with port 8080. And it is accessible from the browser by this url:
http://192.168.1.2:8080 from IIS server.

And you want to make it accessible by this domain: http://example.com

You need to install URL Rewrite and ARR module for IIS

Enable ARR. On the Application Request Routing page, select Enable proxy

Add Website from applications Pools -> Site Name(example.com)

Physical path (C:\example.com)

Add binding for example.com and port 80

Create web.config in C:\example.com folder

<?xml version="1.0" encoding="UTF-8"?><configuration>

<system.webServer>
    <rewrite>
        <rules>
           <rule name="rewrite to 8080" stopProcessing="true">
                <match url="(.*)" />
                <action type="Rewrite" url="http://192.168.1.2:8080/{R:1}" />
            </rule>
        </rules>
    </rewrite>
</system.webServer>

</configuration>