问:
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>```

答:
Use Below Code:

First Declare these global variables:

```<code>int visibleItemCount, totalItemCount = 1;
int firstVisiblesItems = 0;
int totalPages = 1; // get your total pages from web service first response
int current_page = 0;

boolean canLoadMoreData = true; // make this variable false while your web service call is going on.

LinearLayoutManager linearLayoutManager;
</code>```

Assign Layout manager to your Recyclerview:

```<code>linearLayoutManager = new LinearLayoutManager(mActivity);
mRecyclerView.setLayoutManager(linearLayoutManager);
</code>```

Scroll Listener of your recyclerview:

```<code>mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            if (dy > 0) //check for scroll down
            {
                visibleItemCount = linearLayoutManager.getChildCount();
                totalItemCount = linearLayoutManager.getItemCount();
                firstVisiblesItems = linearLayoutManager.findFirstVisibleItemPosition();

                    if (canLoadMoreData) {
                        if ((visibleItemCount + firstVisiblesItems) >= totalItemCount) {
                            if (current_page < totalPages) {
                                canLoadMoreData  = false;
                                /**
                                 * .
                                 * .
                                 * .
                                 * .call your webservice with page index
                                 * .
                                 * .
                                 *
                                 */
                                //After completion of web service make 'canLoadMoreData = true'
                            }
                        }
                    }

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

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:
Use Below Code:

First Declare these global variables:

int visibleItemCount, totalItemCount = 1;
int firstVisiblesItems = 0;
int totalPages = 1; // get your total pages from web service first response
int current_page = 0;

boolean canLoadMoreData = true; // make this variable false while your web service call is going on.

LinearLayoutManager linearLayoutManager;

Assign Layout manager to your Recyclerview:

linearLayoutManager = new LinearLayoutManager(mActivity);
mRecyclerView.setLayoutManager(linearLayoutManager);

Scroll Listener of your recyclerview:

mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            if (dy > 0) //check for scroll down
            {
                visibleItemCount = linearLayoutManager.getChildCount();
                totalItemCount = linearLayoutManager.getItemCount();
                firstVisiblesItems = linearLayoutManager.findFirstVisibleItemPosition();

                    if (canLoadMoreData) {
                        if ((visibleItemCount + firstVisiblesItems) >= totalItemCount) {
                            if (current_page < totalPages) {
                                canLoadMoreData  = false;
                                /**
                                 * .
                                 * .
                                 * .
                                 * .call your webservice with page index
                                 * .
                                 * .
                                 *
                                 */
                                //After completion of web service make 'canLoadMoreData = true'
                            }
                        }
                    }

            }
        }
    });


来源: stackexchange

问:
Promises in JavaScript not executing propertly
I have this series of steps that needs to be completed in order:

Validate an object

Fetch an image URL using Bing's image search API

Add the found URLs to the object

Make a post request and send the object

A sample object looks like:

```<code>`{
    options: [{
      text: 'Pizza',
      votes: 0,
      imageURL: ""
    }, {
      text: 'Hot Dog',
      votes: 0,
      imageURL: ""
    }]
  };`
</code>```

