问:
RecyclerView Can't Scroll While Refreshing From API (OkHttp), Crashes With IndexOutOfBoundsException
My RecyclerView crashes with an IndexOutOfBoundsException while scrolling after attempting to refresh the data.

Desired functionality: After API request has successfully populated RecyclerView once, I'd like to refresh the RecyclerView and be able to scroll up and down while it refreshes.

Current functionality: If I don't scroll while refreshing the data, the app doesn't crash. If I scroll after making a refresh request, it crashes with an IndexOutOfBoundsException.

I've spent several weeks trying to troubleshoot this problem without posting a question, and I believe I've tried enough potential solutions to justify asking Stack Overflow for guidance. There are countless questions on here with the same subject, but unfortunately none of them have solved my problem. Thank you in advance for your consideration.

Here are some solutions other people have suggested:

To use adapter.notifyDataSetChanged(), but I understand this to
be considered a 'last resort' in the Android documentation

To call list.clear before adapter.notifyDataSetChanged()

To get the position of all current items in the data set to an Integer called 'position' with adapter.getItemCount(), and then pass that to adapter.notifyItemRangeChanged(position)

To set adapter.setHasStableIds(true)

To call mRecyclerView.getRecycledViewPool().clear() and mAdapter.notifyDataSetChanged();

Apparently if the RecyclerView is inside a LinearLayout, 'notify' methods don't work (this might pertain to an old bug in Android which may be fixed now, but I'm not sure.)

All of these suggestions result in a 'Fatal Exception'.

My app uses five files:

JobsAdapter (Adapter)

JobsListItem (Getters and Setters)

JobsOut (Fragment)

jobs_recyclerview

jobs_listitem

I've only included code for the Adapter and Fragment, because I'm confident that the layout files and Getters and Setters are well formed.

Fragment:

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

String jobId;
String jobTitle;
String jobNumber;
String jobStartTime;
String dispatchType;

@BindView(R.id.jobsOutRecyclerView) RecyclerView jobsOutRecyclerView;
@BindView(R.id.fab) FloatingActionButton refreshFab;

private List<JobsListItem> dispatch;
private RecyclerView.Adapter mJobsOutAdapter;
public RecyclerView.LayoutManager dispatchLayoutManager;

OkHttpClient client = new OkHttpClient();
Handler handler = new Handler();

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.recycler_test, container, false);
    ButterKnife.bind(this, rootView);

    dispatch = new ArrayList<>();
    jobsOutRecyclerView.setHasFixedSize(true);
    dispatchLayoutManager = new LinearLayoutManager(getContext());
    jobsOutRecyclerView.setLayoutManager(dispatchLayoutManager);

    downloadDispatch();

    refreshFab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            downloadDispatch();

            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    dispatch.clear();
                }
            });
        }
    });

    return rootView;
}

@Override
public void onDestroy() {
    super.onDestroy();
    handler.removeCallbacksAndMessages(this);
}

private void downloadDispatch() {
    final okhttp3.Request request = new okhttp3.Request.Builder()
            .url("url")
            .header("X_SUBDOMAIN", "SUBDOMAIN")
            .header("X-AUTH-TOKEN", "API_KEY")
            .build();

    Call call = client.newCall(request);
    call.enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {

        }

        @Override
        public void onResponse(Call call, okhttp3.Response response) throws IOException {

            try {
                String jsonData = response.body().string();

                JSONObject getRootObject = new JSONObject(jsonData);
                JSONObject metaObject = getRootObject.getJSONObject("meta");
                final String row_count = metaObject.getString("total_row_count");
                {

                    if (row_count.equals("0")) {
                        // do something for no jobs
                    } else {
                        JSONObject getArray = new JSONObject(jsonData);
                        JSONArray opportunitiesArray = getArray.getJSONArray("opportunities");

                        for (int i = 0; i < opportunitiesArray.length(); i++) {
                            JSONObject opportunity = opportunitiesArray.getJSONObject(i);

                            jobId = opportunity.getString("id");
                            jobTitle = opportunity.getString("subject");
                            jobNumber = opportunity.getString("number");
                            jobStartTime = opportunity.getString("starts_at");
                            dispatchType = opportunity.getString("customer_collecting");

                            // Take Strings from response and send them to JobsListItem
                            final JobsListItem item = new JobsListItem(jobId, jobTitle, jobNumber, jobStartTime, dispatchType);

                            // If the adapter hasn't been created, do this
                            if (mJobsOutAdapter == null) {
                                new Handler(Looper.getMainLooper()).post(new Runnable() {
                                    @Override
                                    public void run() {
                                        mJobsOutAdapter = new JobsAdapter(dispatch, getContext());
                                        jobsOutRecyclerView.setAdapter(mJobsOutAdapter);
                                        dispatch.add(item);
                                    }
                                });
                            }
                            // If the adapter has been created, just do this
                            else if (mJobsOutAdapter != null) {
                                new Handler(Looper.getMainLooper()).post(new Runnable() {
                                    @Override
                                    public void run() {
                                        dispatch.add(item);
                                        mJobsOutAdapter.notifyDataSetChanged();
                                    }
                                });
                            }
                        }
                    }
                }
            } catch (IOException e) {
                Log.e("TAG", "IO exception caught: ", e);
            } catch (JSONException e) {
                Log.e("TAG", "TAG exception caught: ", e);
            }
        }
    });
}
</code>```

Adapter:

```<code>public class JobsAdapter extends RecyclerView.Adapter<JobsAdapter.ViewHolder> {

private List<JobsListItem> mJobsListItem;
private Context context;

public JobsAdapter(List<JobsListItem> mJobsListItem, Context context) {
    this.mJobsListItem = mJobsListItem;
    this.context = context;
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.jobs_listitem, parent, false);

    return new ViewHolder(view);
}

@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
    final JobsListItem mJobsListItemViewHolder = this.mJobsListItem.get(position);

    // holders go here and do things with text and what-not
}

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

public class ViewHolder extends RecyclerView.ViewHolder {

    // BindView's with ButterKnife go here and all that jazz

    public ViewHolder(View itemView) {
        super(itemView);
        ButterKnife.bind(this, itemView);
    }
}
</code>```

Logcat from crash:

```<code>26404-26404 E/AndroidRuntime: FATAL EXCEPTION: main
                          Process: uk.co.plasmacat.techmate, PID: 26404
                          java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid item position 4(offset:4).state:16
                              at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5504)
                              at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5440)
                              at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5436)
                              at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2224)
                              at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1551)
                              at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1511)
                              at android.support.v7.widget.LinearLayoutManager.scrollBy(LinearLayoutManager.java:1325)
                              at android.support.v7.widget.LinearLayoutManager.scrollVerticallyBy(LinearLayoutManager.java:1061)
                              at android.support.v7.widget.RecyclerView.scrollByInternal(RecyclerView.java:1695)
                              at android.support.v7.widget.RecyclerView.onTouchEvent(RecyclerView.java:2883)
                              at android.view.View.dispatchTouchEvent(View.java:10063)
                              at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2630)
                              at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2307)
                              at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2636)
                              at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2321)
                              at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2636)
                              at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2321)
                              at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2636)
                              at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2321)
                              at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2636)
                              at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2321)
                              at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2636)
                              at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2321)
                              at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2636)
                              at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2321)
                              at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2636)
                              at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2321)
                              at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2636)
                              at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2321)
                              at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2636)
                              at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2321)
                              at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2636)
                              at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2321)
                              at com.android.internal.policy.DecorView.superDispatchTouchEvent(DecorView.java:413)
                              at com.android.internal.policy.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1819)
                              at android.app.Activity.dispatchTouchEvent(Activity.java:3127)
                              at android.support.v7.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:71)
                              at android.support.v7.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:71)
                              at com.android.internal.policy.DecorView.dispatchTouchEvent(DecorView.java:375)
                              at android.view.View.dispatchPointerEvent(View.java:10283)
                                  at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:4522)
                              at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:4353)
                              at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3893)
                              at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3946)
                              at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3912)
                              at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:4039)
                              at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3920)
                              at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:4096)
                              at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3893)
                              at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3946)
                              at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3912)
                              at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3920)
                              at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3893)
                              at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:6341)
                              at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:6315)
                              at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:6265)
                              at

android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:6444)
                                  at android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:185)
                                  at android.view.InputEventReceiver.nativeConsumeBatchedInputEvents(Native Method)
                                  at android.view.InputEventReceiver.consumeBatchedInputEvents(InputEventReceiver.java:176)
                                  at android.view.ViewRootImpl.doConsumeBatchedInput(ViewRootImpl.java:6415)
                                  at android.view.ViewRootImpl$ConsumeBatchedInputRunnable.run(ViewRootImpl.java:6467)
                                  at android.view.Choreographer$CallbackRecord.run(Choreographer.java:874)
                                  at android.view.Choreographer.doCallbacks(Choreographer.java:686)
                                  at android.view.Choreographer.doFrame(Choreographer.java:615)
                                  at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:860)
                                  at android.os.Handler.handleCallback(Handler.java:751)
                                  at android.os.Handler.dispatchMessage(Handler.java:95)
                                  at android.os.Looper.loop(Looper.java:154)
                                  at android.app.ActivityThread.main(ActivityThread.java:6290)
                                  at java.lang.reflect.Method.invoke(Native Method)
                                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