Because the order in this series, I am using promises to make sure everything goes in the order specified above. So far I have:

  function validatePoll() {
    var isValid = true;
    for (var i = 0; i < $scope.poll.options.length; i++) {
      if (!$scope.poll.options[i].text) {
        isValid = false;
        break;
      }
    }
    return isValid;
  }

  let promiseURL = function(searchTerm) {
    return new Promise(function(resolve, reject) {
      $http.get('https://api.cognitive.microsoft.com/bing/v5.0/images/search?q=' + searchTerm + '&count=1&offset=0&mkt=en-us&safeSearch=Strict', {
        headers: {
          'Ocp-Apim-Subscription-Key': 'XXXXXXXXXXXXXXXXXXXXXXXXXX'
        }
      }).success(function(response) {
        console.log(response);
        resolve(response);
      }).error(function (err, status) {
        reject(err);
      })
    })
  };

  let fetchImageURL = function() {
    for(var i = 0; i < $scope.poll.options.length; i++) {
      console.log(promiseURL($scope.poll.options[i].text));
    }
  }

  $scope.submitChoice = function() {
    var isValid = validatePoll();
    if(isValid) {
      fetchImageURL();
    } else {
      console.log("Not Valid Poll");
    }
  }```

But what ends up happening is the console.log(promiseURL($scope.poll.options[i].text)); in the fetchImageURL returns an unresolved promise instead of the response string I want instead. How might I be able to fix the code to ensure that:

A call to promiseURL is made with the proper argument

A response is received and can be parsed

The parsed information can be added to the imageURL property in the polls object

答:
You're seeing the printout of the Promise because you're printing out the promise. You need to be handling the promise resolve/reject. What you should be calling is:</p>

```<code>promiseURL($scope.poll.options[i].text)
   .then(function(data){
      console.log("Success",data)
   })
   .catch(function(error){
      console.log("Error",error")
   })
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have this series of steps that needs to be completed in order:

Validate an object

Fetch an image URL using Bing's image search API

Add the found URLs to the object

Make a post request and send the object

A sample object looks like:

`{
    options: [{
      text: 'Pizza',
      votes: 0,
      imageURL: ""
    }, {
      text: 'Hot Dog',
      votes: 0,
      imageURL: ""
    }]
  };`

Because the order in this series, I am using promises to make sure everything goes in the order specified above. So far I have:

  function validatePoll() {
    var isValid = true;
    for (var i = 0; i < $scope.poll.options.length; i++) {
      if (!$scope.poll.options[i].text) {
        isValid = false;
        break;
      }
    }
    return isValid;
  }

  let promiseURL = function(searchTerm) {
    return new Promise(function(resolve, reject) {
      $http.get('https://api.cognitive.microsoft.com/bing/v5.0/images/search?q=' + searchTerm + '&count=1&offset=0&mkt=en-us&safeSearch=Strict', {
        headers: {
          'Ocp-Apim-Subscription-Key': 'XXXXXXXXXXXXXXXXXXXXXXXXXX'
        }
      }).success(function(response) {
        console.log(response);
        resolve(response);
      }).error(function (err, status) {
        reject(err);
      })
    })
  };

  let fetchImageURL = function() {
    for(var i = 0; i < $scope.poll.options.length; i++) {
      console.log(promiseURL($scope.poll.options[i].text));
    }
  }

  $scope.submitChoice = function() {
    var isValid = validatePoll();
    if(isValid) {
      fetchImageURL();
    } else {
      console.log("Not Valid Poll");
    }
  }

But what ends up happening is the console.log(promiseURL($scope.poll.options[i].text)); in the fetchImageURL returns an unresolved promise instead of the response string I want instead. How might I be able to fix the code to ensure that:

A call to promiseURL is made with the proper argument

A response is received and can be parsed

The parsed information can be added to the imageURL property in the polls object

Body:
You're seeing the printout of the Promise because you're printing out the promise. You need to be handling the promise resolve/reject. What you should be calling is:

promiseURL($scope.poll.options[i].text)
   .then(function(data){
      console.log("Success",data)
   })
   .catch(function(error){
      console.log("Error",error")
   })


问:
Springboot Camel context name
Is there an easy way to give a SpringBoot Camel context a name?

In a CDI environment I can name a CamelContext:

```<code>@ApplicationScoped
@ContextName("awesomename")
public class AwesomeRouteBuilder extends RouteBuilder {
</code>```

In SpringBoot it seems I have 2 options:

Either I need to either mess around with NameStrategy.

Or I need to use the @Configuration approach rather than extending SpringRouteBuilder and letting Spring create the camel context itself.

I believe giving a camel context a name is easy enough through xml configuration

What have people used to give a CamelContext a name in a Springboot environment?

答: You can configure the name in the application.properties or application.yaml configuration file for Spring Boot via camel.springboot.name, see https://github.com/apache/camel/blob/master/examples/camel-example-spring-boot/src/main/resources/application.properties#L19

Title: Springboot Camel context name

Body:
Is there an easy way to give a SpringBoot Camel context a name?

In a CDI environment I can name a CamelContext:

@ApplicationScoped
@ContextName("awesomename")
public class AwesomeRouteBuilder extends RouteBuilder {

In SpringBoot it seems I have 2 options:

Either I need to either mess around with NameStrategy.

Or I need to use the @Configuration approach rather than extending SpringRouteBuilder and letting Spring create the camel context itself.

I believe giving a camel context a name is easy enough through xml configuration

What have people used to give a CamelContext a name in a Springboot environment?


问:
Package Tab for net46 project in VS2017
VS2017 has a nice Package tab to enable using 'msbuild pack' for making nuget packages. It works for netstandardXX portable libraries, but is it possible to use it for traditional net framework libraries as well?

I'm thinking that I can create a netstandard portable library, then change the target framework to net46:

```<code><Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>net46</TargetFramework>
  </PropertyGroup>

</Project>
</code>```

答:
Yes this works exactly like you want it to: Create an "SDK-based" project with net* as TargetFramework.

The only downside is that some designers (WinForms, XAML, EDMX) won't work yet with these types of project, but for logic libraries this is now an easier way to create NuGet packages.

Title: Package Tab for net46 project in VS2017

Body:
VS2017 has a nice Package tab to enable using 'msbuild pack' for making nuget packages. It works for netstandardXX portable libraries, but is it possible to use it for traditional net framework libraries as well?

I'm thinking that I can create a netstandard portable library, then change the target framework to net46:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>net46</TargetFramework>
  </PropertyGroup>

</Project>


问:
stemming library in java
Is there any library for stemming in java!? </p>

答: You might want to look at Apache Lucene. It is generally written to do other things, but it does some stemming as part of its indexing process.</p>

ContentLicense: CC BY-SA 2.5

Title: stemming library in java


问:
Values pf pandas data frame columns as list
I am creating a data frame from dictionary in a list like below :

```<code>[{'points': [-9.3613566605198262, 4.0910018605047171, -9.3473134841172731, 4.0960021770649475], 'uid': 0},
 {'points': [-9.4687215264026712, 4.0132947848279499, -9.3641925245477857, 4.0159059337303784], 'uid': 1},
</code>```

The above is a list called l1

For data frame:

```<code>df = pd.DataFrame.from_records(l1)
</code>```

This creates following df:

```<code>   points                                          uid
0  [-9.3613566605198262, 4.09100186050......]      0
1  [-9.4687215264026712, 4.01329478482......]      1
</code>```

I want to know how to remove the list format/ square brackets from the points column, and it should contain simple comma separated values.

Also, How to limit the decimal place only to 2 digits?

I tried the following, but it doesn't works.

```<code>np.round(df, 2)
</code>```

and

```<code>df.round({'points':2})
</code>```

expected df

```<code>   points                      uid
0  -9.36, 4.09, -9.34, 4.09    0
1  -9.46, 4.01, -9.36, 4.01    1
</code>```

Body:
I am creating a data frame from dictionary in a list like below :

[{'points': [-9.3613566605198262, 4.0910018605047171, -9.3473134841172731, 4.0960021770649475], 'uid': 0},
 {'points': [-9.4687215264026712, 4.0132947848279499, -9.3641925245477857, 4.0159059337303784], 'uid': 1},

The above is a list called l1

For data frame:

df = pd.DataFrame.from_records(l1)

This creates following df:

   points                                          uid
0  [-9.3613566605198262, 4.09100186050......]      0
1  [-9.4687215264026712, 4.01329478482......]      1

I want to know how to remove the list format/ square brackets from the points column, and it should contain simple comma separated values.

Also, How to limit the decimal place only to 2 digits?

I tried the following, but it doesn't works.

np.round(df, 2)

and

df.round({'points':2})

expected df

   points                      uid
0  -9.36, 4.09, -9.34, 4.09    0
1  -9.46, 4.01, -9.36, 4.01    1

Body:
Just a heads up... you don't need from_records, pd.DataFrame handles lists of dictionaries just fine.

df = pd.DataFrame(l1)
df

                                                                           points  uid
0  [-9.361356660519826, 4.091001860504717, -9.347313484117272, 4.096002177064947]    0
1   [-9.468721526402671, 4.01329478482795, -9.364192524547786, 4.015905933730378]    1

I like using these string formatters instead

f = lambda n: ', '.join(['{:.2f}'] * n).format
d = lambda x: f(len(x))(*x)
df.assign(points=df.points.apply(d))

                     points  uid
0  -9.36, 4.09, -9.35, 4.10    0
1  -9.47, 4.01, -9.36, 4.02    1


问:
Hive results not being saved into S3 bucket
I am having trouble getting my Hive output to save to S3. I have tried sshing into the master node and running my command in Hive but it does not save the output. I have also tried running the command in Hue from the EMR console in AWS and still it does not save to S3. I also added the script as a step and still it doesn't save. The only way I have been able to get the results is to run it in Hue and then click to see results and download that way, then push them to S3. I am clueless as to why this is happening. Here is the query that I am running.

```<code>with temp as (
select /*+ streamtable(l) */ a.id, a.name, a.page
from my_table a
join my_other_table l on (a.id = l.id)
group by a.page, a.id, a.name)
insert overwrite directory 's3://bucket/folder/folder2/folder3/folder4/folder5/folder6/folder7/'
select page, count(distinct id) over (PARTITION BY page)
from temp
group by page;
</code>```

As a note, I would prefer for the solution to work when adding a step since I plan to add x number of steps sequentially.

答:
The normal way I've seen Amazon EMR output to Amazon S3 is to CREATE EXTERNAL TABLE with a LOCATION in Amazon S3.

For example:

```<code>CREATE EXTERNAL TABLE IF NOT EXISTS output_table
(gram string, year int, ratio double, increase double)
ROW FORMAT DELIMITED FIELDS TERMINATED BY '\t'
STORED AS TEXTFILE
LOCATION 's3://my-bucket/directory';
</code>```

Then, just INSERT data into that table:

```<code>INSERT OVERWRITE TABLE output_table
SELECT gram FROM table...
</code>```

Body:
I am having trouble getting my Hive output to save to S3. I have tried sshing into the master node and running my command in Hive but it does not save the output. I have also tried running the command in Hue from the EMR console in AWS and still it does not save to S3. I also added the script as a step and still it doesn't save. The only way I have been able to get the results is to run it in Hue and then click to see results and download that way, then push them to S3. I am clueless as to why this is happening. Here is the query that I am running.

with temp as (
select /*+ streamtable(l) */ a.id, a.name, a.page
from my_table a
join my_other_table l on (a.id = l.id)
group by a.page, a.id, a.name)
insert overwrite directory 's3://bucket/folder/folder2/folder3/folder4/folder5/folder6/folder7/'
select page, count(distinct id) over (PARTITION BY page)
from temp
group by page;

As a note, I would prefer for the solution to work when adding a step since I plan to add x number of steps sequentially.

Body:
The normal way I've seen Amazon EMR output to Amazon S3 is to CREATE EXTERNAL TABLE with a LOCATION in Amazon S3.

For example:

CREATE EXTERNAL TABLE IF NOT EXISTS output_table
(gram string, year int, ratio double, increase double)
ROW FORMAT DELIMITED FIELDS TERMINATED BY '\t'
STORED AS TEXTFILE
LOCATION 's3://my-bucket/directory';

Then, just INSERT data into that table:

INSERT OVERWRITE TABLE output_table
SELECT gram FROM table...


问:
the efficient way to get the high 32 bits of the product of two unsigned integers c++
```<code>unsigned int a = 4294967295;  // (2^32)-1
unsigned int b = 2;
</code>```

I am trying to figure out the most efficient way to get the high 32 bits of the product of two unsigned integers.
For example, using CUDA programming I can just unsigned int first32bits = __umulhi(a,b) and get the high 32 bits.

Are there ways to do such thing in C++?

Here's my approach:

```<code>unsigned long c = ( ((unsigned long)a * (unsigned long)b ) >> 32) & 0x00000000FFFFFFFF;
</code>```

Are there any ways to make my approach faster?

答:
Intrinsics like __umulhi() are designed to use fewer / specialized instructions on specific architectures (Nvidia GPUs here). You would have to look at proprietary solutions as suggested in the comments (e.g. Intel for CPU) rather than expect something from C++.

In this situation I highly doubt you will find an intrinsic that replaces your approach with any meaningful performance increases.

Body:
unsigned int a = 4294967295;  // (2^32)-1
unsigned int b = 2;

I am trying to figure out the most efficient way to get the high 32 bits of the product of two unsigned integers.
For example, using CUDA programming I can just unsigned int first32bits = __umulhi(a,b) and get the high 32 bits.

Are there ways to do such thing in C++?

Here's my approach:

unsigned long c = ( ((unsigned long)a * (unsigned long)b ) >> 32) & 0x00000000FFFFFFFF;

Are there any ways to make my approach faster?


问:
jqgrid tooltip for header cells only
How can i add tooltip to my jqgrid header cells? in case of multiple grids in the same page.

This is my code:

```<code>var initialized = [false,false,false];
    $('#tabs').tabs
    (
        {
            show: function(event, ui)
                {
                    if(ui.index == 0 && !initialized[0])
                    {
                        init_confirm_payment();
                        initialized[0] = true;
                    }
                    else if(ui.index == 1 && !initialized[1])
                    {
                        init_signatory1_payment();
                        initialized[1] = true;
                    }
                    else if(ui.index == 2 && !initialized[2])
                    {
                        init_signatory2_payment();
                        initialized[2] = true;
                    }
                }
        }
    );

        function init_table1()
        {
            jQuery("#cpayment").jqGrid({
                url:'loadgrid.jsp?type=1',
                datatype: "xml",
                loadonce:true ,
                direction:"rtl",
                height: '100%',
                width: '100%',
                headertitles: true ,
                colNames:['col11','col22','col33','col44'],
                colModel:[
                    {name:'col11',xmlmap:'col11', width:80, align:"right",sorttype:"int"},
                    {name:'col22',xmlmap:'col22', width:70, align:"right",sorttype:"int"},
                    {name:'col33',xmlmap:'col33', width:120, align:"right",sorttype:"string"},
                    {name:'col44:'col44', width:60, align:"right",sorttype:"float"},
                ],
                multiselect: false,
                autowidth: true,
                forceFit: false,
                shrinkToFit: false,
                loadonce:true
            });

        }

        function init_table2()
        {
            jQuery("#payment1").jqGrid({
                url:'loadgrid.jsp?type=2',
                datatype: "xml",
                direction:"rtl",
                height: '100%',
                width: '100%',
                headertitles: true ,
                colNames:['col111','col222','col333','col444'],
                colModel:[
                    {name:'col111',xmlmap:'col111', width:80, align:"right",sorttype:"int"},
                    {name:'col222',xmlmap:'col222', width:70, align:"right",sorttype:"int"},
                    {name:'col333',xmlmap:'col333', width:120, align:"right",sorttype:"string"},
                    {name:'col444',xmlmap:'col444', width:60, align:"right",sorttype:"float"},
                ],
                multiselect: false,
                autowidth: true,
                forceFit: false,
                shrinkToFit: false,
                loadonce:true
            });
        }

        function init_table3()
        {
            jQuery("#payment2").jqGrid({
                url:'loadgrid.jsp?type=3',
                datatype: "xml",
                direction:"rtl",
                height: '100%',
                width: '100%',
                headertitles: true ,
                colNames:['col1','col2','col3','col4'],
                colModel:[
                    {name:'col1',xmlmap:'col1', width:80, align:"right",sorttype:"int"},
                    {name:'col2',xmlmap:'col2', width:70, align:"right",sorttype:"int"},
                    {name:'col3',xmlmap:'col3', width:120, align:"right",sorttype:"string"},
                    {name:'col4xmlmap:'col4', width:60, align:"right",sorttype:"float"},
                ],
                multiselect: false,
                autowidth: true,
                forceFit: false,
                shrinkToFit: false,
                loadonce:true
            });
        }

        function test()
        {
            var thd = jQuery("thead:first", $("#cpayment").hdiv)[0];
            jQuery("tr th:eq(" + 3 + ")", thd).attr("title", "bla bla");

            var thd1 = jQuery("thead:first", $("#payment1").hdiv)[0];
            jQuery("tr th:eq(" + 3 + ")", thd1).attr("title", "bla bla1");
        }
    </script>

</head>
<body>
<form>
    <div id="tabs">
        <ul>
            <li><a href="#tabs-1"> tab1 </a></li>
            <li><a href="#tabs-2"> tab2 </a></li>
            <li><a href="#tabs-3"> tab3 </a></li>
        </ul>

        <div id="tabs-1">
            <table id="cpayment"></table>
        </div>

        <div id="tabs-2">
            <table id="payment1"></table>
        </div>

        <div id="tabs-3">
            <table id="payment2"></table>
        </div>
    </div>
    <input type="button" onClick="test()">
</form>
</body>
</code>```

Thank's In Advance.

答:
To add tooltip just call this methode on loadcomplete:</p>

```<code>addToolTipForColumnheader('YourGridID');

function addToolTipForColumnheader(gridID){
    var columnNameList=$('#'+gridID)[0].p.colNames;
    for (var i = 0; i < columnNameList.length; i++){
        var columnName=$('#'+gridID)[0].p.colModel[i].name;
        $('#'+gridID+'_'+columnName).attr("title", $('#'+gridID)[0].p.colNames[i]);
    }
}
</code>```

Title: jqgrid tooltip for header cells only

Body:
How can i add tooltip to my jqgrid header cells? in case of multiple grids in the same page.

This is my code:

var initialized = [false,false,false];
    $('#tabs').tabs
    (
        {
            show: function(event, ui)
                {
                    if(ui.index == 0 && !initialized[0])
                    {
                        init_confirm_payment();
                        initialized[0] = true;
                    }
                    else if(ui.index == 1 && !initialized[1])
                    {
                        init_signatory1_payment();
                        initialized[1] = true;
                    }
                    else if(ui.index == 2 && !initialized[2])
                    {
                        init_signatory2_payment();
                        initialized[2] = true;
                    }
                }
        }
    );

        function init_table1()
        {
            jQuery("#cpayment").jqGrid({
                url:'loadgrid.jsp?type=1',
                datatype: "xml",
                loadonce:true ,
                direction:"rtl",
                height: '100%',
                width: '100%',
                headertitles: true ,
                colNames:['col11','col22','col33','col44'],
                colModel:[
                    {name:'col11',xmlmap:'col11', width:80, align:"right",sorttype:"int"},
                    {name:'col22',xmlmap:'col22', width:70, align:"right",sorttype:"int"},
                    {name:'col33',xmlmap:'col33', width:120, align:"right",sorttype:"string"},
                    {name:'col44:'col44', width:60, align:"right",sorttype:"float"},
                ],
                multiselect: false,
                autowidth: true,
                forceFit: false,
                shrinkToFit: false,
                loadonce:true
            });

        }

        function init_table2()
        {
            jQuery("#payment1").jqGrid({
                url:'loadgrid.jsp?type=2',
                datatype: "xml",
                direction:"rtl",
                height: '100%',
                width: '100%',
                headertitles: true ,
                colNames:['col111','col222','col333','col444'],
                colModel:[
                    {name:'col111',xmlmap:'col111', width:80, align:"right",sorttype:"int"},
                    {name:'col222',xmlmap:'col222', width:70, align:"right",sorttype:"int"},
                    {name:'col333',xmlmap:'col333', width:120, align:"right",sorttype:"string"},
                    {name:'col444',xmlmap:'col444', width:60, align:"right",sorttype:"float"},
                ],
                multiselect: false,
                autowidth: true,
                forceFit: false,
                shrinkToFit: false,
                loadonce:true
            });
        }

        function init_table3()
        {
            jQuery("#payment2").jqGrid({
                url:'loadgrid.jsp?type=3',
                datatype: "xml",
                direction:"rtl",
                height: '100%',
                width: '100%',
                headertitles: true ,
                colNames:['col1','col2','col3','col4'],
                colModel:[
                    {name:'col1',xmlmap:'col1', width:80, align:"right",sorttype:"int"},
                    {name:'col2',xmlmap:'col2', width:70, align:"right",sorttype:"int"},
                    {name:'col3',xmlmap:'col3', width:120, align:"right",sorttype:"string"},
                    {name:'col4xmlmap:'col4', width:60, align:"right",sorttype:"float"},
                ],
                multiselect: false,
                autowidth: true,
                forceFit: false,
                shrinkToFit: false,
                loadonce:true
            });
        }

        function test()
        {
            var thd = jQuery("thead:first", $("#cpayment").hdiv)[0];
            jQuery("tr th:eq(" + 3 + ")", thd).attr("title", "bla bla");

            var thd1 = jQuery("thead:first", $("#payment1").hdiv)[0];
            jQuery("tr th:eq(" + 3 + ")", thd1).attr("title", "bla bla1");
        }
    </script>

<form>

 tab1

 tab2

 tab3

    <input type="button" onClick="test()">
</form>

Thank's In Advance.

Body:
To add tooltip just call this methode on loadcomplete:

addToolTipForColumnheader('YourGridID');

function addToolTipForColumnheader(gridID){
    var columnNameList=$('#'+gridID)[0].p.colNames;
    for (var i = 0; i < columnNameList.length; i++){
        var columnName=$('#'+gridID)[0].p.colModel[i].name;
        $('#'+gridID+'_'+columnName).attr("title", $('#'+gridID)[0].p.colNames[i]);
    }
}


问:
Custom Validator on reactive form for password and confirm password matching getting undefined parameters into Angular 4
I'm trying to implement a custom validator to check if the password and password confirm are equal. The problem is that the validator is getting undefined password and confirmedPassword parameters. How do I make this work. The function works cause if I change the condition to === instead of !== it throws the error correctly when the fields are the same. Does anyone know which is the error here?

signup.component.html

```<code><div class="col-md-7 col-md-offset-1 col-sm-7">
  <div class="block">
    <div class="well">
        <form (onSubmit)="onSubmit()" [formGroup]="signUpForm">
          <div class="form-group">
            <label for="username" class="control-label">Nombre de usuario:</label>
            <input type="text" class="form-control" formControlName="username"  title="Please enter your username" placeholder="username">
            <p class="help-block" *ngIf="signUpForm.get('username').hasError('required') && signUpForm.get('username').touched">El nombre de usuario es obligatorio</p>
            <p class="help-block" *ngIf="signUpForm.get('username').hasError('minlength') && signUpForm.get('username').touched">El nombre de usuario debe tener al menos 6 caracteres</p>
            <p class="help-block" *ngIf="signUpForm.get('username').hasError('maxlength') && signUpForm.get('username').touched">El nombre de usuario debe tener menos de 15 caracteres</p>
          </div>
          <div class="form-group">
            <label for="email" class="control-label">E-mail:</label>
            <input class="form-control" formControlName="email" title="Please enter your email" placeholder="example@gmail.com">
            <p class="help-block" *ngIf="signUpForm.get('email').hasError('required') && signUpForm.get('email').touched">La dirección de email es obligatoria</p>
            <p class="help-block" *ngIf="signUpForm.get('email').hasError('email') && signUpForm.get('email').touched">Debe ingresar una dirección de correo válida</p>
          </div>
          <div class="form-group">
            <label for="password" class="control-label">Contraseña:</label>
            <input type="password" class="form-control" formControlName="password" title="Please enter your password" [(ngModel)]="password">
            <p class="help-block" *ngIf="signUpForm.get('password').hasError('required') && signUpForm.get('password').touched">Debe ingresar una contraseña</p>
          </div>
          <div class="form-group">
            <label for="confirmedPassword" class="control-label">Confirmar Contraseña:</label>
            <input type="password" class="form-control" formControlName="confirmedPassword"  title="Please re-enter your password" [(ngModel)]="confirmedPassword">
            <p class="help-block" *ngIf="signUpForm.get('confirmedPassword').hasError('required') && signUpForm.get('confirmedPassword').touched">La confirmación de contraseña no puede estar vacía</p>
            <p class="help-block" *ngIf="signUpForm.get('confirmedPassword').hasError('passwordMismatch') && signUpForm.get('confirmedPassword').touched">Las contraseñas no coinciden</p>
          </div>
          <button type="submit" class="btn btn-success" [disabled]="!signUpForm.valid">Registrarse</button>
          <a routerLink="/signin" class="btn btn-default" style="">Ya tenes usuario? Logueate</a> {{ creationMessage }}
        </form>

      </div>

  </div>
</div>
</code>```

signup.component.ts

```<code>import { Component, OnInit, ViewChild, Input } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { CustomValidators } from '../../shared/custom-validators';
import { Observable } from 'rxjs/Observable';

@Component({
  selector: 'app-signup',
  templateUrl: './signup.component.html',
  styleUrls: ['./signup.component.sass']
})
export class SignupComponent implements OnInit {

  signUpForm: FormGroup;
  user = {
    username: '',
    email: '',
    password: ''
  };
  submitted = false;
  @Input() password='';
  @Input() confirmedPassword='';

  constructor() { }

  ngOnInit() {

    this.signUpForm = new FormGroup({
      'username': new FormControl(null, [Validators.required, Validators.minLength(6), Validators.maxLength(15)]),
      'email': new FormControl(null, [Validators.required, Validators.email, Validators.minLength(5)]),
      'password': new FormControl(null, [Validators.required]),
      'confirmedPassword': new FormControl(null, [Validators.required, CustomValidators.passwordsMatch(this.password,this.confirmedPassword).bind(this)])
    });
  }

  onSubmit() {
    if (this.signUpForm.valid) {
      console.log(this.signUpForm.value);
    }
  }

}
</code>```

custom-validators.ts

```<code>    import { FormControl } from '@angular/forms';

    export class CustomValidators{

    public static passwordsMatch(password: string, confirmedPassword: string) {

     return (control: FormControl) : { [s: string]: boolean } =>{
       //getting undefined values for both variables
       console.log(password,confirmedPassword);
        //if I change this condition to === it throws the error if the
//  two fields are the same, so this part works
        if (password !== confirmedPassword) {
          return { 'passwordMismatch': true }
        } else {
          //it always gets here no matter what
          return null;
        }
    }
      }

    }
</code>```

答:
The issue is that you are mixing the reactive forms module with the input approach. This is causing you to get undefined when passing the values to the validator.

You don't need to bind to the ng-model when using the reactive forms. Instead, you should access the value of the fields from the Instance of FormGroup.

I do something like this in an app to validate the passwords match.

```<code>public Credentials: FormGroup;

ngOnInit() {
    this.Credentials = new FormGroup({});
    this.Credentials.addControl('Password', new FormControl('', [Validators.required]));
    this.Credentials.addControl('Confirmation', new FormControl(
        '', [Validators.compose(
            [Validators.required, this.validateAreEqual.bind(this)]
        )]
    ));
}

private validateAreEqual(fieldControl: FormControl) {
    return fieldControl.value === this.Credentials.get("Password").value ? null : {
        NotEqual: true
    };
}
</code>```

Note that the validator expects a FormControl field as a parameter and it compares the value of the field to that of the value of the Password field of the Credentials FormGroup.

In the HTML make sure to remove the ng-model.

```<code><input type="password" class="form-control" formControlName="confirmedPassword"  title="Please re-enter your password" >
<!-- AND -->
<input type="password" class="form-control" formControlName="password" title="Please enter your password">
</code>```

Hope this helps!

Body:
I'm trying to implement a custom validator to check if the password and password confirm are equal. The problem is that the validator is getting undefined password and confirmedPassword parameters. How do I make this work. The function works cause if I change the condition to === instead of !== it throws the error correctly when the fields are the same. Does anyone know which is the error here?

signup.component.html

        <form (onSubmit)="onSubmit()" [formGroup]="signUpForm">

            Nombre de usuario:
            <input type="text" class="form-control" formControlName="username"  title="Please enter your username" placeholder="username">

El nombre de usuario es obligatorio

El nombre de usuario debe tener al menos 6 caracteres

El nombre de usuario debe tener menos de 15 caracteres

            E-mail:
            <input class="form-control" formControlName="email" title="Please enter your email" placeholder="example@gmail.com">

La dirección de email es obligatoria

Debe ingresar una dirección de correo válida

            Contraseña:
            <input type="password" class="form-control" formControlName="password" title="Please enter your password" [(ngModel)]="password">

Debe ingresar una contraseña

            Confirmar Contraseña:
            <input type="password" class="form-control" formControlName="confirmedPassword"  title="Please re-enter your password" [(ngModel)]="confirmedPassword">

La confirmación de contraseña no puede estar vacía

Las contraseñas no coinciden

          <button type="submit" class="btn btn-success" [disabled]="!signUpForm.valid">Registrarse</button>
          Ya tenes usuario? Logueate {{ creationMessage }}
        </form>

signup.component.ts

import { Component, OnInit, ViewChild, Input } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { CustomValidators } from '../../shared/custom-validators';
import { Observable } from 'rxjs/Observable';

@Component({
  selector: 'app-signup',
  templateUrl: './signup.component.html',
  styleUrls: ['./signup.component.sass']
})
export class SignupComponent implements OnInit {

  signUpForm: FormGroup;
  user = {
    username: '',
    email: '',
    password: ''
  };
  submitted = false;
  @Input() password='';
  @Input() confirmedPassword='';

  constructor() { }

  ngOnInit() {

    this.signUpForm = new FormGroup({
      'username': new FormControl(null, [Validators.required, Validators.minLength(6), Validators.maxLength(15)]),
      'email': new FormControl(null, [Validators.required, Validators.email, Validators.minLength(5)]),
      'password': new FormControl(null, [Validators.required]),
      'confirmedPassword': new FormControl(null, [Validators.required, CustomValidators.passwordsMatch(this.password,this.confirmedPassword).bind(this)])
    });
  }

  onSubmit() {
    if (this.signUpForm.valid) {
      console.log(this.signUpForm.value);
    }
  }

}

custom-validators.ts

    import { FormControl } from '@angular/forms';

    export class CustomValidators{

    public static passwordsMatch(password: string, confirmedPassword: string) {

     return (control: FormControl) : { [s: string]: boolean } =>{
       //getting undefined values for both variables
       console.log(password,confirmedPassword);
        //if I change this condition to === it throws the error if the
//  two fields are the same, so this part works
        if (password !== confirmedPassword) {
          return { 'passwordMismatch': true }
        } else {
          //it always gets here no matter what
          return null;
        }
    }
      }

    }

Body:
The issue is that you are mixing the reactive forms module with the input approach. This is causing you to get undefined when passing the values to the validator.

You don't need to bind to the ng-model when using the reactive forms. Instead, you should access the value of the fields from the Instance of FormGroup.

I do something like this in an app to validate the passwords match.

public Credentials: FormGroup;

ngOnInit() {
    this.Credentials = new FormGroup({});
    this.Credentials.addControl('Password', new FormControl('', [Validators.required]));
    this.Credentials.addControl('Confirmation', new FormControl(
        '', [Validators.compose(
            [Validators.required, this.validateAreEqual.bind(this)]
        )]
    ));
}

private validateAreEqual(fieldControl: FormControl) {
    return fieldControl.value === this.Credentials.get("Password").value ? null : {
        NotEqual: true
    };
}

Note that the validator expects a FormControl field as a parameter and it compares the value of the field to that of the value of the Password field of the Credentials FormGroup.

In the HTML make sure to remove the ng-model.

<input type="password" class="form-control" formControlName="confirmedPassword"  title="Please re-enter your password" >
<!-- AND -->
<input type="password" class="form-control" formControlName="password" title="Please enter your password">

Hope this helps!


问:
How to increase the size of deconv2d filters for a fixed data size?
I am trying to adjust this DCGAN code to be able to work with 2x80 data samples.

All generator layers are tf.nn.deconv2d other than h0, which is ReLu. Generator filter sizes per level are currently:

```<code>Generator: h0: s_h16 x s_w16: 1  x  5
Generator: h1: s_h8 x s_w8: 1  x  10
Generator: h2: s_h4 x s_w4: 1  x  20
Generator: h3: s_h2 x s_w2: 1  x  40
Generator: h4: s_h x s_w: 2  x  80
</code>```

Because of the nature of my data I would like them to be initially generated as 2 x ..., i.e. for filters to be 2 x 5, 2 x 10, 2 x 20, 2 x 40, and 2 x 80. However when I just manually enter s_h16 = 2 * s_h16 and so on up to s_h2 = 2 * s_h2, I run into the following error:

```<code>ValueError: Shapes (64, 1, 40, 64) and (64, 2, 40, 64) are not compatible
</code>```

So I know that the error happens at the level h3, but I can't quite track it down (64 here is the batch size). Any ideas how this can be fixed?

Edit: the edited DCGANs code is in this repository, after the DCGAN-tensorflow is set-up as in the instructions you'd have to place Data_npy folder into DCGAN-tensorflow/data folder.

Then running python main.py --dataset Data_npy --input_height=2 --output_height=2 --train would provide you with the error I get.

The full error traceback looks as follows:

```<code>Traceback (most recent call last):
  File "/home/marija/.local/lib/python3.5/site-packages/tensorflow/python/framework/tensor_shape.py", line 560, in merge_with
    new_dims.append(dim.merge_with(other[i]))
  File "/home/marija/.local/lib/python3.5/site-packages/tensorflow/python/framework/tensor_shape.py", line 135, in merge_with
    self.assert_is_compatible_with(other)
  File "/home/marija/.local/lib/python3.5/site-packages/tensorflow/python/framework/tensor_shape.py", line 108, in assert_is_compatible_with
    % (self, other))
ValueError: Dimensions 1 and 2 are not compatible

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "main.py", line 97, in <module>
    tf.app.run()
  File "/home/marija/.local/lib/python3.5/site-packages/tensorflow/python/platform/app.py", line 48, in run
    _sys.exit(main(_sys.argv[:1] + flags_passthrough))
  File "main.py", line 80, in main
    dcgan.train(FLAGS)
  File "/home/marija/DCGAN-tensorflow/model.py", line 180, in train
    .minimize(self.g_loss, var_list=self.g_vars)
  File "/home/marija/.local/lib/python3.5/site-packages/tensorflow/python/training/optimizer.py", line 315, in minimize
    grad_loss=grad_loss)
  File "/home/marija/.local/lib/python3.5/site-packages/tensorflow/python/training/optimizer.py", line 386, in compute_gradients
    colocate_gradients_with_ops=colocate_gradients_with_ops)
  File "/home/marija/.local/lib/python3.5/site-packages/tensorflow/python/ops/gradients_impl.py", line 580, in gradients
    in_grad.set_shape(t_in.get_shape())
  File "/home/marija/.local/lib/python3.5/site-packages/tensorflow/python/framework/ops.py", line 413, in set_shape
    self._shape = self._shape.merge_with(shape)
  File "/home/marija/.local/lib/python3.5/site-packages/tensorflow/python/framework/tensor_shape.py", line 564, in merge_with
    (self, other))
ValueError: Shapes (64, 1, 40, 64) and (64, 2, 40, 64) are not compatible
</code>```

答:
In your ops.py file

your problem come from the striding size in your deconv filter, modify the header for conv2d and deconv2d to:

```<code>def conv2d(input_, output_dim,
       k_h=5, k_w=5, d_h=1, d_w=2, stddev=0.02,
       name="conv2d"):

def deconv2d(input_, output_shape,
       k_h=5, k_w=5, d_h=1, d_w=2, stddev=0.02,
       name="deconv2d", with_w=False):
</code>```

Like this it started to train for me. I didn't check the output though.

The problem is considering the shape of your input, strinding on height by 2 (original value for d_h) will result by a (64, 1, 40, 64) shape during back propagation. (Because you only have 2 values)

Also you might think to change k_h=5 to k_h=2 as taking 5 element on height when you have only 2 doesn't make so much sense.

Body:
I am trying to adjust this DCGAN code to be able to work with 2x80 data samples.

All generator layers are tf.nn.deconv2d other than h0, which is ReLu. Generator filter sizes per level are currently:

Generator: h0: s_h16 x s_w16: 1  x  5
Generator: h1: s_h8 x s_w8: 1  x  10
Generator: h2: s_h4 x s_w4: 1  x  20
Generator: h3: s_h2 x s_w2: 1  x  40
Generator: h4: s_h x s_w: 2  x  80

Because of the nature of my data I would like them to be initially generated as 2 x ..., i.e. for filters to be 2 x 5, 2 x 10, 2 x 20, 2 x 40, and 2 x 80. However when I just manually enter s_h16 = 2 * s_h16 and so on up to s_h2 = 2 * s_h2, I run into the following error:

ValueError: Shapes (64, 1, 40, 64) and (64, 2, 40, 64) are not compatible

So I know that the error happens at the level h3, but I can't quite track it down (64 here is the batch size). Any ideas how this can be fixed?

Edit: the edited DCGANs code is in this repository, after the DCGAN-tensorflow is set-up as in the instructions you'd have to place Data_npy folder into DCGAN-tensorflow/data folder.

Then running python main.py --dataset Data_npy --input_height=2 --output_height=2 --train would provide you with the error I get.

The full error traceback looks as follows:

Traceback (most recent call last):
  File "/home/marija/.local/lib/python3.5/site-packages/tensorflow/python/framework/tensor_shape.py", line 560, in merge_with
    new_dims.append(dim.merge_with(other[i]))
  File "/home/marija/.local/lib/python3.5/site-packages/tensorflow/python/framework/tensor_shape.py", line 135, in merge_with
    self.assert_is_compatible_with(other)
  File "/home/marija/.local/lib/python3.5/site-packages/tensorflow/python/framework/tensor_shape.py", line 108, in assert_is_compatible_with
    % (self, other))
ValueError: Dimensions 1 and 2 are not compatible

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "main.py", line 97, in <module>
    tf.app.run()
  File "/home/marija/.local/lib/python3.5/site-packages/tensorflow/python/platform/app.py", line 48, in run
    _sys.exit(main(_sys.argv[:1] + flags_passthrough))
  File "main.py", line 80, in main
    dcgan.train(FLAGS)
  File "/home/marija/DCGAN-tensorflow/model.py", line 180, in train
    .minimize(self.g_loss, var_list=self.g_vars)
  File "/home/marija/.local/lib/python3.5/site-packages/tensorflow/python/training/optimizer.py", line 315, in minimize
    grad_loss=grad_loss)
  File "/home/marija/.local/lib/python3.5/site-packages/tensorflow/python/training/optimizer.py", line 386, in compute_gradients
    colocate_gradients_with_ops=colocate_gradients_with_ops)
  File "/home/marija/.local/lib/python3.5/site-packages/tensorflow/python/ops/gradients_impl.py", line 580, in gradients
    in_grad.set_shape(t_in.get_shape())
  File "/home/marija/.local/lib/python3.5/site-packages/tensorflow/python/framework/ops.py", line 413, in set_shape
    self._shape = self._shape.merge_with(shape)
  File "/home/marija/.local/lib/python3.5/site-packages/tensorflow/python/framework/tensor_shape.py", line 564, in merge_with
    (self, other))
ValueError: Shapes (64, 1, 40, 64) and (64, 2, 40, 64) are not compatible

Body:
In your ops.py file

your problem come from the striding size in your deconv filter, modify the header for conv2d and deconv2d to:

def conv2d(input_, output_dim,
       k_h=5, k_w=5, d_h=1, d_w=2, stddev=0.02,
       name="conv2d"):

def deconv2d(input_, output_shape,
       k_h=5, k_w=5, d_h=1, d_w=2, stddev=0.02,
       name="deconv2d", with_w=False):

Like this it started to train for me. I didn't check the output though.

The problem is considering the shape of your input, strinding on height by 2 (original value for d_h) will result by a (64, 1, 40, 64) shape during back propagation. (Because you only have 2 values)

Also you might think to change k_h=5 to k_h=2 as taking 5 element on height when you have only 2 doesn't make so much sense.


问:
how to configure cypal plugins into eclipse
I am trying to configure the eclipse with the cypal studio  to run GWT (Google Web Toolkit) into java application. now i am trying to find libraries for cypal to configure into eclipse but i am not able to find the proper solution for installing plugins in eclipse.</p>

答:
Using collections framework in Java, a developer has to use loops and make repeated checks. Another concern is efficiency; as multi-core processors are available at ease, a Java developer has to write parallel code processing that can be pretty error-prone.

To resolve such issues, Java 8 introduced the concept of stream that lets the developer to process data declaratively and leverage multicore architecture without the need to write any specific code for it. Using stream, you can process data in a declarative way.

In Java 8, Collection interface has two methods to generate a Stream −

stream() − Returns a sequential stream considering collection as its source.

parallelStream() − Returns a parallel Stream considering collection as its source.

Example:

```<code>List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
List<String> filtered = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList());
</code>```

The filter() method is used to eliminate elements based on a criteria. Like this there are so many methods in Stream.

You can also check this link:

https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html

Body:
Using collections framework in Java, a developer has to use loops and make repeated checks. Another concern is efficiency; as multi-core processors are available at ease, a Java developer has to write parallel code processing that can be pretty error-prone.

To resolve such issues, Java 8 introduced the concept of stream that lets the developer to process data declaratively and leverage multicore architecture without the need to write any specific code for it. Using stream, you can process data in a declarative way.

In Java 8, Collection interface has two methods to generate a Stream −

stream() − Returns a sequential stream considering collection as its source.

parallelStream() − Returns a parallel Stream considering collection as its source.

Example:

List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
List<String> filtered = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList());

The filter() method is used to eliminate elements based on a criteria. Like this there are so many methods in Stream.

You can also check this link:

https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html


问:
"Chrome Not Reachable" when invoking Selenium scripts from Eclipse IDE
In our Selenium remote webdriver set up, we wrote our Selenium Java test scripts for to run in Chrome Browser. We are using Chrome Driver 2.28. Selenium Standalone Server 2.53. Selenium API 2.53. When we run our scripts from with in Eclipse IDE, 3 out of 5 times, the Chrome browser does not get invoked or take a long time to start by the script. When it fails to invoke the browser, it fails with this exception ....

```<code>> Caused by: org.openqa.selenium.WebDriverException: chrome not
> reachable   (Driver info: chromedriver=2.28.455520
> (cc17746adff54984afff480136733114c6b3704b),platform=Windows NT
> 6.1.7601 SP1 x86_64) (WARNING: The server did not provide any stacktrace information) Command duration or timeout: 62.50 seconds
> Build info: version: '2.53.0', revision: '35ae25b', time: '2016-03-15
> 17:00:58' System info: host: '<XXXXXXX>', ip: '<XXXXXXXXXX>',
> os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1',
> java.version: '1.8.0_121' Driver info:
> org.openqa.selenium.chrome.ChromeDriver
>         at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
>         at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
>         at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
>         at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
>         at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:206)
>         at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:158)
>         at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:678)
>         at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:249)
>         at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:131)
>         at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:144)
>         at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:170)
>         at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:138)
>         ... 13 more 11:58:11.356 WARN - Exception: chrome not reachable
</code>```

(Driver info: chromedriver=2.28.455520
  (cc17746adff54984afff480136733114c6b3704b),platform=Windows NT
  6.1.7601 SP1 x86_64) (WARNING: The server did not provide any stacktrace information) Command duration or timeout: 62.50 seconds
  Build info: version: '2.53.0', revision: '35ae25b', time: '2016-03-15
  17:00:58' System info: host: '', ip: '',
  os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1',
  java.version: '1.8.0_121' Driver info:
  org.openqa.selenium.chrome.ChromeDriver
          at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
          at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
          at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
          at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
          at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:206)
          at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:158)
          at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:678)
          at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:249)
          at org.openqa.selenium.remote.RemoteWebDriver.(RemoteWebDriver.java:131)
          at org.openqa.selenium.remote.RemoteWebDriver.(RemoteWebDriver.java:144)
          at org.openqa.selenium.chrome.ChromeDriver.(ChromeDriver.java:170)
          at org.openqa.selenium.chrome.ChromeDriver.(ChromeDriver.java:138)
          ... 13 more 11:58:11.356 WARN - Exception: chrome not reachable

The temporary but painful solution is to go to Windows TaskManager and kill the half a dozen or so, Chrome.exe processes one after another. It is observed that even when we run our script or manually running the application, the Chrome browser processes that get invoked are more like 6 or 7, not less.

Is it a Chrome Browser or Selenium issue. ?
Individually, I used NOT to have this problem unlike my team member who is having this problem since a year. As soon as I upgraded Chrome Driver to 2.28 from 2.25, I started having this problem.

答: If you are running the script as root user, it will throw the error "chrome not reachable". Try running script as normal user, it will work fine.</p>

Body:
In our Selenium remote webdriver set up, we wrote our Selenium Java test scripts for to run in Chrome Browser. We are using Chrome Driver 2.28. Selenium Standalone Server 2.53. Selenium API 2.53. When we run our scripts from with in Eclipse IDE, 3 out of 5 times, the Chrome browser does not get invoked or take a long time to start by the script. When it fails to invoke the browser, it fails with this exception ....

> Caused by: org.openqa.selenium.WebDriverException: chrome not
> reachable   (Driver info: chromedriver=2.28.455520
> (cc17746adff54984afff480136733114c6b3704b),platform=Windows NT
> 6.1.7601 SP1 x86_64) (WARNING: The server did not provide any stacktrace information) Command duration or timeout: 62.50 seconds
> Build info: version: '2.53.0', revision: '35ae25b', time: '2016-03-15
> 17:00:58' System info: host: '<XXXXXXX>', ip: '<XXXXXXXXXX>',
> os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1',
> java.version: '1.8.0_121' Driver info:
> org.openqa.selenium.chrome.ChromeDriver
>         at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
>         at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
>         at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
>         at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
>         at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:206)
>         at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:158)
>         at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:678)
>         at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:249)
>         at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:131)
>         at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:144)
>         at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:170)
>         at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:138)
>         ... 13 more 11:58:11.356 WARN - Exception: chrome not reachable