</code>```

If you have the time, I would thoroughly appreciate your help.

Thank you!

答:
What you’re trying to do is fairly common, your index out of bounds happens when the recycler view needs to ask its adapter for data (because it has scrolled) and the position it needs doesn’t exist in the Adatper. E.g.: the adapter tries to grab item number “N” and the data contains N-1 (or less).

This is most of the times due to a number of factors:

Threading. This should all be handled (for the most part) on the UI Thread (notifications and what not). The network request is obviously happening in a background thread, I think that eventually onResponse is now back on the main thread (otherwise you’d get other exceptions). Double check it my testing Looper.getMainLooper() == Looper.myLooper() (or similar).

You’re doing a lot of (unneeded) work on the Main Thread. You receive the response from the network, and you parse JSON and create objects in the Main Thread… why not offload all the work and once you have a list of items, pass it onto the adapter.

You’re inefficiently calling notifyDataSetChanged() every time (this is bad). Why not use the (included in Android) DiffUtil class to only notify of the changed range? Allow me to point you to a good sample of how it works: https://guides.codepath.com/android/using-the-recyclerview#diffing-larger-changes

It should take you about 30 minutes to implement these changes and it will make your code way more robust.

Bonus points if you use RXJava to make it a stream :-)

note: You should create the adapter once, and then simply call setItems(your_list_of_items) every time you have new data. The DiffUtil and adapter should know how to deal with this. You have a lot of “business logic” there in your activity/fragment/networking code that doesn’t belong there. All your “onResponse” method should do is prepare the data and pass it to the class responsible for managing the data (the adapter). When I see this // If the adapter hasn't been created, do this, I frown. Why is this code creating the adapter here? Who’s gonna test this? What if you change OKHttp with something else? (why not use retrofit and make it even easier?).

I mean, there are multiple things you can do to make your life as a programmer easier, you’re not making use of the solutions available to you.

Body:
My RecyclerView crashes with an IndexOutOfBoundsException while scrolling after attempting to refresh the data.

Desired functionality: After API request has successfully populated RecyclerView once, I'd like to refresh the RecyclerView and be able to scroll up and down while it refreshes.

Current functionality: If I don't scroll while refreshing the data, the app doesn't crash. If I scroll after making a refresh request, it crashes with an IndexOutOfBoundsException.

I've spent several weeks trying to troubleshoot this problem without posting a question, and I believe I've tried enough potential solutions to justify asking Stack Overflow for guidance. There are countless questions on here with the same subject, but unfortunately none of them have solved my problem. Thank you in advance for your consideration.

Here are some solutions other people have suggested:

To use adapter.notifyDataSetChanged(), but I understand this to
be considered a 'last resort' in the Android documentation

To call list.clear before adapter.notifyDataSetChanged()

To get the position of all current items in the data set to an Integer called 'position' with adapter.getItemCount(), and then pass that to adapter.notifyItemRangeChanged(position)

To set adapter.setHasStableIds(true)

To call mRecyclerView.getRecycledViewPool().clear() and mAdapter.notifyDataSetChanged();

Apparently if the RecyclerView is inside a LinearLayout, 'notify' methods don't work (this might pertain to an old bug in Android which may be fixed now, but I'm not sure.)

All of these suggestions result in a 'Fatal Exception'.

My app uses five files:

JobsAdapter (Adapter)

JobsListItem (Getters and Setters)

JobsOut (Fragment)

jobs_recyclerview

jobs_listitem

I've only included code for the Adapter and Fragment, because I'm confident that the layout files and Getters and Setters are well formed.

Fragment:

public class JobsOut extends Fragment {

String jobId;
String jobTitle;
String jobNumber;
String jobStartTime;
String dispatchType;

@BindView(R.id.jobsOutRecyclerView) RecyclerView jobsOutRecyclerView;
@BindView(R.id.fab) FloatingActionButton refreshFab;

private List<JobsListItem> dispatch;
private RecyclerView.Adapter mJobsOutAdapter;
public RecyclerView.LayoutManager dispatchLayoutManager;

OkHttpClient client = new OkHttpClient();
Handler handler = new Handler();

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.recycler_test, container, false);
    ButterKnife.bind(this, rootView);

    dispatch = new ArrayList<>();
    jobsOutRecyclerView.setHasFixedSize(true);
    dispatchLayoutManager = new LinearLayoutManager(getContext());
    jobsOutRecyclerView.setLayoutManager(dispatchLayoutManager);

    downloadDispatch();

    refreshFab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            downloadDispatch();

            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    dispatch.clear();
                }
            });
        }
    });

    return rootView;
}

@Override
public void onDestroy() {
    super.onDestroy();
    handler.removeCallbacksAndMessages(this);
}

private void downloadDispatch() {
    final okhttp3.Request request = new okhttp3.Request.Builder()
            .url("url")
            .header("X_SUBDOMAIN", "SUBDOMAIN")
            .header("X-AUTH-TOKEN", "API_KEY")
            .build();

    Call call = client.newCall(request);
    call.enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {

        }

        @Override
        public void onResponse(Call call, okhttp3.Response response) throws IOException {

            try {
                String jsonData = response.body().string();

                JSONObject getRootObject = new JSONObject(jsonData);
                JSONObject metaObject = getRootObject.getJSONObject("meta");
                final String row_count = metaObject.getString("total_row_count");
                {

                    if (row_count.equals("0")) {
                        // do something for no jobs
                    } else {
                        JSONObject getArray = new JSONObject(jsonData);
                        JSONArray opportunitiesArray = getArray.getJSONArray("opportunities");

                        for (int i = 0; i < opportunitiesArray.length(); i++) {
                            JSONObject opportunity = opportunitiesArray.getJSONObject(i);

                            jobId = opportunity.getString("id");
                            jobTitle = opportunity.getString("subject");
                            jobNumber = opportunity.getString("number");
                            jobStartTime = opportunity.getString("starts_at");
                            dispatchType = opportunity.getString("customer_collecting");

                            // Take Strings from response and send them to JobsListItem
                            final JobsListItem item = new JobsListItem(jobId, jobTitle, jobNumber, jobStartTime, dispatchType);

                            // If the adapter hasn't been created, do this
                            if (mJobsOutAdapter == null) {
                                new Handler(Looper.getMainLooper()).post(new Runnable() {
                                    @Override
                                    public void run() {
                                        mJobsOutAdapter = new JobsAdapter(dispatch, getContext());
                                        jobsOutRecyclerView.setAdapter(mJobsOutAdapter);
                                        dispatch.add(item);
                                    }
                                });
                            }
                            // If the adapter has been created, just do this
                            else if (mJobsOutAdapter != null) {
                                new Handler(Looper.getMainLooper()).post(new Runnable() {
                                    @Override
                                    public void run() {
                                        dispatch.add(item);
                                        mJobsOutAdapter.notifyDataSetChanged();
                                    }
                                });
                            }
                        }
                    }
                }
            } catch (IOException e) {
                Log.e("TAG", "IO exception caught: ", e);
            } catch (JSONException e) {
                Log.e("TAG", "TAG exception caught: ", e);
            }
        }
    });
}

Adapter:

public class JobsAdapter extends RecyclerView.Adapter<JobsAdapter.ViewHolder> {

private List<JobsListItem> mJobsListItem;
private Context context;

public JobsAdapter(List<JobsListItem> mJobsListItem, Context context) {
    this.mJobsListItem = mJobsListItem;
    this.context = context;
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.jobs_listitem, parent, false);

    return new ViewHolder(view);
}

@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
    final JobsListItem mJobsListItemViewHolder = this.mJobsListItem.get(position);

    // holders go here and do things with text and what-not
}

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

public class ViewHolder extends RecyclerView.ViewHolder {

    // BindView's with ButterKnife go here and all that jazz

    public ViewHolder(View itemView) {
        super(itemView);
        ButterKnife.bind(this, itemView);
    }
}

Logcat from crash:

26404-26404 E/AndroidRuntime: FATAL EXCEPTION: main
                          Process: uk.co.plasmacat.techmate, PID: 26404
                          java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid item position 4(offset:4).state:16
                              at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5504)
                              at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5440)
                              at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5436)
                              at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2224)
                              at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1551)
                              at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1511)
                              at android.support.v7.widget.LinearLayoutManager.scrollBy(LinearLayoutManager.java:1325)
                              at android.support.v7.widget.LinearLayoutManager.scrollVerticallyBy(LinearLayoutManager.java:1061)
                              at android.support.v7.widget.RecyclerView.scrollByInternal(RecyclerView.java:1695)
                              at android.support.v7.widget.RecyclerView.onTouchEvent(RecyclerView.java:2883)
                              at android.view.View.dispatchTouchEvent(View.java:10063)
                              at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2630)
                              at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2307)
                              at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2636)
                              at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2321)
                              at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2636)
                              at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2321)
                              at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2636)
                              at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2321)
                              at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2636)
                              at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2321)
                              at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2636)
                              at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2321)
                              at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2636)
                              at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2321)
                              at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2636)
                              at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2321)
                              at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2636)
                              at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2321)
                              at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2636)
                              at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2321)
                              at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2636)
                              at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2321)
                              at com.android.internal.policy.DecorView.superDispatchTouchEvent(DecorView.java:413)
                              at com.android.internal.policy.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1819)
                              at android.app.Activity.dispatchTouchEvent(Activity.java:3127)
                              at android.support.v7.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:71)
                              at android.support.v7.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:71)
                              at com.android.internal.policy.DecorView.dispatchTouchEvent(DecorView.java:375)
                              at android.view.View.dispatchPointerEvent(View.java:10283)
                                  at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:4522)
                              at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:4353)
                              at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3893)
                              at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3946)
                              at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3912)
                              at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:4039)
                              at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3920)
                              at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:4096)
                              at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3893)
                              at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3946)
                              at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3912)
                              at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3920)
                              at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3893)
                              at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:6341)
                              at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:6315)
                              at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:6265)
                              at

android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:6444)
                                  at android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:185)
                                  at android.view.InputEventReceiver.nativeConsumeBatchedInputEvents(Native Method)
                                  at android.view.InputEventReceiver.consumeBatchedInputEvents(InputEventReceiver.java:176)
                                  at android.view.ViewRootImpl.doConsumeBatchedInput(ViewRootImpl.java:6415)
                                  at android.view.ViewRootImpl$ConsumeBatchedInputRunnable.run(ViewRootImpl.java:6467)
                                  at android.view.Choreographer$CallbackRecord.run(Choreographer.java:874)
                                  at android.view.Choreographer.doCallbacks(Choreographer.java:686)
                                  at android.view.Choreographer.doFrame(Choreographer.java:615)
                                  at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:860)
                                  at android.os.Handler.handleCallback(Handler.java:751)
                                  at android.os.Handler.dispatchMessage(Handler.java:95)
                                  at android.os.Looper.loop(Looper.java:154)
                                  at android.app.ActivityThread.main(ActivityThread.java:6290)
                                  at java.lang.reflect.Method.invoke(Native Method)
                                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

If you have the time, I would thoroughly appreciate your help.

Thank you!


来源: stackexchange

问:
Default user: WSO2 Identity Server with Mariadb
I followed the steps defined in this link and restarted the WSO2 identity server.

When trying to login at https://localhost:9443/carbon using admin/admin credentials, it's giving me login failed message. Before changing the settings for WSO2, it was working with this credentials.

Obviously, that user is not present in MariaDB. Does anyone has any scripts to insert an admin user in WSO2 Maria DB for? I don't know what all tables I need to update in case of adding user manually. Or is there any other default user?

Kindly suggest.

答:
Had the same problem, even switched to mysql community and it didn't fix it.
So with mysql installed I did the following, after MANY tries,
mysql -u root -p
create DATABASE regdb;
exit;
mysql -u root -p regdb < <WSO2_HOME>/dbscripts/mysql5.7.sql
mysql -u root -p regdb < <WSO2_HOME>/dbscripts/identity/mysql-5.7.sql
nohup <WSO2_HOME>/bin/wso2server.h -Dsetup &
If there is someplace to see the DB version, I haven't found it, but this got it all to working form me.  So loading keep failing the DB because of some default time functions in the sql.
My $0.02

ContentLicense: CC BY-SA 3.0


问:
C# switch statement limitations - why?
When writing a switch statement, there appears to be two limitations on what you can switch on in case statements.

For example (and yes, I know, if you're doing this sort of thing it probably means your object-oriented (OO) architecture is iffy - this is just a contrived example!),

```<code>  Type t = typeof(int);

  switch (t) {

    case typeof(int):
      Console.WriteLine("int!");
      break;

    case typeof(string):
      Console.WriteLine("string!");
      break;

    default:
      Console.WriteLine("unknown!");
      break;
  }