(Driver info: chromedriver=2.28.455520
  (cc17746adff54984afff480136733114c6b3704b),platform=Windows NT
  6.1.7601 SP1 x86_64) (WARNING: The server did not provide any stacktrace information) Command duration or timeout: 62.50 seconds
  Build info: version: '2.53.0', revision: '35ae25b', time: '2016-03-15
  17:00:58' System info: host: '', ip: '',
  os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1',
  java.version: '1.8.0_121' Driver info:
  org.openqa.selenium.chrome.ChromeDriver
          at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
          at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
          at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
          at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
          at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:206)
          at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:158)
          at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:678)
          at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:249)
          at org.openqa.selenium.remote.RemoteWebDriver.(RemoteWebDriver.java:131)
          at org.openqa.selenium.remote.RemoteWebDriver.(RemoteWebDriver.java:144)
          at org.openqa.selenium.chrome.ChromeDriver.(ChromeDriver.java:170)
          at org.openqa.selenium.chrome.ChromeDriver.(ChromeDriver.java:138)
          ... 13 more 11:58:11.356 WARN - Exception: chrome not reachable

The temporary but painful solution is to go to Windows TaskManager and kill the half a dozen or so, Chrome.exe processes one after another. It is observed that even when we run our script or manually running the application, the Chrome browser processes that get invoked are more like 6 or 7, not less.