</code>```

Here the switch() statement fails with 'A value of an integral type expected' and the case statements fail with 'A constant value is expected'.

Why are these restrictions in place, and what is the underlying justification? I don't see any reason why the switch statement has to succumb to static analysis only, and why the value being switched on has to be integral (that is,  primitive). What is the justification?

答: According to the switch statement documentation if there is an unambiguous way to implicitly convert the the object to an integral type, then it will be allowed.  I think you are expecting a behavior where for each case statement it would be replaced with if (t == typeof(int)), but that would open a whole can of worms when you get to overload that operator.  The behavior would change when implementation details for the switch statement changed if you wrote your == override incorrectly.  By reducing the comparisons to integral types and string and those things that can be reduced to integral types (and are intended to) they avoid potential issues.

OwnerDisplayName: kronoz

Title: C# switch statement limitations - why?

Body:
When writing a switch statement, there appears to be two limitations on what you can switch on in case statements.

For example (and yes, I know, if you're doing this sort of thing it probably means your object-oriented (OO) architecture is iffy - this is just a contrived example!),

  Type t = typeof(int);

  switch (t) {

    case typeof(int):
      Console.WriteLine("int!");
      break;

    case typeof(string):
      Console.WriteLine("string!");
      break;

    default:
      Console.WriteLine("unknown!");
      break;
  }

Here the switch() statement fails with 'A value of an integral type expected' and the case statements fail with 'A constant value is expected'.

Why are these restrictions in place, and what is the underlying justification? I don't see any reason why the switch statement has to succumb to static analysis only, and why the value being switched on has to be integral (that is,  primitive). What is the justification?

LastEditorDisplayName: ecleel

OwnerDisplayName: fryguybob

ContentLicense: CC BY-SA 2.5


问:
MySQL AUTO_INCREMENT does not ROLLBACK
I'm using MySQL's AUTO_INCREMENT field and InnoDB to support transactions. I noticed when I rollback the transaction, the AUTO_INCREMENT field is not rollbacked? I found out that it was designed this way but are there any workarounds to this? </p>

答:
I do not know of any way to do that.  According to the MySQL Documentation, this is expected behavior and will happen with all innodb_autoinc_lock_mode lock modes.  The specific text is:

In all lock modes (0, 1, and 2), if a
  transaction that generated
  auto-increment values rolls back,
  those auto-increment values are
  “lost.” Once a value is generated for
  an auto-increment column, it cannot be
  rolled back, whether or not the
  “INSERT-like” statement is completed,
  and whether or not the containing
  transaction is rolled back. Such lost
  values are not reused. Thus, there may
  be gaps in the values stored in an
  AUTO_INCREMENT column of a table.

OwnerDisplayName: Gian Paulo

Title: MySQL AUTO_INCREMENT does not ROLLBACK

OwnerDisplayName: gpojd


问:
Radio buttons enabled, user cannot change the value
Is it possible to have enabled radio buttons though the user cannot change the value?</p>

答:
It is possible. If you create your radio buttons with the BS_RADIOBUTTON style instead of BS_AUTORADIOBUTTON then Windows will not automatically change the selection when the user clicks a radio button. (In the dialog editor in Visual Studio, right click the radio button and set the Auto property to False.)

Read the "Using Radio Buttons" section of this page in MSDN for more information.


问:
How can I calculate the total number of times an activity in android is displayed on screen?
Suppose i have a SecondActivity , I open the app and go to SecondActivity that should be count = 1 time, now I navigate to ThirdActivity and go back to SecondActivity that should be now count=2. Next I minimize the app, and then open the app, the count should now be count = 3.

答: Use a static int in the Activity, initialized to 0.  In onResume, increment it.</p>


问:
Android custom circular ProgressBar direction
I have a custom Circular Progressbar. This is the drawable I have for it to be determinate:

```<code><?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:id="@android:id/secondaryProgress">
    <shape
        android:innerRadiusRatio="6"
        android:shape="ring"
        android:thicknessRatio="20.0"
        android:useLevel="true">
     <gradient
          android:centerColor="#999999"
          android:endColor="#999999"
          android:startColor="#999999"
          android:type="sweep" />
    </shape>
  </item>
  <item android:id="@android:id/progress">
   <rotate
      android:fromDegrees="270"
      android:pivotX="50%"
      android:pivotY="50%"
      android:toDegrees="270">

  <shape
      android:innerRadiusRatio="6"
      android:shape="ring"
      android:thicknessRatio="20.0"
      android:useLevel="true">

    <rotate
        android:fromDegrees="360"
        android:pivotX="50%"
        android:pivotY="50%"
        android:toDegrees="0" />

    <gradient
        android:centerColor="?attr/colorAccent"
        android:endColor="?attr/colorAccent"
        android:startColor="?attr/colorAccent"
        android:type="sweep" />

      </shape>
    </rotate>
  </item>
</layer-list>
</code>```

I want it to show the progress in a clockwise direction, but now it's showing counterclockwise.

How do I change it?

答:
I guess you're using an rtl language? You can force the progress bar to an ltr or clockwise direction by setting the layoutDirection property on your ProgressBar.

```<code><ProgressBar
    ...
    android:layoutDirection="ltr" />
</code>```

Body:
I have a custom Circular Progressbar. This is the drawable I have for it to be determinate:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:id="@android:id/secondaryProgress">
    <shape
        android:innerRadiusRatio="6"
        android:shape="ring"
        android:thicknessRatio="20.0"
        android:useLevel="true">
     <gradient
          android:centerColor="#999999"
          android:endColor="#999999"
          android:startColor="#999999"
          android:type="sweep" />
    </shape>
  </item>
  <item android:id="@android:id/progress">
   <rotate
      android:fromDegrees="270"
      android:pivotX="50%"
      android:pivotY="50%"
      android:toDegrees="270">

  <shape
      android:innerRadiusRatio="6"
      android:shape="ring"
      android:thicknessRatio="20.0"
      android:useLevel="true">

    <rotate
        android:fromDegrees="360"
        android:pivotX="50%"
        android:pivotY="50%"
        android:toDegrees="0" />

    <gradient
        android:centerColor="?attr/colorAccent"
        android:endColor="?attr/colorAccent"
        android:startColor="?attr/colorAccent"
        android:type="sweep" />

      </shape>
    </rotate>
  </item>
</layer-list>

I want it to show the progress in a clockwise direction, but now it's showing counterclockwise.

How do I change it?

Body:
I guess you're using an rtl language? You can force the progress bar to an ltr or clockwise direction by setting the layoutDirection property on your ProgressBar.

<ProgressBar
    ...
    android:layoutDirection="ltr" />


问:
google.gax.errors.RetryError StatusCode.DEADLINE_EXCEEDED
from this github:
https://github.com/GoogleCloudPlatform/python-docs-samples

i am trying to test Video intelligence API and do label analysis.

```<code>import argparse
import sys
import time
import io
import base64

from google.cloud.gapic.videointelligence.v1beta1 import enums
from google.cloud.gapic.videointelligence.v1beta1 import (
    video_intelligence_service_client)
# [END imports]

#python labels.py /Users/rockbaek/tildawatch-contents/EpicSkillShot/M7-_VukSueY/SKT\ vs\ KT\ Game\ 3\ _\ Grand\ Finals\ S7\ LCK\ Spring\ 2017\ _\ KT\ Rolster\ vs\ SK\ Telecom\ T1\ G3\ 1080p-M7-_VukSueY.mp4

def analyze_labels_file(path):
    """ Detects labels given a file path. """
    video_client = (video_intelligence_service_client.
                    VideoIntelligenceServiceClient())
    features = [enums.Feature.LABEL_DETECTION]

    with io.open(path, "rb") as movie:
        content_base64 = base64.b64encode(movie.read())

    operation = video_client.annotate_video(
        '', features, input_content=content_base64)
    print('\nProcessing video for label annotations:')

    while not operation.done():
        sys.stdout.write('.')
        sys.stdout.flush()
        time.sleep(15)

    print('\nFinished processing.')

    # first result is retrieved because a single video was processed
    results = operation.result().annotation_results[0]

    for i, label in enumerate(results.label_annotations):
        print('Label description: {}'.format(label.description))
        print('Locations:')

        for l, location in enumerate(label.locations):
            positions = 'Entire video'
            if (location.segment.start_time_offset != -1 or
                    location.segment.end_time_offset != -1):
                positions = '{} to {}'.format(
                    location.segment.start_time_offset / 1000000.0,
                    location.segment.end_time_offset / 1000000.0)
            print('\t{}: {}'.format(l, positions))

        print('\n')