Is it a Chrome Browser or Selenium issue. ?
Individually, I used NOT to have this problem unlike my team member who is having this problem since a year. As soon as I upgraded Chrome Driver to 2.28 from 2.25, I started having this problem.


问:
Among Kubernetes, OpenShift, Docker Swarm and Docker DataCenter deployment tools which all are having automatic rollback?
Among Kubernetes, OpenShift, Docker Swarm and Docker DataCenter deployment tools which all are having automatic rollback in case of any failure happens?</p>

答:
All of them have a sort of rollback mechanism built-in with commands available for you to control. However, these are not fully automated and you might have to do it manually. For Kubernetes, here is the related github issue and another issue for Swarm. Docker DataCenter use Swarm already.

Rollback documentations I was able to find:

Kubernetes: Rolling Back a Deployment

Swarm: Roll back to the previous version of a service (features --update-delay)

OpenShift: Rolling Back a Deployment


答:
When you're creating the validator, you're passing in the values of password and confirmedPassword, but changes in those values will not be reflected in the validator.

The two options I see are:

define your validator on the FormGroup, and look up the values from the two controls you want to compare; or

since you're binding to this already, use this.password and this.confirmedPassword in your validator.

Title: Custom Validator on reactive form for password and confirm password matching getting undefined parameters into Angular 4


问:
UITextfield keyboard with only alphabet, no numbers, no caps, no spacebar?
I want the keyboard for the UITextfield to only have a-z, no numbers, no special characters (!@$!@$@!#), and no caps. Basicly I am going for a keyboard with only the alphabet.

I was able to disable the space already. Anyone know how to disable numbers, special characters, and caps? A solution for any of these would be great.

Is the best solution to do the below for all the characters but I dont want?

```<code>func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

    if (string == " ") {
        return false
    }

    if (string == "1") {
        return false
    }

    return true
}
</code>```

答:
```<code>class ViewController: UIViewController,UITextFieldDelegate {

     @IBOutlet var phoneTextField:UITextField!

    override func viewDidLoad() {
            super.viewDidLoad()
    self.phoneTextField.delegate = self
    }

     func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
           {
                let textString = (textField.text! as NSString).replacingCharacters(in: range, with: string)

                if textField == self.phoneTextField  && string.characters.count > 0 {
                    let LettersOnly = NSCharacterSet.Letters
                    let strValid = LettersOnly.contains(UnicodeScalar.init(string)!)
                    return strValid && textString.characters.count <= 10
                }
                return true
            }
    }
</code>```

Try this code

In above code is only allow 10 char in text field

Body:
I want the keyboard for the UITextfield to only have a-z, no numbers, no special characters (!@$!@$@!#), and no caps. Basicly I am going for a keyboard with only the alphabet.

I was able to disable the space already. Anyone know how to disable numbers, special characters, and caps? A solution for any of these would be great.

Is the best solution to do the below for all the characters but I dont want?

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

    if (string == " ") {
        return false
    }

    if (string == "1") {
        return false
    }

    return true
}

Body:
class ViewController: UIViewController,UITextFieldDelegate {

     @IBOutlet var phoneTextField:UITextField!

    override func viewDidLoad() {
            super.viewDidLoad()
    self.phoneTextField.delegate = self
    }

     func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
           {
                let textString = (textField.text! as NSString).replacingCharacters(in: range, with: string)

                if textField == self.phoneTextField  && string.characters.count > 0 {
                    let LettersOnly = NSCharacterSet.Letters
                    let strValid = LettersOnly.contains(UnicodeScalar.init(string)!)
                    return strValid && textString.characters.count <= 10
                }
                return true
            }
    }

Try this code

In above code is only allow 10 char in text field


问:
PHP date range problems
Today I am having a rather strange problem with my date range.

```<code>$oBeginDate = newDateTime('last wednesday');
$oEndDate = newDateTime('next tuesday');
echo $oBeginDate->format('d/m/Y') . ' to ' . $oEndDate->format('d/m/Y');
</code>```

This should usually display 14/12/2010 to 21/12/2010, but today, 14/12/2010, it is displaying 08/12/2010 to 21/12/2010.

Any suggestions as to how I can fix this problem?

I would like the date to update from 08/12/2010 to 14/12/2010 automatically to keep the one week range.

答: Last Wednesday was on 8th. Not sure why would you expect 14th which is Tuesday.</p>

Title: PHP date range problems

Body:
Today I am having a rather strange problem with my date range.

$oBeginDate = newDateTime('last wednesday');
$oEndDate = newDateTime('next tuesday');
echo $oBeginDate->format('d/m/Y') . ' to ' . $oEndDate->format('d/m/Y');

This should usually display 14/12/2010 to 21/12/2010, but today, 14/12/2010, it is displaying 08/12/2010 to 21/12/2010.

Any suggestions as to how I can fix this problem?

I would like the date to update from 08/12/2010 to 14/12/2010 automatically to keep the one week range.


答:
import {AbstractControl, FormBuilder, FormGroup, Validators} from

set your password input into the group and no need to use "ngModel".

```<code><div class="form-group row" formGroupName="passwords">
  <div class="form-group">
     <label for="password" class="control-label">Contraseña:</label>
     <input type="password" class="form-control" formControlName="password" title="Please enter your password">
     <p class="help-block" *ngIf="signUpForm.get('password').hasError('required') && signUpForm.get('password').touched">Debe ingresar una contraseña</p>
  </div>
  <div class="form-group">
     <label for="confirmedPassword" class="control-label">Confirmar Contraseña:</label>
     <input type="password" class="form-control" formControlName="confirmedPassword"  title="Please re-enter your password">
     <p class="help-block" *ngIf="signUpForm.get('confirmedPassword').hasError('required') && signUpForm.get('confirmedPassword').touched">Password must be required</p>
     <p class="help-block" *ngIf="signUpForm.get('confirmedPassword').hasError('passwordMismatch') && signUpForm.get('confirmedPassword').touched">password does not match</p>
  </div>
</code>```

```<code>     buildForm(): void {
            this.userForm = this.formBuilder.group({
                passwords: this.formBuilder.group({
                    password: ['', [Validators.required]],
                    confirm_password: ['', [Validators.required]],
                }, {validator: this.passwordConfirming}),

            });
        }
</code>```

add this custom function for validate password and confirm password

```<code>  passwordConfirming(c: AbstractControl): { invalid: boolean } {
    if (c.get('password').value !== c.get('confirm_password').value) {
        return {invalid: true};
    }
}
</code>```

Display error when password does not match

```<code><div style='color:#ff7355' *ngIf="userForm.get(['passwords','password']).value != userForm.get(['passwords','confirm_password']).value && userForm.get(['passwords','confirm_password']).value != null">
  Password does not match</div>
</code>```

Body:
import {AbstractControl, FormBuilder, FormGroup, Validators} from

set your password input into the group and no need to use "ngModel".

<div class="form-group row" formGroupName="passwords">
  <div class="form-group">
     <label for="password" class="control-label">Contraseña:</label>
     <input type="password" class="form-control" formControlName="password" title="Please enter your password">
     <p class="help-block" *ngIf="signUpForm.get('password').hasError('required') && signUpForm.get('password').touched">Debe ingresar una contraseña</p>
  </div>
  <div class="form-group">
     <label for="confirmedPassword" class="control-label">Confirmar Contraseña:</label>
     <input type="password" class="form-control" formControlName="confirmedPassword"  title="Please re-enter your password">
     <p class="help-block" *ngIf="signUpForm.get('confirmedPassword').hasError('required') && signUpForm.get('confirmedPassword').touched">Password must be required</p>
     <p class="help-block" *ngIf="signUpForm.get('confirmedPassword').hasError('passwordMismatch') && signUpForm.get('confirmedPassword').touched">password does not match</p>
  </div>

     buildForm(): void {
            this.userForm = this.formBuilder.group({
                passwords: this.formBuilder.group({
                    password: ['', [Validators.required]],
                    confirm_password: ['', [Validators.required]],
                }, {validator: this.passwordConfirming}),

            });
        }

add this custom function for validate password and confirm password

  passwordConfirming(c: AbstractControl): { invalid: boolean } {
    if (c.get('password').value !== c.get('confirm_password').value) {
        return {invalid: true};
    }
}

Display error when password does not match

<div style='color:#ff7355' *ngIf="userForm.get(['passwords','password']).value != userForm.get(['passwords','confirm_password']).value && userForm.get(['passwords','confirm_password']).value != null">
  Password does not match</div>

ContentLicense: CC BY-SA 4.0