if __name__ == '__main__':
    # [START running_app]
    parser = argparse.ArgumentParser(
        description=__doc__,
        formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument('path', help='GCS file path for label detection.')
    args = parser.parse_args()

    analyze_labels_file(args.path)
# [END running_app]
# [END full_tutorial]
</code>```

and then i run it from terminal
python labels.py MP4_FILE_PATH

After quite a while, it fails with this error code:

```<code>Traceback (most recent call last):
  File "labels.py", line 123, in <module>
    analyze_labels_file(args.path)
  File "labels.py", line 52, in analyze_labels_file
    '', features, input_content=content_base64)
  File "/Library/Python/2.7/site-packages/google/cloud/gapic/videointelligence/v1beta1/video_intelligence_service_client.py", line 237, in annotate_video
    self._annotate_video(request, options), self.operations_client,
  File "/Library/Python/2.7/site-packages/google/gax/api_callable.py", line 428, in inner
    return api_caller(api_call, this_settings, request)
  File "/Library/Python/2.7/site-packages/google/gax/api_callable.py", line 416, in base_caller
    return api_call(*args)
  File "/Library/Python/2.7/site-packages/google/gax/api_callable.py", line 376, in inner
    return a_func(*args, **kwargs)
  File "/Library/Python/2.7/site-packages/google/gax/retry.py", line 144, in inner
    raise exc
google.gax.errors.RetryError: GaxError(Retry total timeout exceeded with exception, caused by <_Rendezvous of RPC that terminated with (StatusCode.DEADLINE_EXCEEDED, Deadline Exceeded)>)
</code>```

Please help why it is not working! :(

答:
I tried your code with a small video and it seems to work just fine for me. Maybe you are hitting some form of quota or limits (refer: https://cloud-dot-devsite.googleplex.com/video-intelligence/limits)? I have also run large videos loaded in Google Storage and using Python client library without issue.

Other step to try: send the request to the service via a curl command.

Body:
from this github:
https://github.com/GoogleCloudPlatform/python-docs-samples

i am trying to test Video intelligence API and do label analysis.

import argparse
import sys
import time
import io
import base64

from google.cloud.gapic.videointelligence.v1beta1 import enums
from google.cloud.gapic.videointelligence.v1beta1 import (
    video_intelligence_service_client)
# [END imports]

#python labels.py /Users/rockbaek/tildawatch-contents/EpicSkillShot/M7-_VukSueY/SKT\ vs\ KT\ Game\ 3\ _\ Grand\ Finals\ S7\ LCK\ Spring\ 2017\ _\ KT\ Rolster\ vs\ SK\ Telecom\ T1\ G3\ 1080p-M7-_VukSueY.mp4

def analyze_labels_file(path):
    """ Detects labels given a file path. """
    video_client = (video_intelligence_service_client.
                    VideoIntelligenceServiceClient())
    features = [enums.Feature.LABEL_DETECTION]

    with io.open(path, "rb") as movie:
        content_base64 = base64.b64encode(movie.read())

    operation = video_client.annotate_video(
        '', features, input_content=content_base64)
    print('\nProcessing video for label annotations:')

    while not operation.done():
        sys.stdout.write('.')
        sys.stdout.flush()
        time.sleep(15)

    print('\nFinished processing.')

    # first result is retrieved because a single video was processed
    results = operation.result().annotation_results[0]

    for i, label in enumerate(results.label_annotations):
        print('Label description: {}'.format(label.description))
        print('Locations:')

        for l, location in enumerate(label.locations):
            positions = 'Entire video'
            if (location.segment.start_time_offset != -1 or
                    location.segment.end_time_offset != -1):
                positions = '{} to {}'.format(
                    location.segment.start_time_offset / 1000000.0,
                    location.segment.end_time_offset / 1000000.0)
            print('\t{}: {}'.format(l, positions))

        print('\n')

if __name__ == '__main__':
    # [START running_app]
    parser = argparse.ArgumentParser(
        description=__doc__,
        formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument('path', help='GCS file path for label detection.')
    args = parser.parse_args()

    analyze_labels_file(args.path)
# [END running_app]
# [END full_tutorial]

and then i run it from terminal
python labels.py MP4_FILE_PATH

After quite a while, it fails with this error code:

Traceback (most recent call last):
  File "labels.py", line 123, in <module>
    analyze_labels_file(args.path)
  File "labels.py", line 52, in analyze_labels_file
    '', features, input_content=content_base64)
  File "/Library/Python/2.7/site-packages/google/cloud/gapic/videointelligence/v1beta1/video_intelligence_service_client.py", line 237, in annotate_video
    self._annotate_video(request, options), self.operations_client,
  File "/Library/Python/2.7/site-packages/google/gax/api_callable.py", line 428, in inner
    return api_caller(api_call, this_settings, request)
  File "/Library/Python/2.7/site-packages/google/gax/api_callable.py", line 416, in base_caller
    return api_call(*args)
  File "/Library/Python/2.7/site-packages/google/gax/api_callable.py", line 376, in inner
    return a_func(*args, **kwargs)
  File "/Library/Python/2.7/site-packages/google/gax/retry.py", line 144, in inner
    raise exc
google.gax.errors.RetryError: GaxError(Retry total timeout exceeded with exception, caused by <_Rendezvous of RPC that terminated with (StatusCode.DEADLINE_EXCEEDED, Deadline Exceeded)>)

Please help why it is not working! :(


问:
Timestamp line to a excel readable timestamp
I have thousands of timestamps in the form shown:

Sun Jul 02 06:00:02 2017 (GMT-04:00)

With Date, Day, and Time all varying. This is a military time stamp ( ie each day counts up to 24 hours)

I have used the following formula to get just the time. But it's not readable by excel.

```<code>=MID($A2,FIND(":",$A2)-2,8)
</code>```

This results in a value like:

06:00:02

However, this does not help and I have to do much manipulation. I want excel to recognize the date and time so i have a true timeline on my x-axis.

I'd like to get it in the form of

7/2/2017  6:00:02 AM

This way I can have a graph that appears like the following:

Graph Example with desired timeline on x axis

Cheers!!!!

答:
Since the weekday and the month are all in three letter abbreviations, you can use the Mid function with an absolute position to extract elements of the date. For just the date you could use

```<code>=DATEVALUE(MID(A1,9,2)&"-"&MID(A1,5,3)&"-"&MID(A1,21,4))
</code>```

For just the time value, you could use

```<code>=TIMEVALUE(MID(A1,12,8))
</code>```

To get the date and time in one value, just add the two and format as you want to see it.

```<code>=DATEVALUE(MID(A1,9,2)&"-"&MID(A1,5,3)&"-"&MID(A1,21,4))+TIMEVALUE(MID(A1,12,8))
</code>```

Body:
I have thousands of timestamps in the form shown:

Sun Jul 02 06:00:02 2017 (GMT-04:00)

With Date, Day, and Time all varying. This is a military time stamp ( ie each day counts up to 24 hours)

I have used the following formula to get just the time. But it's not readable by excel.

=MID($A2,FIND(":",$A2)-2,8)

This results in a value like:

06:00:02

However, this does not help and I have to do much manipulation. I want excel to recognize the date and time so i have a true timeline on my x-axis.

I'd like to get it in the form of

7/2/2017  6:00:02 AM

This way I can have a graph that appears like the following:

Graph Example with desired timeline on x axis

Cheers!!!!

Body:
Since the weekday and the month are all in three letter abbreviations, you can use the Mid function with an absolute position to extract elements of the date. For just the date you could use

=DATEVALUE(MID(A1,9,2)&"-"&MID(A1,5,3)&"-"&MID(A1,21,4))

For just the time value, you could use

=TIMEVALUE(MID(A1,12,8))

To get the date and time in one value, just add the two and format as you want to see it.

=DATEVALUE(MID(A1,9,2)&"-"&MID(A1,5,3)&"-"&MID(A1,21,4))+TIMEVALUE(MID(A1,12,8))


问:
What to put in the parameters of the EditText constructor in Android Studio?
I'm still fairly new to Android Studio and I want to test out something by creating a GridLayout with the desired rows and columns and fill it up with EditTexts. However I run into a problem where I do not know what to put as a parameter in the EditText constructor.
Here is the java code below:

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //The numbers WILL vary but this is just a test
    int rows = 3;
    int columns = 4;

    GridLayout gd = (GridLayout) findViewById(R.id.grid1);
    gd.setRowCount(rows);
    gd.setColumnCount(columns);
    EditText edt;

    for(int r = 0; r < rows; r++)
    {
        for(int c = 0; c < columns; c++)
        {
            //What to put in the parameters in this code below?
            edt = new EditText();
            gd.addView(edt);
        }
    }
}
</code>```

And here is the XML:

```<code><GridLayout
        android:id="@+id/grid1"
        android:layout_width="368dp"
        android:layout_height="495dp"
        tools:layout_editor_absoluteX="8dp"
        tools:layout_editor_absoluteY="8dp">

</GridLayout>
</code>```

I looked at the constructor for EditText and find that Context is needed, but how do I put that in there? If this is not the right way to do it, please tell me the right way.

答:
At first use findviewbyId for the edittext and then use set text for that edit text object

For example
EditText edit=(EditText)findViewById(R.id.edit_id);
edit.setText("abc");

Body:
I'm still fairly new to Android Studio and I want to test out something by creating a GridLayout with the desired rows and columns and fill it up with EditTexts. However I run into a problem where I do not know what to put as a parameter in the EditText constructor.
Here is the java code below:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //The numbers WILL vary but this is just a test
    int rows = 3;
    int columns = 4;

    GridLayout gd = (GridLayout) findViewById(R.id.grid1);
    gd.setRowCount(rows);
    gd.setColumnCount(columns);
    EditText edt;

    for(int r = 0; r < rows; r++)
    {
        for(int c = 0; c < columns; c++)
        {
            //What to put in the parameters in this code below?
            edt = new EditText();
            gd.addView(edt);
        }
    }
}

And here is the XML:

<GridLayout
        android:id="@+id/grid1"
        android:layout_width="368dp"
        android:layout_height="495dp"
        tools:layout_editor_absoluteX="8dp"
        tools:layout_editor_absoluteY="8dp">

</GridLayout>

I looked at the constructor for EditText and find that Context is needed, but how do I put that in there? If this is not the right way to do it, please tell me the right way.


问:
Tensorflow Object Detection API: disable nonmaxima suppression for off-the-shelf models
Is it possible and/or easy to disable the non-maxima suppression part of the off-the-shelf object detectors provided in the Tensorflow Object Detection API? E.g., I'd like to run the provided "SSD mobilenet which was trained on MSCOCO" without the non-maxima operation at the end. How can I achieve this? </p>

答:
If you want to do this for speed reasons, the only way is to edit the code itself (see https://github.com/tensorflow/models/blob/master/object_detection/meta_architectures/ssd_meta_arch.py#L331) --- this is a bit involved as you need to replace the call to NMS by code that would still put the boxes in the expected output format.

If you just want to get rid of the effect of NMS, you can simply set the score_threshold and iou_threshold of the postprocessing part of the config file:
https://github.com/tensorflow/models/blob/master/object_detection/samples/configs/ssd_mobilenet_v1_pets.config#L131
to be 0.0 and 1.0 respectively, meaning, don't filter low scoring boxes, and prune boxes based on iou only if they perfectly overlap (which in practice will be never).


问:
bash - math multiple integer with float type
In bash,I am trying to do math with a integer and a float number to get a integer result. below code snippet doesn't work:

```<code>x=25
y=0.2
z=$((x*y))
echo $x*$y=$z
</code>```

The error message is:

```<code>sh: line 3: 0.2: syntax error: invalid arithmetic operator (error token is ".2")
</code>```

If both variable is integer, it works fine.

How can I get "25*0.2=5" from bash script?

答:
Place your printout in quotes in echo. Also your z=$((x*y)) will make z empty or error:

25*0.2: syntax error: invalid arithmetic operator (error token is
  ".2")

So... Here is tested code and might be like this:

```<code>x=25
y=0.2
z=$(echo $x*$y | bc)
echo "$x*$y=$z"
</code>```

result will be like this:

```<code>25*0.2=5.0
</code>```

Note: we used bc command for z calculation

Body:
In bash,I am trying to do math with a integer and a float number to get a integer result. below code snippet doesn't work:

x=25
y=0.2
z=$((x*y))
echo $x*$y=$z

The error message is:

sh: line 3: 0.2: syntax error: invalid arithmetic operator (error token is ".2")

If both variable is integer, it works fine.

How can I get "25*0.2=5" from bash script?

Body:
Place your printout in quotes in echo. Also your z=$((x*y)) will make z empty or error:

25*0.2: syntax error: invalid arithmetic operator (error token is
  ".2")

So... Here is tested code and might be like this:

x=25
y=0.2
z=$(echo $x*$y | bc)
echo "$x*$y=$z"

result will be like this:

25*0.2=5.0

Note: we used bc command for z calculation


问:
String variable and echo (C) *Homework*
I am trying to solve this question: Write a C program that reads in characters from the keyboard until the return key is entered and echoes the entered text on the screen.

This is what I have so far, I am not sure what variable I can store the users input in so that I can print it back (assuming that is what they mean by echo):

```<code>#include<stdio.h>
#include<string>
int main ()
{
    char sentence;
    printf("Please enter anything you want: ");
    scanf("%c",&sentence);

    printf("%c",sentence);

    return 0;
}
</code>```

答:
It seems that all you need is the following

```<code>#include <stdio.h>

int main(void)
{
    printf( "Please enter anything you want: " );

    int c;

    while ( ( c = getchar() ) != EOF && c != '\n' )
    {
        putchar( c );
    }

    putchar( '\n' );

    return 0;
}
</code>```

That is you need to use a loop that will iterate until the Enter key is pressed.

Title: String variable and echo (C) *Homework*

Body:
I am trying to solve this question: Write a C program that reads in characters from the keyboard until the return key is entered and echoes the entered text on the screen.

This is what I have so far, I am not sure what variable I can store the users input in so that I can print it back (assuming that is what they mean by echo):

#include<stdio.h>
#include<string>
int main ()
{
    char sentence;
    printf("Please enter anything you want: ");
    scanf("%c",&sentence);

    printf("%c",sentence);

    return 0;
}

Body:
It seems that all you need is the following

#include <stdio.h>

int main(void)
{
    printf( "Please enter anything you want: " );

    int c;

    while ( ( c = getchar() ) != EOF && c != '\n' )
    {
        putchar( c );
    }

    putchar( '\n' );

    return 0;
}

That is you need to use a loop that will iterate until the Enter key is pressed.


答:
Option 1

pd.concat

```<code>pd.concat({i: d.set_index('context').time for i, d in pn.iteritems()}).unstack()

context  foo  bar  baz
0         21   37   53
1         36   42   76
2         24   56   83
3         17   32   45
</code>```

Option 2

pd.DataFrame

```<code>pd.DataFrame([d.set_index('context').time for i, d in pn.iteritems()], pn.items)

context  foo  bar  baz
0         21   37   53
1         36   42   76
2         24   56   83
3         17   32   45
</code>```

Title: Transform pandas panel into dataframe

Body:
I have a pandas.Panel, and I want to create a pandas.DataFrame with the column headers coming from one column, the data from another column, and the number of rows is the number of items in the panel.

If diagrams will help describe what I'm looking for...

My panel looks somewhat like the following:

      +---+---------+------------+------+
    +---+---------+------------+------+ |
  +---+---------+------------+------+ |-+
+---+---------+------------+------+ |-+ |
|   | context | iterations | time |-+ |-+
+---+---------+------------+------+ |-+ |
| 0 | foo     |          1 |   21 |-+ |-+
+---+---------+------------+------+ |-+ |
| 1 | bar     |          2 |   37 |-+ |-+
+---+---------+------------+------+ |-+
| 2 | baz     |          1 |   53 |-+
+---+---------+------------+------+

I would like to transform the panel into a dataframe:

The dataframe column headers are the "context" column

The dataframe values are the "time" column

The number of rows in the dataframe is the number of items in the panel

The result would look something like this:

+---+-----+-----+-----+
|   | foo | bar | baz |
+---+-----+-----+-----+
| 0 |  21 |  37 |  53 |
+---+-----+-----+-----+
| 1 |  36 |  42 |  76 |
+---+-----+-----+-----+
| 2 |  24 |  56 |  83 |
+---+-----+-----+-----+
| 3 |  17 |  32 |  45 |
+---+-----+-----+-----+

Body:
Option 1

pd.concat

pd.concat({i: d.set_index('context').time for i, d in pn.iteritems()}).unstack()

context  foo  bar  baz
0         21   37   53
1         36   42   76
2         24   56   83
3         17   32   45

Option 2

pd.DataFrame

pd.DataFrame([d.set_index('context').time for i, d in pn.iteritems()], pn.items)

context  foo  bar  baz
0         21   37   53
1         36   42   76
2         24   56   83
3         17   32   45


问:
Why is datekey in fact tables always INT?
I'm looking at the datekey column from the fact tables in AdventureWorksDW and they're all of type int.

Is there a reason for this and not of type date?

I understand that creating a clustered index composed of an INT would optimize query speed. But let's say I want to get data from this past week. I can subtract 6 from date 20170704 and I'll get 20170698 which is not a valid date. So I have to cast everything to date, subtract, and then cast as int.

Right now I have a foreign key constraint to make sure that something besides 'YYYYMMDD' isn't inserted. It wouldn't be necessary with a Date type. Just now, I wanted to get some data between 6/28 and 7/4. I can't just subtract six from `20170703'; I have to cast from int to date.

It seems like a lot of hassle and not many benefits.

Thanks.

答:
Yes, you could be using a Date data type and have that as your primary key in the Fact and the dimension and you're going to save yourself a byte in the process.

And then you're going to have to deal with a sale that is recorded and we didn't know the date. What then? In a "normal" dimensional model, you define Unknown surrogate values so that people know there is data and it might be useful but it's incomplete. A common convention is to make it zero or in the negative realm. Easy to do with integers.

Dates are a little weird in that we typically use smart keys - yyyymmdd. From a debugging perspective, it's easy to quickly identify what the date is without having to look up against your dimension.

You can't make an invalid date. Soooo what then? Everyone "knows" that 1899-12-31 is the "fake" date (or whatever tickles your fancy) and that's all well and good until someone fat fingers a date and magically hit your sentinel date and now you've got valid unknowns mixed with merely bad data entry.

If you're doing date calculations against an smart key, you're doing it wrong. You need to go to your data dimension to properly resolve the value and use methods that are aware of date logic because it's ugly and nasty beyond just simple things like month lengths and leap year calculations.


问:
Passing Input Pipeline to TensorFlow Estimator
I'm a noob to TF so go easy on me.

I have to train a simple CNN from a bunch of images in a directory with labels.  After looking around a lot, I cooked up this code that prepares a TF input pipeline and I was able to print the image array.

```<code>    image_list, label_list = load_dataset()

    imagesq = ops.convert_to_tensor(image_list, dtype=dtypes.string)
    labelsq = ops.convert_to_tensor(label_list, dtype=dtypes.int32)

    # Makes an input queue
    input_q = tf.train.slice_input_producer([imagesq, labelsq],
                                                shuffle=True)

    file_content = tf.read_file(input_q[0])
    train_image = tf.image.decode_png(file_content,channels=3)
    train_label = input_q[1]

    train_image.set_shape([120,120,3])

    # collect batches of images before processing
    train_image_batch, train_label_batch = tf.train.batch(
        [train_image, train_label],
        batch_size=5
        # ,num_threads=1
    )

    with tf.Session() as sess:
        # initialize the variables
        sess.run(tf.global_variables_initializer())
        # initialize the queue threads to start to shovel data
        coord = tf.train.Coordinator()
        threads = tf.train.start_queue_runners(coord=coord)
        # print "from the train set:"
        for i in range(len(image_list)):
             print sess.run(train_image_batch)
        # sess.run(train_image)
        # sess.run(train_label)
        # classifier.fit(input_fn=lambda: (train_image, train_label),
        #                steps=100,
        #                monitors=[logging_hook])

        # stop our queue threads and properly close the session
        coord.request_stop()
        coord.join(threads)
        sess.close()
</code>```

But looking at the MNIST example given in TF docs, I see they use a cnn_model_fn along with Estimator class.

I have defined my own cnn_model_fn and would like to combine the two.  Please help me on how to move forward with this.  This code doesn't work

```<code>classifier = learn.Estimator(model_fn=cnn_model_fn, model_dir='./test_model')
classifier.fit(input_fn=lambda: (train_image, train_label),
steps=100,
monitors=[logging_hook])
</code>```

It seems the pipeline is populated only when the session is run, otherwise its empty and it gives a ValueError 'Input graph and Layer graph are not the same'

Please help me.

答:
I'm new to tensorflow myself so take this with a grain of salt.

AFAICT, when you call any of the tf APIs that create "tensors" or "operations" they are created into a context called a Graph.

Further, I believe when the Estimator runs it creates a new empty Graph for each run. It populates the Graph by running model_fn and input_fn that are supposed to call tf APIs that add the "tensors" and "operations" in context of this fresh Graph.

The return values from model_fn and input_fn just provide references so that the parts could be connected correctly - the Graph already contains them.

However in this example the input operations have already been created before the Estimator created the Graph and thus their related operations have been added to the implicit default Graph (one is created automatically I believe). So when the Estimator creates a new one and populates the model with model_fn the input and model will be on two different graphs.

To fix this you need to change the input_fn. Don't just wrap the (image, labels) pair into a lambda but rather wrap the entire construction of the input into a function so that when the Estimator runs input_fn as a side effect of all the API calls all the input operations and tensors would be created in context of the correct Graph.

Body:
I'm a noob to TF so go easy on me.

I have to train a simple CNN from a bunch of images in a directory with labels.  After looking around a lot, I cooked up this code that prepares a TF input pipeline and I was able to print the image array.

    image_list, label_list = load_dataset()

    imagesq = ops.convert_to_tensor(image_list, dtype=dtypes.string)
    labelsq = ops.convert_to_tensor(label_list, dtype=dtypes.int32)

    # Makes an input queue
    input_q = tf.train.slice_input_producer([imagesq, labelsq],
                                                shuffle=True)

    file_content = tf.read_file(input_q[0])
    train_image = tf.image.decode_png(file_content,channels=3)
    train_label = input_q[1]

    train_image.set_shape([120,120,3])

    # collect batches of images before processing
    train_image_batch, train_label_batch = tf.train.batch(
        [train_image, train_label],
        batch_size=5
        # ,num_threads=1
    )

    with tf.Session() as sess:
        # initialize the variables
        sess.run(tf.global_variables_initializer())
        # initialize the queue threads to start to shovel data
        coord = tf.train.Coordinator()
        threads = tf.train.start_queue_runners(coord=coord)
        # print "from the train set:"
        for i in range(len(image_list)):
             print sess.run(train_image_batch)
        # sess.run(train_image)
        # sess.run(train_label)
        # classifier.fit(input_fn=lambda: (train_image, train_label),
        #                steps=100,
        #                monitors=[logging_hook])

        # stop our queue threads and properly close the session
        coord.request_stop()
        coord.join(threads)
        sess.close()

But looking at the MNIST example given in TF docs, I see they use a cnn_model_fn along with Estimator class.

I have defined my own cnn_model_fn and would like to combine the two.  Please help me on how to move forward with this.  This code doesn't work

classifier = learn.Estimator(model_fn=cnn_model_fn, model_dir='./test_model')
classifier.fit(input_fn=lambda: (train_image, train_label),
steps=100,
monitors=[logging_hook])

It seems the pipeline is populated only when the session is run, otherwise its empty and it gives a ValueError 'Input graph and Layer graph are not the same'

Please help me.


问:
What is wrong with this code in C for SPOJ Prime Generator?
I am a beginner programmer and I started to code 3 months ago. I decided to do problems on SPOJ but i am getting stuck very frequently. I completed the problem 1 i.e Life and universe which was easy but I got stuck in this one. I wrote the following code:

```<code>#include <stdio.h>
#include <math.h>

int main () {
int m,n,i,j=2, t,counter=0;

scanf ("%d", &t);

while (t--) {

    scanf ("%d%d", &m,&n);

    for (i=m; i<=n; i++) {

        for (j=2; j<(int)sqrt(i); j++) {
            if (i%j==0) {
                break;
            }
            else {
                printf ("%d\n", i);
                break;
             }
         }
    }
  }
return 0;
}
</code>```

I am unable to figure out what and where I am doing it wrong.

I also tried one different version for this which gives the correct answer but that code is taking very long time and giving TLE . The code is as follow :

```<code>#include <stdio.h>
int main () {
int m,n,i,j=2, t,counter=0;

scanf ("%d", &t);

while (t--) {
    scanf ("%d%d", &m,&n);

    for (i=m; i<=n; i++) {
        while (j<=i) {
         if (i%j==0)
         counter++;
         j++;
        }
        if (counter==1)
        printf ("%d\n",i);
        counter=0;
        j=2;
    }
 }
return 0;
}
</code>```

How can I prepare myself for SPOJ and other programming competitions? Where I am lacking?

答:
For this question, keeping the constraints(value of m and n) in mind, use Sieve of Eratosthenes algorithm, a simple, efficient and ancient algorithm for finding all prime numbers up to any given limit.Here is the pseudo code for the algorithm

```<code>Input: an integer n > 1.

 Let A be an array of Boolean values, indexed by integers 2 to n,
 initially all set to true.

 for i = 2, 3, 4, ..., not exceeding √n:
   if A[i] is true:
     for j = i2, i2+i, i2+2i, i2+3i, ..., not exceeding n:
       A[j] := false.

 Output: all i such that A[i] is true.
</code>```

Source: https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes. Hope this helps!

Body:
I am a beginner programmer and I started to code 3 months ago. I decided to do problems on SPOJ but i am getting stuck very frequently. I completed the problem 1 i.e Life and universe which was easy but I got stuck in this one. I wrote the following code:

#include <stdio.h>
#include <math.h>

int main () {
int m,n,i,j=2, t,counter=0;

scanf ("%d", &t);

while (t--) {

    scanf ("%d%d", &m,&n);

    for (i=m; i<=n; i++) {

        for (j=2; j<(int)sqrt(i); j++) {
            if (i%j==0) {
                break;
            }
            else {
                printf ("%d\n", i);
                break;
             }
         }
    }
  }
return 0;
}

I am unable to figure out what and where I am doing it wrong.

I also tried one different version for this which gives the correct answer but that code is taking very long time and giving TLE . The code is as follow :

#include <stdio.h>
int main () {
int m,n,i,j=2, t,counter=0;

scanf ("%d", &t);

while (t--) {
    scanf ("%d%d", &m,&n);

    for (i=m; i<=n; i++) {
        while (j<=i) {
         if (i%j==0)
         counter++;
         j++;
        }
        if (counter==1)
        printf ("%d\n",i);
        counter=0;
        j=2;
    }
 }
return 0;
}

How can I prepare myself for SPOJ and other programming competitions? Where I am lacking?

Body:
For this question, keeping the constraints(value of m and n) in mind, use Sieve of Eratosthenes algorithm, a simple, efficient and ancient algorithm for finding all prime numbers up to any given limit.Here is the pseudo code for the algorithm

Input: an integer n > 1.

 Let A be an array of Boolean values, indexed by integers 2 to n,
 initially all set to true.

 for i = 2, 3, 4, ..., not exceeding √n:
   if A[i] is true:
     for j = i2, i2+i, i2+2i, i2+3i, ..., not exceeding n:
       A[j] := false.

 Output: all i such that A[i] is true.

Source: https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes. Hope this helps!


问:
Dynamically create a HTML5 video element without it being shown in the page
Is it possible to dynamically create a HTML5 video element so that I can access the element by API's like document.getElementById or Name but it may not show up in the webpage.

Something like div.hide() or something in that direction ?

答:
Updated (and simplest) way to achieve this (since Google searches are leading here):</p>

```<code>var x = document.createElement("VIDEO");

if (x.canPlayType("video/mp4")) {
    x.setAttribute("src","movie.mp4");
} else {
    x.setAttribute("src","movie.ogg");
}

x.setAttribute("width", "320");
x.setAttribute("height", "240");
x.setAttribute("controls", "controls");
document.body.appendChild(x);
</code>```

Body:
Updated (and simplest) way to achieve this (since Google searches are leading here):

var x = document.createElement("VIDEO");

if (x.canPlayType("video/mp4")) {
    x.setAttribute("src","movie.mp4");
} else {
    x.setAttribute("src","movie.ogg");
}

x.setAttribute("width", "320");
x.setAttribute("height", "240");
x.setAttribute("controls", "controls");
document.body.appendChild(x);


问:
Matlab: Why is the fill function not filling the area between two circles?
I'm trying to fill the intersecting area between two circles in Matlab. I've quite literally copied and pasted this piece of code from this article on Matlab Central.

```<code>t = linspace(0, 2*pi, 100);
cir = @(r,ctr) [r*cos(t)+ctr(1); r*sin(t)+ctr(2)]; % Circle Function
c1 = cir(1.0, [0; 0]);
c2 = cir(1.5, [1; 1]);
in1 = find(inpolygon(c1(1,:), c1(2,:), c2(1,:), c2(2,:))); % Circle #1 Points Inside Circle #2
in2 = find(inpolygon(c2(1,:), c2(2,:), c1(1,:), c1(2,:))); % Circle #2 Points Inside Circle #1
[fillx,ix] = sort([c1(1,in1) c2(1,in2)]); % Sort Points
filly = [c1(2,in1) (c2(2,in2))];
filly = filly(ix);
figure(1)
plot(c1(1,:), c1(2,:))
hold on
plot(c2(1,:), c2(2,:))
fill([fillx fliplr(fillx)], [filly fliplr(filly)], 'g', 'EdgeColor','none')
hold off
axis square
</code>```

What I end up with is the following image:

However, it should appear as this image:

Why is the area not being filled as it is in the example article?

答:
The code in the question does not work because it has some mistake in the order of the points in fillx and filly. We can see that if we set the 'EdgeColor' to be visible, and follow the peripheral line of the patch (see below, here reduced to 20 points, for the illustration). We can clearly see that the point of the polygon to be filled are ordered in a 'zig-zag' between the circles, so it has no area at all. I have numbered the vertices of the polygon taken from each circle to demonstrate in what order the fill function read them.

In order to fill with color all the intersection between the circles, we need to define the 'polygon' by the points on the circles that intersect (in1 and in2) in the right order. This means we want them to make a closed shape if an imaginary pencil is drawing a line between them in the same order they are given. Like this:

We start with 1 in one of the circles and continue until the numbers on that circle are ended, and then move to 1 on the other circle, and when we reach the end in the second circle we close the polygon by connecting the last point to the first one. As you can see in both figure above, the starting point and the end point of the circles are really close, so we get 2 numbers above each other.

How can we order the points correctly?

We start by getting in1 and in2 as described in the question. Let's take a look at in1:

```<code>in1 =
     1     2     3     4     5     6     7    19    20
</code>```

Those are the indices of the points from c1 to be taken, they appear to be in order, but contains a gap. This gap is because inpolygon checks the points by the order in c1, and the starting point of c1 is within the intersection region. So we get the first 7 points, then we are out of the intersection, and we go back in as we reach points 19 and 20. However, for our polygon, we need this points to start from the closest point to one of that places where the circle intersect and to go around the circle until we reach the second point of intersection.

To do that, we look for the 'gap' in the points order:

```<code>gap = find(diff(in1)>1);
</code>```

and reorder them correctly:

```<code>X1 = [c1(1,in1(gap+1:end)) c1(1,in1(1:gap))];
Y1 = [c1(2,in1(gap+1:end)) c1(2,in1(1:gap))];
</code>```

But, there may be no 'gap', as we see in in2:

```<code>in2 =
    11    12    13    14
</code>```

So we need to wrap this within an if to check if the points need to be reordered:

```<code>if ~isempty(gap)
    X1 = [c1(1,in1(gap+1:end)) c1(1,in1(1:gap))];
    Y1 = [c1(2,in1(gap+1:end)) c1(2,in1(1:gap))];
else
    X1 = c1(1,in1);
    Y1 = c1(2,in1);
end
</code>```

Now all we need to do it to concatenate X1 and X2 (for circle 2), and the same for the Ys, and use patch (which is like fill, but better) to draw it:

```<code>patch([X1 X2],[Y1 Y2],'g','EdgeColor','none')
</code>```

With 20 points the circle is not really a circle and the intersection is partially colored, so here is the full code and the result with 200 points:

```<code>t = linspace(0, 2*pi, 200);
cir = @(r,ctr) [r*cos(t)+ctr(1); r*sin(t)+ctr(2)]; % Circle Function
c1 = cir(1.0, [0; 0]);
c2 = cir(1.5, [1; 1]);
plot(c1(1,:), c1(2,:))
hold on
plot(c2(1,:), c2(2,:))
axis equal
in1 = find(inpolygon(c1(1,:), c1(2,:), c2(1,:), c2(2,:)));
in2 = find(inpolygon(c2(1,:), c2(2,:), c1(1,:), c1(2,:)));
gap = find(diff(in1)>1);
if ~isempty(gap)
    X1 = [c1(1,in1(gap+1:end)) c1(1,in1(1:gap))];
    Y1 = [c1(2,in1(gap+1:end)) c1(2,in1(1:gap))];
else
    X1 = c1(1,in1);
    Y1 = c1(2,in1);
end
gap = find(diff(in2)>1);
if ~isempty(gap)
    X2 = [c2(1,in2(gap+1:end)) c2(1,in2(1:gap))];
    Y2 = [c2(2,in2(gap+1:end)) c2(2,in2(1:gap))];
else
    X2 = c2(1,in2);
    Y2 = c2(2,in2);
end
patch([X1 X2],[Y1 Y2],'g','EdgeColor','none')
hold off
</code>```

All mentioned above could be replace with the use of convhull on the vertices that intersect and give the same result:

```<code>x = [c1(1,in1) c2(1,in2)]; % all x's for intersecting vertices
y = [c1(2,in1) c2(2,in2)]; % all y's for intersecting vertices
k = convhull(x,y); % calculate the convex polygon
patch(x(k),y(k),'g','EdgeColor','none')
</code>```

Body:
I'm trying to fill the intersecting area between two circles in Matlab. I've quite literally copied and pasted this piece of code from this article on Matlab Central.

t = linspace(0, 2*pi, 100);
cir = @(r,ctr) [r*cos(t)+ctr(1); r*sin(t)+ctr(2)]; % Circle Function
c1 = cir(1.0, [0; 0]);
c2 = cir(1.5, [1; 1]);
in1 = find(inpolygon(c1(1,:), c1(2,:), c2(1,:), c2(2,:))); % Circle #1 Points Inside Circle #2
in2 = find(inpolygon(c2(1,:), c2(2,:), c1(1,:), c1(2,:))); % Circle #2 Points Inside Circle #1
[fillx,ix] = sort([c1(1,in1) c2(1,in2)]); % Sort Points
filly = [c1(2,in1) (c2(2,in2))];
filly = filly(ix);
figure(1)
plot(c1(1,:), c1(2,:))
hold on
plot(c2(1,:), c2(2,:))
fill([fillx fliplr(fillx)], [filly fliplr(filly)], 'g', 'EdgeColor','none')
hold off
axis square

What I end up with is the following image:

However, it should appear as this image:

Why is the area not being filled as it is in the example article?

Body:
The code in the question does not work because it has some mistake in the order of the points in fillx and filly. We can see that if we set the 'EdgeColor' to be visible, and follow the peripheral line of the patch (see below, here reduced to 20 points, for the illustration). We can clearly see that the point of the polygon to be filled are ordered in a 'zig-zag' between the circles, so it has no area at all. I have numbered the vertices of the polygon taken from each circle to demonstrate in what order the fill function read them.

In order to fill with color all the intersection between the circles, we need to define the 'polygon' by the points on the circles that intersect (in1 and in2) in the right order. This means we want them to make a closed shape if an imaginary pencil is drawing a line between them in the same order they are given. Like this:

We start with 1 in one of the circles and continue until the numbers on that circle are ended, and then move to 1 on the other circle, and when we reach the end in the second circle we close the polygon by connecting the last point to the first one. As you can see in both figure above, the starting point and the end point of the circles are really close, so we get 2 numbers above each other.

How can we order the points correctly?

We start by getting in1 and in2 as described in the question. Let's take a look at in1:

in1 =
     1     2     3     4     5     6     7    19    20

Those are the indices of the points from c1 to be taken, they appear to be in order, but contains a gap. This gap is because inpolygon checks the points by the order in c1, and the starting point of c1 is within the intersection region. So we get the first 7 points, then we are out of the intersection, and we go back in as we reach points 19 and 20. However, for our polygon, we need this points to start from the closest point to one of that places where the circle intersect and to go around the circle until we reach the second point of intersection.

To do that, we look for the 'gap' in the points order:

gap = find(diff(in1)>1);

and reorder them correctly:

X1 = [c1(1,in1(gap+1:end)) c1(1,in1(1:gap))];
Y1 = [c1(2,in1(gap+1:end)) c1(2,in1(1:gap))];

But, there may be no 'gap', as we see in in2:

in2 =
    11    12    13    14

So we need to wrap this within an if to check if the points need to be reordered:

if ~isempty(gap)
    X1 = [c1(1,in1(gap+1:end)) c1(1,in1(1:gap))];
    Y1 = [c1(2,in1(gap+1:end)) c1(2,in1(1:gap))];
else
    X1 = c1(1,in1);
    Y1 = c1(2,in1);
end

Now all we need to do it to concatenate X1 and X2 (for circle 2), and the same for the Ys, and use patch (which is like fill, but better) to draw it:

patch([X1 X2],[Y1 Y2],'g','EdgeColor','none')

With 20 points the circle is not really a circle and the intersection is partially colored, so here is the full code and the result with 200 points:

t = linspace(0, 2*pi, 200);
cir = @(r,ctr) [r*cos(t)+ctr(1); r*sin(t)+ctr(2)]; % Circle Function
c1 = cir(1.0, [0; 0]);
c2 = cir(1.5, [1; 1]);
plot(c1(1,:), c1(2,:))
hold on
plot(c2(1,:), c2(2,:))
axis equal
in1 = find(inpolygon(c1(1,:), c1(2,:), c2(1,:), c2(2,:)));
in2 = find(inpolygon(c2(1,:), c2(2,:), c1(1,:), c1(2,:)));
gap = find(diff(in1)>1);
if ~isempty(gap)
    X1 = [c1(1,in1(gap+1:end)) c1(1,in1(1:gap))];
    Y1 = [c1(2,in1(gap+1:end)) c1(2,in1(1:gap))];
else
    X1 = c1(1,in1);
    Y1 = c1(2,in1);
end
gap = find(diff(in2)>1);
if ~isempty(gap)
    X2 = [c2(1,in2(gap+1:end)) c2(1,in2(1:gap))];
    Y2 = [c2(2,in2(gap+1:end)) c2(2,in2(1:gap))];
else
    X2 = c2(1,in2);
    Y2 = c2(2,in2);
end
patch([X1 X2],[Y1 Y2],'g','EdgeColor','none')
hold off

All mentioned above could be replace with the use of convhull on the vertices that intersect and give the same result:

x = [c1(1,in1) c2(1,in2)]; % all x's for intersecting vertices
y = [c1(2,in1) c2(2,in2)]; % all y's for intersecting vertices
k = convhull(x,y); % calculate the convex polygon
patch(x(k),y(k),'g','EdgeColor','none')


问:
CSS - Pointer on element, but default cursor (arrow) on :after?
I have an element with cursor: pointer;, and would like for its :after pseudo-element to have cursor: default; (the normal mouse arrow).

.one {
  display: inline-block;
  padding: 0;
  margin: 4px;
  color: #FFF;
  font-size: 14px;
  background: red;
}

.two {
  cursor: pointer;
}

.two:after {
  content: "\2027";
  padding: 0 5px;
  background: aqua;
  color: #000;
  cursor: default;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="one">
  <div class="two">
    Text
  </div>
</div></code>```

But no matter what I set cursor to in the :after pseudo-element, it always displays pointer.

Here is a Fiddle of the issue

None of the SO posts that I can find provide a solution to the issue.

Edit #1

Based on comment, this might be a Safari-only issue. Tested in Chrome, and all is well.

答:
This seems to be a know issue in Safari, others having this problem too.

What you can do is, put the content of your "two" class in another html tag and apply the style on those. Like this https://jsfiddle.net/cornelraiu/L5pyr342/1/:

HTML:

```<code><div class="one">
    <div class="two">
        <span class="pointer">
            Text
        </span>
    </div>
</div>
</code>```

CSS:

```<code>.one {
    display: inline-block;
    padding: 0;
    margin: 4px;
    color: #FFF;
    font-size: 14px;
    background: red;
}

.pointer {
    cursor: pointer;
}
.two:after {
    content: "\2027";
    padding: 0 5px;
    background: aqua;
    color: #000;
}
</code>```

I know this is a "hack" but it works on all browsers.

EDIT: There seems to be an answer to the same issue here but on an old version of Chrome and still present on the newer versions of Safari: cursor: pointer doesn't work on :after element? resolved in the same way I have it :)

Body:
I have an element with cursor: pointer;, and would like for its :after pseudo-element to have cursor: default; (the normal mouse arrow).

.one {
  display: inline-block;
  padding: 0;
  margin: 4px;
  color: #FFF;
  font-size: 14px;
  background: red;
}

.two {
  cursor: pointer;
}

.two:after {
  content: "\2027";
  padding: 0 5px;
  background: aqua;
  color: #000;
  cursor: default;
}

    Text

But no matter what I set cursor to in the :after pseudo-element, it always displays pointer.

Here is a Fiddle of the issue

None of the SO posts that I can find provide a solution to the issue.

Edit #1

Based on comment, this might be a Safari-only issue. Tested in Chrome, and all is well.

Body:
This seems to be a know issue in Safari, others having this problem too.

What you can do is, put the content of your "two" class in another html tag and apply the style on those. Like this https://jsfiddle.net/cornelraiu/L5pyr342/1/:

HTML:

<div class="one">
    <div class="two">
        <span class="pointer">
            Text
        </span>
    </div>
</div>

CSS:

.one {
    display: inline-block;
    padding: 0;
    margin: 4px;
    color: #FFF;
    font-size: 14px;
    background: red;
}

.pointer {
    cursor: pointer;
}
.two:after {
    content: "\2027";
    padding: 0 5px;
    background: aqua;
    color: #000;
}

I know this is a "hack" but it works on all browsers.

EDIT: There seems to be an answer to the same issue here but on an old version of Chrome and still present on the newer versions of Safari: cursor: pointer doesn't work on :after element? resolved in the same way I have it :)


问:
Is there a way to pause a jenkins pipeline periodic build?
I have periodic builds set up with a jenkins pipeline job and I want to pause the automated builds temporarily. One option is to uncheck the "build periodically" checkbox, but then the schedule information gets cleared out. Is there a way to put the builds on hold but preserve the schedule info?

Update:
Adding screenshot of main pipeline job page.

答:
There is the button Disable Project top-right on a project's main page.

UPDATE:

And there's General → Build Triggers → ☐ Disable this project in a pipeline project's config.


问:
Get Assembly From C# Project File
I am trying to make a simple WinForm tool to assist with code generation, and I was wondering if it was possible to get the Assembly of one project into a different one that presides in a different solution.  I want the form to show all of the classes and then properties for each class, and the easiest/best way I can think of doing that is like:

```<code>private Type[] GetTypesInNamespace(Assembly assembly, string nameSpace)
{
    return assembly.GetTypes().Where(t => String.Equals(t.Namespace, nameSpace, StringComparison.Ordinal)).ToArray();
}
</code>```

If the user selects a .csproj file, is it possible to get the Assembly?  Or is there a different way to get the classes/properties without recursively searching the project folder and parsing the files?

答:
The csproj file will contain the assembly name and the output directory.

```<code><Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <AssemblyName>MyAppAssemblyNameOnly</AssemblyName>
    <TargetFrameworkVersion>v4.6.2</TargetFrameworkVersion>
  </PropertyGroup>
</Project>
</code>```

You'll have to add .dll suffix to it to get the actual file name.

The Output Path can be found in the different Configuration <PropertyGroup> nodes.

```<code><PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <PlatformTarget>x86</PlatformTarget>
    <Optimize>false</Optimize>
    <OutputPath>bin\Debug\</OutputPath>
</PropertyGroup>
</code>```

There's a couple of problems I can think of right off the bat.

The DLL may not be built and so it won't exist.

There are many different configurations with there being Debug and Release by default. You'll have to decide which one to look for.

For ease, you may just want to make the user feed you a DLL if the project is not part of the solution and you don't actually need anything else.

You can also look into Roslyn and parse the files with Roslyn to get you all of the information you need too.

Here's an example straight from their page. Seems super simple and straightforward. Kind of larger than I want, but don't want to just give a single link-only suggestion.

```<code>class Program
{
    static void Main(string[] args)
    {
        SyntaxTree tree = CSharpSyntaxTree.ParseText(
                @"using System;
                using System.Collections;
                using System.Linq;
                using System.Text;

                namespace HelloWorld
                {
                class Program
                {
                    static void Main(string[] args)
                    {
                        Console.WriteLine(""Hello, World!"");
                    }
                }
                }");

        var root = (CompilationUnitSyntax)tree.GetRoot();

        var firstMember = root.Members[0];

        var helloWorldDeclaration = (NamespaceDeclarationSyntax)firstMember;

        var programDeclaration = (ClassDeclarationSyntax)helloWorldDeclaration.Members[0];

        var mainDeclaration = (MethodDeclarationSyntax)programDeclaration.Members[0];

        var argsParameter = mainDeclaration.ParameterList.Parameters[0];

    }
}
</code>```

Title: Get Assembly From C# Project File

Body:
I am trying to make a simple WinForm tool to assist with code generation, and I was wondering if it was possible to get the Assembly of one project into a different one that presides in a different solution.  I want the form to show all of the classes and then properties for each class, and the easiest/best way I can think of doing that is like:

private Type[] GetTypesInNamespace(Assembly assembly, string nameSpace)
{
    return assembly.GetTypes().Where(t => String.Equals(t.Namespace, nameSpace, StringComparison.Ordinal)).ToArray();
}

If the user selects a .csproj file, is it possible to get the Assembly?  Or is there a different way to get the classes/properties without recursively searching the project folder and parsing the files?

Body:
The csproj file will contain the assembly name and the output directory.

<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <AssemblyName>MyAppAssemblyNameOnly</AssemblyName>
    <TargetFrameworkVersion>v4.6.2</TargetFrameworkVersion>
  </PropertyGroup>
</Project>

You'll have to add .dll suffix to it to get the actual file name.

The Output Path can be found in the different Configuration <PropertyGroup> nodes.

<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <PlatformTarget>x86</PlatformTarget>
    <Optimize>false</Optimize>
    <OutputPath>bin\Debug\</OutputPath>
</PropertyGroup>

There's a couple of problems I can think of right off the bat.

The DLL may not be built and so it won't exist.

There are many different configurations with there being Debug and Release by default. You'll have to decide which one to look for.

For ease, you may just want to make the user feed you a DLL if the project is not part of the solution and you don't actually need anything else.

You can also look into Roslyn and parse the files with Roslyn to get you all of the information you need too.

Here's an example straight from their page. Seems super simple and straightforward. Kind of larger than I want, but don't want to just give a single link-only suggestion.

class Program
{
    static void Main(string[] args)
    {
        SyntaxTree tree = CSharpSyntaxTree.ParseText(
                @"using System;
                using System.Collections;
                using System.Linq;
                using System.Text;

                namespace HelloWorld
                {
                class Program
                {
                    static void Main(string[] args)
                    {
                        Console.WriteLine(""Hello, World!"");
                    }
                }
                }");

        var root = (CompilationUnitSyntax)tree.GetRoot();

        var firstMember = root.Members[0];

        var helloWorldDeclaration = (NamespaceDeclarationSyntax)firstMember;

        var programDeclaration = (ClassDeclarationSyntax)helloWorldDeclaration.Members[0];

        var mainDeclaration = (MethodDeclarationSyntax)programDeclaration.Members[0];

        var argsParameter = mainDeclaration.ParameterList.Parameters[0];

    }
}


问:
Parsing and storing xml into MSSQL database table
I am parsing xml and creating Java object out of it.
Now, how can i serialize that object and store it into a database

I am parsing xml object as follows

```<code>    outputStr = IOUtils.toString(xmlfile.getInputStream(),"UTF-8");
    Report = XMLUtil.toObject(outputStr, Customer.class);
</code>```

I want to store Report object into database

答:
The following article is not about Java and MSSQL, it's about C# and MSSQL.

But the principle, I think, is clear:

How to Save Object Graph in Master-Detail Relationship with One Stored Procedure.

Or just send the xml data right to a stored procedure:

Saving Master-Details form using XML.

Body:
I am parsing xml and creating Java object out of it.
Now, how can i serialize that object and store it into a database

I am parsing xml object as follows

    outputStr = IOUtils.toString(xmlfile.getInputStream(),"UTF-8");
    Report = XMLUtil.toObject(outputStr, Customer.class);

I want to store Report object into database