问:
Application crashed when trying to load Json using retrofit to a recyclerView in a fragment in a tablayout
so to be more specific i have an activity which contains a tablayout each tab should basically load a standalone fragment containing a recycler view an i want the data retrieved from the api using retrofit to be loaded in the recyclerView bases on user action

so this is the activity :

```<code>public class RestaurantLogoView extends AppCompatActivity implements LiteFragment.OnFragmentInteractionListener, RegularFragment.OnFragmentInteractionListener, View.OnClickListener {
    private static final String TAG = "RestaurantLogoView";
        public static ProgressDialog progressDialog;
    //TODO
    public static View.OnClickListener myOnClickListener;

    private String chosenArea;
    TextView locationTv;

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

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        ViewPager mViewPager = (ViewPager) findViewById(R.id.container);
        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(mViewPager);
        SectionsPagerAdapter pagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(),getApplicationContext());
        //remove this if you still didnt get data in the fragment
        mViewPager.setAdapter(pagerAdapter);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(view -> Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                .setAction("Action", null).show());

        locationTv = (TextView) findViewById(R.id.location_tv);
        chosenArea = (String) getIntent().getSerializableExtra("Object");
        locationTv.setText(chosenArea);
        locationTv.setOnClickListener(this);
    }

    @Override
    public void onFragmentInteraction(Uri uri) {
        //TODO i added this lately not sure what its supposed to do but consider removing it
    }

    /**
     * Called when a view has been clicked.
     *
     * @param v The view that was clicked.
     */

//
//
//    @Override
//    public boolean onCreateOptionsMenu(Menu menu) {
//        getMenuInflater().inflate(R.menu.menu_restaurant_main_view, menu);
//        return true;
//    }
    @Override
    public void onClick(View v) {
        if (v == locationTv) {
            Intent o = new Intent(getApplicationContext(), AreaList.class);
            startActivity(o);
            finish();
        } else {
            Toast.makeText(getApplicationContext(), "What do you want to eat today?", Toast.LENGTH_LONG).show();
        }
    }

    private class SectionsPagerAdapter extends FragmentStatePagerAdapter {

        String tabTitles[] = {getString(R.string.regular), getString(R.string.lite)};
        Context context;

        SectionsPagerAdapter(FragmentManager fm, Context context) {
            super(fm);
            this.context = context;
        }

        @Override
        public Fragment getItem(int position) {
            switch (position) {
                case 0:
                    new RegularFragment();
                    return RegularFragment.newInstance(TAG, position);
                case 1:
                    new LiteFragment();
                    return LiteFragment.newInstance(TAG, position);

                default:
                    return null;
            }
        }

        @Override
        public int getCount() {
            return tabTitles.length;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            // Generate title based on item position
            return tabTitles[position];
        }

    }

}
`
</code>```

This is the first fragment which should be shown in my first tab

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

    OnFragmentInteractionListener mListener;

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    public static final String REGULAR_PARAM1 = "lite";
    View RootView;
    List<RestaurantModel> regularRestaurants;
    private RecyclerView recyclerView;
    RecyclerViewAdapter adapter;
    private Call<RestaurantElKbeer> callbackCall;
    private String TAG = "RegularFragment";
    //new
    public static final String ARG_PAGE = "ARG_PAGE";

    private int mPage;

    public RegularFragment() {
    }

    // TODO: Rename and change types and number of parameters
    public static Fragment newInstance(String param, int position) {

        //TODO it might be important i didnt know why i created it
        Fragment fragment = new RegularFragment();
        Bundle args = new Bundle();
        args.putInt(param, position);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        regularRestaurants = requestRegularList();
        mPage = getArguments().getInt(ARG_PAGE);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        //new
        RootView = inflater.inflate(R.layout.fragment_regular, container, false);
        recyclerView = (RecyclerView) RootView.findViewById(R.id.recyclerView);
        recyclerView.setHasFixedSize(true);
        initializeAdapter();
        LinearLayoutManager llm = new LinearLayoutManager(this.getContext());
        recyclerView.setLayoutManager(llm);
        return RootView;
    }

    private void initializeAdapter() {
        adapter = new RecyclerViewAdapter(getActivity(), regularRestaurants);
        recyclerView.setAdapter(adapter);
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    private List<RestaurantModel> requestRegularList() {
        List<RestaurantModel> myRestaurantsList = new ArrayList<>();
        RestAdapter restAdapter = new RestAdapter();
        API api = restAdapter.getApi();
        // URL: https://betaweb.jeebley.com/services_new/services.php?action=search&langId=1&countryId=21&cuisineType=1&cuisineId=all&areaId=1&delvType=1

        Call<RestaurantElKbeer> call = api.getRestaurants("search", "1", "21", "all", "1", "1");
        call.enqueue(new Callback<RestaurantElKbeer>() {
            @Override
            public void onResponse(@NonNull Call<RestaurantElKbeer> call, @NonNull Response<RestaurantElKbeer> response) {
                if (response.isSuccessful()) {
                    ArrayList<String> names = new ArrayList<String>();
                    RestaurantElKbeer restaurantResponse = response.body();
                   List<RestaurantModel> list = restaurantResponse.getRestaurantModel();
                if(list != null && !list.isEmpty()){
                    for (int i = 0; i < list.size(); i++) {
                        String name;
                        name = list.get(i).getRName();
                        names.add(name);
                        Log.i(TAG, "onResponse: " + names.get(i));
                    }

                }
                else
                    {
                        Log.i(TAG, "onResponse(regular): RestaurantModelList is null");
                    }
                    RecyclerViewAdapter adapter = new RecyclerViewAdapter(getContext(), list);
                    recyclerView.setAdapter(adapter);
                    recyclerView.setOnClickListener(v -> {
                        Intent i = new Intent(getContext(), ChooseYourLanguage.class);
                        i.putExtra("Object", getId());
                        startActivityForResult(i, 0);
                    });
                }
            }

            @Override
            public void onFailure(@NonNull Call<RestaurantElKbeer> call, Throwable t) {
                Log.i(TAG, "onFailure: failed RegularFragmentCall");
            }
        });
        return myRestaurantsList;
    }

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

    /**
     * Initialize the contents of the Fragment host's standard options menu.  You
     * should place your menu items in to <var>menu</var>.  For this method
     * to be called, you must have first called {@link #setHasOptionsMenu}.  See
     * {@link RestaurantLogoView#onCreateOptionsMenu(Menu) Activity.onCreateOptionsMenu}
     * for more information.
     *
     * @param menu     The options menu in which you place your items.
     * @param inflater
     * @see #setHasOptionsMenu
     * @see #onPrepareOptionsMenu
     * @see #onOptionsItemSelected
     */
    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public void setHasOptionsMenu(boolean hasMenu) {
        super.setHasOptionsMenu(hasMenu);
    }
}
</code>```

And this is my RecyclerViewAdapter

```<code>public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
    private List<RestaurantModel> items;
    private Context ctx;

    public RecyclerViewAdapter(Context context, List<RestaurantModel> items) {
        this.ctx = context;
        this.items=items;
    }

    private OnItemClickListener mOnItemClickListener;
    private SharedPref sharedPref;

    public interface OnItemClickListener {
        void onItemClick(View view, RestaurantModel obj, int position);
    }

    public void setOnItemClickListener(final OnItemClickListener mItemClickListener) {
        this.mOnItemClickListener = mItemClickListener;
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {

        CardView cv;
        TextView title;
        TextView description;
        ImageView imageView;

        ViewHolder(View itemView) {
            super(itemView);
            cv = (CardView) itemView.findViewById(R.id.restaurant_card_view);
            title = (TextView) itemView.findViewById(R.id.restaurantName_section_label);
            description = (TextView) itemView.findViewById(R.id.section_label2);
            imageView = (ImageView) itemView.findViewById(R.id.restaurantImageView);
        }
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View v = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.restaurant_card_layout, parent, false);
        return new ViewHolder(v);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position, List<Object> payloads) {
        super.onBindViewHolder(holder, position, payloads);
        RestaurantModel p = (RestaurantModel) payloads.get(position);
        holder.title.setText(p.getRName());
        if (!p.getDelvType().equals("1")) {
            holder.description.setText(p.getJDeliveryTime() + " " + p.getRMinOrderAmt() + " " + p.getJDeliveryCharge());
        } else {
            holder.description.setText(p.getRDeliveryTime() + " " + p.getRMinOrderAmt() + " " + p.getRDeliveryCharge());
            holder.imageView.setImageResource(R.mipmap.ic_launcher);
        }
       holder.cv.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
               Log.i("RecyclerViewAdapter", "onClick: replace with intent to send Restaurant data");
           }
       });
    }

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

        final RestaurantModel p = items.get(position);
        holder.title.setText(p.getRName());
        if (!p.getDelvType().equals("1")) {
            holder.description.setText(p.getJDeliveryTime() + " " + p.getRMinOrderAmt() + " " + p.getJDeliveryCharge());
        } else {
            holder.description.setText(p.getRDeliveryTime() + " " + p.getRMinOrderAmt() + " " + p.getRDeliveryCharge());

        }
        holder.cv.setOnClickListener(view -> {
                mOnItemClickListener.onItemClick(view, p, position);

        });
    }

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

    public interface OnLoadMoreListener {
        void onLoadMore(int current_page);
    }
}
</code>```

This is the exception i'm getting

**

06-06 00:11:05.215 10571-10571/com.jeebley.jeebley E/AndroidRuntime: FATAL EXCEPTION: main
                                                                       Process: com.jeebley.jeebley, PID: 10571
                                                                       java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
                                                                           at com.jeebley.jeebley.adapters.RecyclerViewAdapter.getItemCount(RecyclerViewAdapter.java:109)
                                                                           at android.support.v7.widget.RecyclerView.dispatchLayoutStep1(RecyclerView.java:3493)
                                                                           at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3310)
                                                                           at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3844)
                                                                           at android.view.View.layout(View.java:17687)
                                                                           at android.view.ViewGroup.layout(ViewGroup.java:5631)
                                                                           at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1079)
                                                                           at android.view.View.layout(View.java:17687)
                                                                           at android.view.ViewGroup.layout(ViewGroup.java:5631)
                                                                           at android.support.v4.view.ViewPager.onLayout(ViewPager.java:1795)
                                                                           at android.view.View.layout(View.java:17687)
                                                                           at android.view.ViewGroup.layout(ViewGroup.java:5631)
                                                                           at android.support.design.widget.HeaderScrollingViewBehavior.layoutChild(HeaderScrollingViewBehavior.java:131)
                                                                           at android.support.design.widget.ViewOffsetBehavior.onLayoutChild(ViewOffsetBehavior.java:42)
                                                                           at android.support.design.widget.AppBarLayout$ScrollingViewBehavior.onLayoutChild(AppBarLayout.java:1391)
                                                                           at android.support.design.widget.CoordinatorLayout.onLayout(CoordinatorLayout.java:870)
                                                                           at android.view.View.layout(View.java:17687)
                                                                           at android.view.ViewGroup.layout(ViewGroup.java:5631)
                                                                           at android.widget.FrameLayout.layoutChildren(FrameLayout.java:325)
                                                                           at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
                                                                           at android.view.View.layout(View.java:17687)
                                                                           at android.view.ViewGroup.layout(ViewGroup.java:5631)
                                                                           at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1762)
                                                                           at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1606)
                                                                           at android.widget.LinearLayout.onLayout(LinearLayout.java:1515)
                                                                           at android.view.View.layout(View.java:17687)
                                                                           at android.view.ViewGroup.layout(ViewGroup.java:5631)
                                                                           at android.widget.FrameLayout.layoutChildren(FrameLayout.java:325)
                                                                           at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
                                                                           at android.view.View.layout(View.java:17687)
                                                                           at android.view.ViewGroup.layout(ViewGroup.java:5631)
                                                                           at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1762)
                                                                           at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1606)
                                                                           at android.widget.LinearLayout.onLayout(LinearLayout.java:1515)
                                                                           at android.view.View.layout(View.java:17687)
                                                                           at android.view.ViewGroup.layout(ViewGroup.java:5631)
                                                                           at android.widget.FrameLayout.layoutChildren(FrameLayout.java:325)
                                                                           at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
                                                                           at com.android.internal.policy.DecorView.onLayout(DecorView.java:774)
                                                                           at android.view.View.layout(View.java:17687)
                                                                           at android.view.ViewGroup.layout(ViewGroup.java:5631)
                                                                           at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2511)
                                                                           at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2226)
                                                                           at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1364)
                                                                           at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6763)
                                                                           at android.view.Choreographer$CallbackRecord.run(Choreographer.java:923)
                                                                           at android.view.Choreographer.doCallbacks(Choreographer.java:735)
                                                                           at android.view.Choreographer.doFrame(Choreographer.java:667)
                                                                           at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:909)
                                                                           at android.os.Handler.handleCallback(Handler.java:761)
                                                                           at android.os.Handler.dispatchMessage(Handler.java:98)
                                                                           at android.os.Looper.loop(Looper.java:156)
                                                                           at android.app.ActivityThread.main(ActivityThread.java:6524)
                                                                           at java.lang.reflect.Method.invoke(Native Method)
                                                                           at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:941)
                                                                           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:831)
  06-06 00:11:05.238 10571-10571/com.jeebley.jeebley I/Process: Sending signal. PID: 10571 SIG: 9

**

答:
This is what you are doing:

```<code>List<RestaurantModel> list = restaurantResponse.getRestaurantModel();
for (int i = 0; i < list.size(); i++) {
    String name;
    name = list.get(i).getRName();
    names.add(name);
    Log.i(TAG, "onResponse: " + names.get(i));
}
</code>```

As far as I can see in the error trace, your problem is that list is null when you ask for the size, so you should ask if the list is not null before:

```<code>...
List<RestaurantModel> list = restaurantResponse.getRestaurantModel();
if(list != null && !list.isEmpty()){
    for (int i = 0; i < list.size(); i++) {
        String name;
        name = list.get(i).getRName();
        names.add(name);
        Log.i(TAG, "onResponse: " + names.get(i));
    }
}
...
</code>```

EDIT:

In your adapter, modify this method:

```<code>@Override
public int getItemCount() {
    return items!=null ? items.size() : 0;
}
</code>```

The method getItemCount() is being called before the array initialization inside the adapter life cycle. That's why you need to check if your list is null or not to avoid npe.

Body:
so to be more specific i have an activity which contains a tablayout each tab should basically load a standalone fragment containing a recycler view an i want the data retrieved from the api using retrofit to be loaded in the recyclerView bases on user action

so this is the activity :

public class RestaurantLogoView extends AppCompatActivity implements LiteFragment.OnFragmentInteractionListener, RegularFragment.OnFragmentInteractionListener, View.OnClickListener {
    private static final String TAG = "RestaurantLogoView";
        public static ProgressDialog progressDialog;
    //TODO
    public static View.OnClickListener myOnClickListener;

    private String chosenArea;
    TextView locationTv;

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

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        ViewPager mViewPager = (ViewPager) findViewById(R.id.container);
        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(mViewPager);
        SectionsPagerAdapter pagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(),getApplicationContext());
        //remove this if you still didnt get data in the fragment
        mViewPager.setAdapter(pagerAdapter);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(view -> Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                .setAction("Action", null).show());

        locationTv = (TextView) findViewById(R.id.location_tv);
        chosenArea = (String) getIntent().getSerializableExtra("Object");
        locationTv.setText(chosenArea);
        locationTv.setOnClickListener(this);
    }

    @Override
    public void onFragmentInteraction(Uri uri) {
        //TODO i added this lately not sure what its supposed to do but consider removing it
    }

    /**
     * Called when a view has been clicked.
     *
     * @param v The view that was clicked.
     */

//
//
//    @Override
//    public boolean onCreateOptionsMenu(Menu menu) {
//        getMenuInflater().inflate(R.menu.menu_restaurant_main_view, menu);
//        return true;
//    }
    @Override
    public void onClick(View v) {
        if (v == locationTv) {
            Intent o = new Intent(getApplicationContext(), AreaList.class);
            startActivity(o);
            finish();
        } else {
            Toast.makeText(getApplicationContext(), "What do you want to eat today?", Toast.LENGTH_LONG).show();
        }
    }

    private class SectionsPagerAdapter extends FragmentStatePagerAdapter {

        String tabTitles[] = {getString(R.string.regular), getString(R.string.lite)};
        Context context;

        SectionsPagerAdapter(FragmentManager fm, Context context) {
            super(fm);
            this.context = context;
        }

        @Override
        public Fragment getItem(int position) {
            switch (position) {
                case 0:
                    new RegularFragment();
                    return RegularFragment.newInstance(TAG, position);
                case 1:
                    new LiteFragment();
                    return LiteFragment.newInstance(TAG, position);

                default:
                    return null;
            }
        }

        @Override
        public int getCount() {
            return tabTitles.length;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            // Generate title based on item position
            return tabTitles[position];
        }

    }

}
`

This is the first fragment which should be shown in my first tab

public class RegularFragment extends Fragment {

    OnFragmentInteractionListener mListener;

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    public static final String REGULAR_PARAM1 = "lite";
    View RootView;
    List<RestaurantModel> regularRestaurants;
    private RecyclerView recyclerView;
    RecyclerViewAdapter adapter;
    private Call<RestaurantElKbeer> callbackCall;
    private String TAG = "RegularFragment";
    //new
    public static final String ARG_PAGE = "ARG_PAGE";

    private int mPage;

    public RegularFragment() {
    }

    // TODO: Rename and change types and number of parameters
    public static Fragment newInstance(String param, int position) {

        //TODO it might be important i didnt know why i created it
        Fragment fragment = new RegularFragment();
        Bundle args = new Bundle();
        args.putInt(param, position);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        regularRestaurants = requestRegularList();
        mPage = getArguments().getInt(ARG_PAGE);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        //new
        RootView = inflater.inflate(R.layout.fragment_regular, container, false);
        recyclerView = (RecyclerView) RootView.findViewById(R.id.recyclerView);
        recyclerView.setHasFixedSize(true);
        initializeAdapter();
        LinearLayoutManager llm = new LinearLayoutManager(this.getContext());
        recyclerView.setLayoutManager(llm);
        return RootView;
    }

    private void initializeAdapter() {
        adapter = new RecyclerViewAdapter(getActivity(), regularRestaurants);
        recyclerView.setAdapter(adapter);
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    private List<RestaurantModel> requestRegularList() {
        List<RestaurantModel> myRestaurantsList = new ArrayList<>();
        RestAdapter restAdapter = new RestAdapter();
        API api = restAdapter.getApi();
        // URL: https://betaweb.jeebley.com/services_new/services.php?action=search&langId=1&countryId=21&cuisineType=1&cuisineId=all&areaId=1&delvType=1

        Call<RestaurantElKbeer> call = api.getRestaurants("search", "1", "21", "all", "1", "1");
        call.enqueue(new Callback<RestaurantElKbeer>() {
            @Override
            public void onResponse(@NonNull Call<RestaurantElKbeer> call, @NonNull Response<RestaurantElKbeer> response) {
                if (response.isSuccessful()) {
                    ArrayList<String> names = new ArrayList<String>();
                    RestaurantElKbeer restaurantResponse = response.body();
                   List<RestaurantModel> list = restaurantResponse.getRestaurantModel();
                if(list != null && !list.isEmpty()){
                    for (int i = 0; i < list.size(); i++) {
                        String name;
                        name = list.get(i).getRName();
                        names.add(name);
                        Log.i(TAG, "onResponse: " + names.get(i));
                    }

                }
                else
                    {
                        Log.i(TAG, "onResponse(regular): RestaurantModelList is null");
                    }
                    RecyclerViewAdapter adapter = new RecyclerViewAdapter(getContext(), list);
                    recyclerView.setAdapter(adapter);
                    recyclerView.setOnClickListener(v -> {
                        Intent i = new Intent(getContext(), ChooseYourLanguage.class);
                        i.putExtra("Object", getId());
                        startActivityForResult(i, 0);
                    });
                }
            }

            @Override
            public void onFailure(@NonNull Call<RestaurantElKbeer> call, Throwable t) {
                Log.i(TAG, "onFailure: failed RegularFragmentCall");
            }
        });
        return myRestaurantsList;
    }

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

    /**
     * Initialize the contents of the Fragment host's standard options menu.  You
     * should place your menu items in to <var>menu</var>.  For this method
     * to be called, you must have first called {@link #setHasOptionsMenu}.  See
     * {@link RestaurantLogoView#onCreateOptionsMenu(Menu) Activity.onCreateOptionsMenu}
     * for more information.
     *
     * @param menu     The options menu in which you place your items.
     * @param inflater
     * @see #setHasOptionsMenu
     * @see #onPrepareOptionsMenu
     * @see #onOptionsItemSelected
     */
    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public void setHasOptionsMenu(boolean hasMenu) {
        super.setHasOptionsMenu(hasMenu);
    }
}

And this is my RecyclerViewAdapter

public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
    private List<RestaurantModel> items;
    private Context ctx;

    public RecyclerViewAdapter(Context context, List<RestaurantModel> items) {
        this.ctx = context;
        this.items=items;
    }

    private OnItemClickListener mOnItemClickListener;
    private SharedPref sharedPref;

    public interface OnItemClickListener {
        void onItemClick(View view, RestaurantModel obj, int position);
    }

    public void setOnItemClickListener(final OnItemClickListener mItemClickListener) {
        this.mOnItemClickListener = mItemClickListener;
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {

        CardView cv;
        TextView title;
        TextView description;
        ImageView imageView;

        ViewHolder(View itemView) {
            super(itemView);
            cv = (CardView) itemView.findViewById(R.id.restaurant_card_view);
            title = (TextView) itemView.findViewById(R.id.restaurantName_section_label);
            description = (TextView) itemView.findViewById(R.id.section_label2);
            imageView = (ImageView) itemView.findViewById(R.id.restaurantImageView);
        }
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View v = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.restaurant_card_layout, parent, false);
        return new ViewHolder(v);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position, List<Object> payloads) {
        super.onBindViewHolder(holder, position, payloads);
        RestaurantModel p = (RestaurantModel) payloads.get(position);
        holder.title.setText(p.getRName());
        if (!p.getDelvType().equals("1")) {
            holder.description.setText(p.getJDeliveryTime() + " " + p.getRMinOrderAmt() + " " + p.getJDeliveryCharge());
        } else {
            holder.description.setText(p.getRDeliveryTime() + " " + p.getRMinOrderAmt() + " " + p.getRDeliveryCharge());
            holder.imageView.setImageResource(R.mipmap.ic_launcher);
        }
       holder.cv.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
               Log.i("RecyclerViewAdapter", "onClick: replace with intent to send Restaurant data");
           }
       });
    }

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

        final RestaurantModel p = items.get(position);
        holder.title.setText(p.getRName());
        if (!p.getDelvType().equals("1")) {
            holder.description.setText(p.getJDeliveryTime() + " " + p.getRMinOrderAmt() + " " + p.getJDeliveryCharge());
        } else {
            holder.description.setText(p.getRDeliveryTime() + " " + p.getRMinOrderAmt() + " " + p.getRDeliveryCharge());

        }
        holder.cv.setOnClickListener(view -> {
                mOnItemClickListener.onItemClick(view, p, position);

        });
    }

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

    public interface OnLoadMoreListener {
        void onLoadMore(int current_page);
    }
}

This is the exception i'm getting

**

06-06 00:11:05.215 10571-10571/com.jeebley.jeebley E/AndroidRuntime: FATAL EXCEPTION: main
                                                                       Process: com.jeebley.jeebley, PID: 10571
                                                                       java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
                                                                           at com.jeebley.jeebley.adapters.RecyclerViewAdapter.getItemCount(RecyclerViewAdapter.java:109)
                                                                           at android.support.v7.widget.RecyclerView.dispatchLayoutStep1(RecyclerView.java:3493)
                                                                           at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3310)
                                                                           at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3844)
                                                                           at android.view.View.layout(View.java:17687)
                                                                           at android.view.ViewGroup.layout(ViewGroup.java:5631)
                                                                           at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1079)
                                                                           at android.view.View.layout(View.java:17687)
                                                                           at android.view.ViewGroup.layout(ViewGroup.java:5631)
                                                                           at android.support.v4.view.ViewPager.onLayout(ViewPager.java:1795)
                                                                           at android.view.View.layout(View.java:17687)
                                                                           at android.view.ViewGroup.layout(ViewGroup.java:5631)
                                                                           at android.support.design.widget.HeaderScrollingViewBehavior.layoutChild(HeaderScrollingViewBehavior.java:131)
                                                                           at android.support.design.widget.ViewOffsetBehavior.onLayoutChild(ViewOffsetBehavior.java:42)
                                                                           at android.support.design.widget.AppBarLayout$ScrollingViewBehavior.onLayoutChild(AppBarLayout.java:1391)
                                                                           at android.support.design.widget.CoordinatorLayout.onLayout(CoordinatorLayout.java:870)
                                                                           at android.view.View.layout(View.java:17687)
                                                                           at android.view.ViewGroup.layout(ViewGroup.java:5631)
                                                                           at android.widget.FrameLayout.layoutChildren(FrameLayout.java:325)
                                                                           at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
                                                                           at android.view.View.layout(View.java:17687)
                                                                           at android.view.ViewGroup.layout(ViewGroup.java:5631)
                                                                           at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1762)
                                                                           at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1606)
                                                                           at android.widget.LinearLayout.onLayout(LinearLayout.java:1515)
                                                                           at android.view.View.layout(View.java:17687)
                                                                           at android.view.ViewGroup.layout(ViewGroup.java:5631)
                                                                           at android.widget.FrameLayout.layoutChildren(FrameLayout.java:325)
                                                                           at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
                                                                           at android.view.View.layout(View.java:17687)
                                                                           at android.view.ViewGroup.layout(ViewGroup.java:5631)
                                                                           at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1762)
                                                                           at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1606)
                                                                           at android.widget.LinearLayout.onLayout(LinearLayout.java:1515)
                                                                           at android.view.View.layout(View.java:17687)
                                                                           at android.view.ViewGroup.layout(ViewGroup.java:5631)
                                                                           at android.widget.FrameLayout.layoutChildren(FrameLayout.java:325)
                                                                           at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
                                                                           at com.android.internal.policy.DecorView.onLayout(DecorView.java:774)
                                                                           at android.view.View.layout(View.java:17687)
                                                                           at android.view.ViewGroup.layout(ViewGroup.java:5631)
                                                                           at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2511)
                                                                           at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2226)
                                                                           at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1364)
                                                                           at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6763)
                                                                           at android.view.Choreographer$CallbackRecord.run(Choreographer.java:923)
                                                                           at android.view.Choreographer.doCallbacks(Choreographer.java:735)
                                                                           at android.view.Choreographer.doFrame(Choreographer.java:667)
                                                                           at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:909)
                                                                           at android.os.Handler.handleCallback(Handler.java:761)
                                                                           at android.os.Handler.dispatchMessage(Handler.java:98)
                                                                           at android.os.Looper.loop(Looper.java:156)
                                                                           at android.app.ActivityThread.main(ActivityThread.java:6524)
                                                                           at java.lang.reflect.Method.invoke(Native Method)
                                                                           at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:941)
                                                                           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:831)
  06-06 00:11:05.238 10571-10571/com.jeebley.jeebley I/Process: Sending signal. PID: 10571 SIG: 9

**

Body:
This is what you are doing:

List<RestaurantModel> list = restaurantResponse.getRestaurantModel();
for (int i = 0; i < list.size(); i++) {
    String name;
    name = list.get(i).getRName();
    names.add(name);
    Log.i(TAG, "onResponse: " + names.get(i));
}

As far as I can see in the error trace, your problem is that list is null when you ask for the size, so you should ask if the list is not null before:

...
List<RestaurantModel> list = restaurantResponse.getRestaurantModel();
if(list != null && !list.isEmpty()){
    for (int i = 0; i < list.size(); i++) {
        String name;
        name = list.get(i).getRName();
        names.add(name);
        Log.i(TAG, "onResponse: " + names.get(i));
    }
}
...

EDIT:

In your adapter, modify this method:

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

The method getItemCount() is being called before the array initialization inside the adapter life cycle. That's why you need to check if your list is null or not to avoid npe.


来源: stackexchange

问:
Close multiple branches in TortoiseHg
I use TortoiseHg 1.1 and in our team we tend to create named branches for each case we work on then merge with default when we're done. Unfortunately most of the named branches don't get closed. This isn't a huge problem but it's annoying when you try and filter by the branch you are currently working on and there is a massive list of old branches to search through.

So is there an easy way in TortoiseHg or from the command line to close multiple branches quickly without having to manually commit and close on each branch?

答:
Okay so this is way late, but I set out to do this via bash and after a lot of pain I got a working solution.  Take note that this does not do an hg push at the end, because I wanted to look over the results in tortoise before pushing.

```<code>#Protected branches to not close
develop='develop'
default='default'

IFS=$'\n'

#Get all branches
allBranches=$( hg branches | sort )

#Loop over and close old branches
for item in $allBranches
do

#Trim off everything but the branch name
branch=$( echo $item | sed -r 's/\s*[0-9]+:[0-9a-f]+(\s\(inactive\))?$//' )

if [ $branch != $develop ] && [ $branch != $default ]
then

hg update $branch
hg commit --close-branch -m "Closing old branch"

fi

done
</code>```

After running the script I asked the team which branches they were actively working on and stripped those closure commits.

ContentLicense: CC BY-SA 2.5

Title: Close multiple branches in TortoiseHg

Body:
Okay so this is way late, but I set out to do this via bash and after a lot of pain I got a working solution.  Take note that this does not do an hg push at the end, because I wanted to look over the results in tortoise before pushing.

#Protected branches to not close
develop='develop'
default='default'

IFS=$'\n'

#Get all branches
allBranches=$( hg branches | sort )

#Loop over and close old branches
for item in $allBranches
do

#Trim off everything but the branch name
branch=$( echo $item | sed -r 's/\s*[0-9]+:[0-9a-f]+(\s\(inactive\))?$//' )

if [ $branch != $develop ] && [ $branch != $default ]
then

hg update $branch
hg commit --close-branch -m "Closing old branch"

fi

done

After running the script I asked the team which branches they were actively working on and stripped those closure commits.

ContentLicense: CC BY-SA 3.0


问:
Wordpress, IIS7, Permalinks and index.php
I know this question may have been asked before, but I have read hundreds of posts all over the Internets and nothing has worked...

I have a wordpress install (WP 3.0), running on MySQL and PHP 5.2.6.

I'm trying to get the permalinks to just be site.com/postname. When I set the permalinks in the settings to just be

```<code>/%postname%
</code>```

It displays as I want it, but I get a 404 on every page (other than the home page).

When it's in this state, if I manually type in site.com/index.php/postname, I get the page, but all the links on the site are pointing to site.com/postname, leading to 404s...

I've been all round the houses on this one, and got in to several different situations. At one point, all the links were going to site.com/postname, and instead of 404'ing, they were all just displaying the home page content

答:
IIS doesn't support a .htaccess file, but you can use the 'URL Rewrite' module to achieve the same pretty urls.

This article (from 2008) describes how it works. The URL rewrite module is available in the web platform installer, as it is a Microsoft add on for IIS (not specific for Wordpress).

Body:
I know this question may have been asked before, but I have read hundreds of posts all over the Internets and nothing has worked...

I have a wordpress install (WP 3.0), running on MySQL and PHP 5.2.6.

I'm trying to get the permalinks to just be site.com/postname. When I set the permalinks in the settings to just be

/%postname%

It displays as I want it, but I get a 404 on every page (other than the home page).

When it's in this state, if I manually type in site.com/index.php/postname, I get the page, but all the links on the site are pointing to site.com/postname, leading to 404s...

I've been all round the houses on this one, and got in to several different situations. At one point, all the links were going to site.com/postname, and instead of 404'ing, they were all just displaying the home page content


问:
how to start observable after x sec
what's the best way to start observable after let's say 10 sec?

```<code>Single<Boolean> init();

public void onStart() {
    init().subscribe(getMySubscriber())
}
</code>```

I'd like to make the actual work in `init starts after 10 sec since subscribed.

答:
Use delaySubscription delaying a subscription to an existing source:

```<code>Single.just(1)
   .delaySubscription(10, TimeUnit.SECONDS)
   .subscribe(System.out::println);
</code>```

If your init() method itself has side-effects before returning a Single, you can wrap it with Single.defer and the above structure should still work:

```<code>Single.defer(() -> init())
    .delaySubscription(10, TimeUnit.SECONDS)
    .subscribe(System.out::println);
</code>```

Title: how to start observable after x sec

Body:
what's the best way to start observable after let's say 10 sec?

Single<Boolean> init();

public void onStart() {
    init().subscribe(getMySubscriber())
}

I'd like to make the actual work in `init starts after 10 sec since subscribed.

Body:
Use delaySubscription delaying a subscription to an existing source:

Single.just(1)
   .delaySubscription(10, TimeUnit.SECONDS)
   .subscribe(System.out::println);

If your init() method itself has side-effects before returning a Single, you can wrap it with Single.defer and the above structure should still work:

Single.defer(() -> init())
    .delaySubscription(10, TimeUnit.SECONDS)
    .subscribe(System.out::println);


问:
How do I create a .bat (batch) file that presses Enter key every 10800 seconds in a loop?
I've tried to make it myself, but it didn't work, as I'm not experienced enough with .bat to get it working.

So what I need is bascily a .bat file which I only need to click once and it will "simulate" me clicking the key 'Enter' every 10800 seconds (3 hours) in a loop, so that it doesn't ever stop clicking the key 'Enter' with a loop time of 10800 seconds, would someone help me out please! :)

答:
You can do this with VBScript and the WScript host:

Save this as "press_enter.vbs" and run it from the CLI with "wscript press_enter.vbs"

```<code>Dim WshShell, FSO, secs

Set WshShell = WScript.CreateObject("WScript.Shell")
Set FSO = CreateObject("Scripting.FileSystemObject")

secs = 10800
kill_file = "C:\Users\Public\Documents\kill_switch.txt"

Do While true
    WScript.Sleep(secs * 1000) ' this is in milliseconds, multiple by 1000
    WshShell.SendKeys "{ENTER}"
    if FSO.FileExists(kill_file) then exit do
Loop
</code>```

As you probably guessed, the program runs forever until it detects the existence of the file "C:\Users\Public\Documents\kill_switch.txt"

You can also kill the program by opening Task Manager and killing the "Microsoft Windows Based Script Host" which will be listed under the "Background processes" section...

Remember that if you stop the application with the "kill_switch.txt" file, you will need to remove it before you start the application again. Perhaps it is best just to kill it with Task Manager...

Body:
You can do this with VBScript and the WScript host:

Save this as "press_enter.vbs" and run it from the CLI with "wscript press_enter.vbs"

Dim WshShell, FSO, secs

Set WshShell = WScript.CreateObject("WScript.Shell")
Set FSO = CreateObject("Scripting.FileSystemObject")

secs = 10800
kill_file = "C:\Users\Public\Documents\kill_switch.txt"

Do While true
    WScript.Sleep(secs * 1000) ' this is in milliseconds, multiple by 1000
    WshShell.SendKeys "{ENTER}"
    if FSO.FileExists(kill_file) then exit do
Loop

As you probably guessed, the program runs forever until it detects the existence of the file "C:\Users\Public\Documents\kill_switch.txt"

You can also kill the program by opening Task Manager and killing the "Microsoft Windows Based Script Host" which will be listed under the "Background processes" section...

Remember that if you stop the application with the "kill_switch.txt" file, you will need to remove it before you start the application again. Perhaps it is best just to kill it with Task Manager...


问:
Get all subsets of a Python dictionary with restrictions
I have the following dictionary:

```<code>intervals = {'param1': [0, 1],
             'param2_hi': [4, 5, 6, 7, 8, 9],
             'param2_lo': [0, 1, 2, 3, 4, 5],
             'param3_hi': [9, 10, 11, 12, 13, 14, 15],
             'param3_lo': [5, 6, 7, 8, 9, 10],
             'param4': [0, 1],
             'param5_hi': [4, 5, 6, 7, 8, 9],
             'param5_lo': [0, 1, 2, 3, 4, 5]}
</code>```

How would I create all possible subsets of this dictionary where I must have exactly one of each number x for 'paramx'? Meaning that I can only have one entry for param1 (_lo or _hi), one entry for param2 (_lo or _hi), and so on, and that each subset must include every paramx that does not have a _lo or _hi.

Here are two possible subsets:

```<code>subset_one = {'param1': [0, 1],
              'param2_hi': [4, 5, 6, 7, 8, 9],
              'param3_hi': [9, 10, 11, 12, 13, 14, 15],
              'param4': [0, 1],
              'param5_hi': [4, 5, 6, 7, 8, 9]}

subset_two = {'param1': [0, 1],
              'param2_lo': [0, 1, 2, 3, 4, 5],
              'param3_lo': [5, 6, 7, 8, 9, 10],
              'param4': [0, 1],
              'param5_lo': [0, 1, 2, 3, 4, 5]}

# Example of mixed '_hi' and '_lo' intervals
subset_three = {'param1': [0, 1],
                'param2_lo': [0, 1, 2, 3, 4, 5],
                'param3_hi': [9, 10, 11, 12, 13, 14, 15],
                'param4': [0, 1],
                'param5_lo': [0, 1, 2, 3, 4, 5]}

...
</code>```

Note: I want to preserve key, value pairs.

Edit: Added subset_three to show the possibility of having mixed '_lo' and '_hi' intervals.

答:
In most simple case you may use the following dict comprehensions:

```<code>subset_1 = {k:v for k,v in intervals.items() if k.endswith('_hi') or not k.endswith('_lo')}
subset_2 = {k:v for k,v in intervals.items() if k.endswith('_lo') or not k.endswith('_hi')}

print(subset_1)
print(subset_2)
</code>```

The output:

```<code>{'param3_hi': [9, 10, 11, 12, 13, 14, 15], 'param1': [0, 1], 'param2_hi': [4, 5, 6, 7, 8, 9], 'param4': [0, 1], 'param5_hi': [4, 5, 6, 7, 8, 9]}
{'param2_lo': [0, 1, 2, 3, 4, 5], 'param1': [0, 1], 'param3_lo': [5, 6, 7, 8, 9, 10], 'param4': [0, 1], 'param5_lo': [0, 1, 2, 3, 4, 5]}
</code>```

Body:
I have the following dictionary:

intervals = {'param1': [0, 1],
             'param2_hi': [4, 5, 6, 7, 8, 9],
             'param2_lo': [0, 1, 2, 3, 4, 5],
             'param3_hi': [9, 10, 11, 12, 13, 14, 15],
             'param3_lo': [5, 6, 7, 8, 9, 10],
             'param4': [0, 1],
             'param5_hi': [4, 5, 6, 7, 8, 9],
             'param5_lo': [0, 1, 2, 3, 4, 5]}

How would I create all possible subsets of this dictionary where I must have exactly one of each number x for 'paramx'? Meaning that I can only have one entry for param1 (_lo or _hi), one entry for param2 (_lo or _hi), and so on, and that each subset must include every paramx that does not have a _lo or _hi.

Here are two possible subsets:

subset_one = {'param1': [0, 1],
              'param2_hi': [4, 5, 6, 7, 8, 9],
              'param3_hi': [9, 10, 11, 12, 13, 14, 15],
              'param4': [0, 1],
              'param5_hi': [4, 5, 6, 7, 8, 9]}

subset_two = {'param1': [0, 1],
              'param2_lo': [0, 1, 2, 3, 4, 5],
              'param3_lo': [5, 6, 7, 8, 9, 10],
              'param4': [0, 1],
              'param5_lo': [0, 1, 2, 3, 4, 5]}

# Example of mixed '_hi' and '_lo' intervals
subset_three = {'param1': [0, 1],
                'param2_lo': [0, 1, 2, 3, 4, 5],
                'param3_hi': [9, 10, 11, 12, 13, 14, 15],
                'param4': [0, 1],
                'param5_lo': [0, 1, 2, 3, 4, 5]}

...

Note: I want to preserve key, value pairs.

Edit: Added subset_three to show the possibility of having mixed '_lo' and '_hi' intervals.

Body:
In most simple case you may use the following dict comprehensions:

subset_1 = {k:v for k,v in intervals.items() if k.endswith('_hi') or not k.endswith('_lo')}
subset_2 = {k:v for k,v in intervals.items() if k.endswith('_lo') or not k.endswith('_hi')}

print(subset_1)
print(subset_2)

The output:

{'param3_hi': [9, 10, 11, 12, 13, 14, 15], 'param1': [0, 1], 'param2_hi': [4, 5, 6, 7, 8, 9], 'param4': [0, 1], 'param5_hi': [4, 5, 6, 7, 8, 9]}
{'param2_lo': [0, 1, 2, 3, 4, 5], 'param1': [0, 1], 'param3_lo': [5, 6, 7, 8, 9, 10], 'param4': [0, 1], 'param5_lo': [0, 1, 2, 3, 4, 5]}


问:
Issue with Kendo ToDataSource(request) build error
Simple stuff, trying to get an idea on how this works.  I am missing something obvious.
I have the kendo.mvc referenced correct vers.
I am getting

System.Collections.Generic.List<SessiondataDTO>' does not contain a definition for 'addTestSessiondata' and no extension method 'addTestSessiondata' accepting a first argument of type 'System.Collections.Generic.List<SessiondataDTO>' could be found

```<code>using Kendo.Mvc.Extensions;
using Kendo.Mvc.UI;
</code>```

Model class

```<code>public class SessiondataDTO
{
    public string userID { get; set; }
    public string serverName { get; set; }
    public string applicationName { get; set; }
    public string farmName { get; set; }
    public string domainName { get; set; }
    public int sessionID { get; set; }
    public string resultmsg { get; set; }
    public bool isInError { get; set; }
    public int id { get; set; }

    public List<SessiondataDTO> addTestSessiondata()
    {
        List<SessiondataDTO> sessiondatas = new List<SessiondataDTO>();

        sessiondatas.Add(new SessiondataDTO { userID = "jayc", applicationName = "testapp1", domainName = "MS", farmName = "testfarm1", serverName = "wtxw0000", sessionID = 12 });
        sessiondatas.Add(new SessiondataDTO { userID = "jayc", applicationName = "testapp44", domainName = "MS", farmName = "testfarm1", serverName = "wtx44444", sessionID = 19 });
        sessiondatas.Add(new SessiondataDTO { userID = "jayc", applicationName = "testapp99", domainName = "MS", farmName = "testfarm1", serverName = "wtxw00890", sessionID = 10 });
        sessiondatas.Add(new SessiondataDTO { userID = "jayc", applicationName = "testapp1", domainName = "MS", farmName = "testfarm1", serverName = "wtxep0000", sessionID = 45 });
        return sessiondatas;
    }
</code>```

Controller

```<code>public class HomeController : Controller
{
    public ActionResult JLO()
    {
        return View();
    }

    public ActionResult sessions_read([DataSourceRequest] DataSourceRequest request)
    {
        List<SessiondataDTO> sdto = new List<SessiondataDTO>();

        sdto.addTestSessiondata();

        DataSourceResult result = sdto.ToDataSourceResult(request,);

        return Json(result, JsonRequestBehavior.AllowGet);
    }
}
</code>```

Everything builds fine but I keep getting that error.  I am using a simple List<> and trying to use the extension method.

答:
addTestSessiondata is not an extension method, but you are attempting to use it as such. Try:</p>

```<code>public ActionResult sessions_read([DataSourceRequest] DataSourceRequest request)
{
    List<SessiondataDTO> sdto = addTestSessiondata();

    DataSourceResult result = sdto.ToDataSourceResult(request);

    return Json(result, JsonRequestBehavior.AllowGet);
}
</code>```

Body:
Simple stuff, trying to get an idea on how this works.  I am missing something obvious.
I have the kendo.mvc referenced correct vers.
I am getting

System.Collections.Generic.List<SessiondataDTO>' does not contain a definition for 'addTestSessiondata' and no extension method 'addTestSessiondata' accepting a first argument of type 'System.Collections.Generic.List<SessiondataDTO>' could be found

using Kendo.Mvc.Extensions;
using Kendo.Mvc.UI;

Model class

public class SessiondataDTO
{
    public string userID { get; set; }
    public string serverName { get; set; }
    public string applicationName { get; set; }
    public string farmName { get; set; }
    public string domainName { get; set; }
    public int sessionID { get; set; }
    public string resultmsg { get; set; }
    public bool isInError { get; set; }
    public int id { get; set; }

    public List<SessiondataDTO> addTestSessiondata()
    {
        List<SessiondataDTO> sessiondatas = new List<SessiondataDTO>();

        sessiondatas.Add(new SessiondataDTO { userID = "jayc", applicationName = "testapp1", domainName = "MS", farmName = "testfarm1", serverName = "wtxw0000", sessionID = 12 });
        sessiondatas.Add(new SessiondataDTO { userID = "jayc", applicationName = "testapp44", domainName = "MS", farmName = "testfarm1", serverName = "wtx44444", sessionID = 19 });
        sessiondatas.Add(new SessiondataDTO { userID = "jayc", applicationName = "testapp99", domainName = "MS", farmName = "testfarm1", serverName = "wtxw00890", sessionID = 10 });
        sessiondatas.Add(new SessiondataDTO { userID = "jayc", applicationName = "testapp1", domainName = "MS", farmName = "testfarm1", serverName = "wtxep0000", sessionID = 45 });
        return sessiondatas;
    }

Controller

public class HomeController : Controller
{
    public ActionResult JLO()
    {
        return View();
    }

    public ActionResult sessions_read([DataSourceRequest] DataSourceRequest request)
    {
        List<SessiondataDTO> sdto = new List<SessiondataDTO>();

        sdto.addTestSessiondata();

        DataSourceResult result = sdto.ToDataSourceResult(request,);

        return Json(result, JsonRequestBehavior.AllowGet);
    }
}

Everything builds fine but I keep getting that error.  I am using a simple List<> and trying to use the extension method.

Body:
addTestSessiondata is not an extension method, but you are attempting to use it as such. Try:

public ActionResult sessions_read([DataSourceRequest] DataSourceRequest request)
{
    List<SessiondataDTO> sdto = addTestSessiondata();

    DataSourceResult result = sdto.ToDataSourceResult(request);

    return Json(result, JsonRequestBehavior.AllowGet);
}


问:
WordPress get post thumbnail and wrap it in permalink
I would like to get the post thumbnail and link it to the post in WordPress. This seems logical to me but it's not producing the desired result.

```<code><?php
    if(is_category()){
        echo '<a href="' . get_permalink() . '">' . '<img src="' . the_post_thumbnail( 'full' ) . '"</a>';
    }
?>
</code>```

Instead, it's producing this in the DOM:

What do I need to do to get this working?

答:
This worked for me:</p>

```<code>echo '<a href="' . get_permalink() . '"><img src="' . get_the_post_thumbnail() . '</a>';
</code>```

Body:
I would like to get the post thumbnail and link it to the post in WordPress. This seems logical to me but it's not producing the desired result.

<?php
    if(is_category()){
        echo '' . '<img src="' . the_post_thumbnail( 'full' ) . '"';
    }
?>

Instead, it's producing this in the DOM:

What do I need to do to get this working?

Body:
This worked for me:

echo '<a href="' . get_permalink() . '"><img src="' . get_the_post_thumbnail() . '</a>';


答:
I think both collections.defaultdict and itertools.product will be useful here. First, construct a pool that sorts the keys based off what they start with. Then, construct the Cartesian product of these bins.

```<code>from collections import defaultdict
from itertools import product

pool = defaultdict(list)
for key in intervals:
    base = key.split('_')[0]
    pool[base].append(key)

subsets = [{key: intervals[key] for key in keys} for keys in product(*pool.values())]

# {'param2_lo': [0, 1, 2, 3, 4, 5], ... , 'param1': [0, 1]}
# {'param5_lo': [0, 1, 2, 3, 4, 5], ..., 'param2_hi': [4, 5, 6, 7, 8, 9]}
# and so on...
</code>```

Title: Get all subsets of a Python dictionary with restrictions

Body:
I think both collections.defaultdict and itertools.product will be useful here. First, construct a pool that sorts the keys based off what they start with. Then, construct the Cartesian product of these bins.

from collections import defaultdict
from itertools import product

pool = defaultdict(list)
for key in intervals:
    base = key.split('_')[0]
    pool[base].append(key)

subsets = [{key: intervals[key] for key in keys} for keys in product(*pool.values())]

# {'param2_lo': [0, 1, 2, 3, 4, 5], ... , 'param1': [0, 1]}
# {'param5_lo': [0, 1, 2, 3, 4, 5], ..., 'param2_hi': [4, 5, 6, 7, 8, 9]}
# and so on...


问:
Pandas HDFStore Tables doesn't accept multiindex columns
This works fine:

```<code>cols = ['X', 'Y']
ind = [('A', 1), ('B', 2)]
ind = pd.MultiIndex.from_tuples(index, names=['foo', 'number'])

df = pd.DataFrame(rand(2,2), columns = cols, index=ind)
store.put('df', df, table=True)
print store['df']

               X         Y
foo number
A   1       0.015005  0.213427
B   2       0.090311  0.595418
</code>```

This breaks:

```<code>cols = [('X', 1), ('Y', 2)]
cols = pd.MultiIndex.from_tuples(index, names=['bar', 'number'])
ind = [('A', 1), ('B', 2)]
ind = pd.MultiIndex.from_tuples(index, names=['foo', 'number'])

df = pd.DataFrame(rand(2,2), columns = cols, index=ind)
store.put('df', df, table=True)
print store['df']

KeyError: u'no item named foo'
</code>```

I suspect this is a known limitation of using PyTables, but I couldn't find any reference in the Pandas docs that the multiindex is in fact restricted to the index, not the columns.

答:
Until #5823 is solved, you may collapse the index prior to storing it, as a workaround (see this SO how: https://stackoverflow.com/a/14508355/548792):

```<code>assert isinstance(df.columns, pd.MultiIndex), df
df.columns = ['.'.join(col).strip() for col in df.columns.values]
df.to_hdf(store, 'df', table=True)
</code>```

And to recreate it, assuming no other dot(.) exists anywhere in the original column names:

```<code>df = store['/df']
df.columns = pd.MultiIndex.from_tuples([c.split('.') for c in df.columns])
</code>```

Body:
This works fine:

cols = ['X', 'Y']
ind = [('A', 1), ('B', 2)]
ind = pd.MultiIndex.from_tuples(index, names=['foo', 'number'])

df = pd.DataFrame(rand(2,2), columns = cols, index=ind)
store.put('df', df, table=True)
print store['df']

               X         Y
foo number
A   1       0.015005  0.213427
B   2       0.090311  0.595418

This breaks:

cols = [('X', 1), ('Y', 2)]
cols = pd.MultiIndex.from_tuples(index, names=['bar', 'number'])
ind = [('A', 1), ('B', 2)]
ind = pd.MultiIndex.from_tuples(index, names=['foo', 'number'])

df = pd.DataFrame(rand(2,2), columns = cols, index=ind)
store.put('df', df, table=True)
print store['df']

KeyError: u'no item named foo'

I suspect this is a known limitation of using PyTables, but I couldn't find any reference in the Pandas docs that the multiindex is in fact restricted to the index, not the columns.

Body:
Until #5823 is solved, you may collapse the index prior to storing it, as a workaround (see this SO how: https://stackoverflow.com/a/14508355/548792):

assert isinstance(df.columns, pd.MultiIndex), df
df.columns = ['.'.join(col).strip() for col in df.columns.values]
df.to_hdf(store, 'df', table=True)

And to recreate it, assuming no other dot(.) exists anywhere in the original column names:

df = store['/df']
df.columns = pd.MultiIndex.from_tuples([c.split('.') for c in df.columns])


问:
Prevent robots from coping images from a website
I have a website created in PHP technology and i want to prevent robots from coping images from the website.What is the best way to prevent robots from coping images from a website?

Please make sure it doesn't harm SEO.
Please make sure this does not influence spyders and crawlers from indexing the site.

答:
Some potential solutions might include using Flash to display the images or loading them dynamically via Javascript after the page has loaded. You could also consider throttling page loads by IP to prevent extremely fast access, making the robot much slower in scraping the site. These solutions have obvious drawbacks, though.

There is no failsafe method of preventing content scraping on your website. A competent developer who wants to scrape a site he has access to can do so with little effort. The best bet is to watermark the content or put it behind a pay wall.


问:
sec_axis function in ggplot2
I want to create a secondary axis in ggplot2. I am running the second example in http://ggplot2.tidyverse.org/reference/sec_axis.html.

```<code>> p <- ggplot(mtcars, aes(cyl, mpg)) +
+     geom_point()
>
> # Create a simple secondary axis
> p + scale_y_continuous(sec.axis = sec_axis(~.+10))
Error in scale_y_continuous(sec.axis = sec_axis(~. + 10)) :
  unused argument (sec.axis = sec_axis(~. + 10))
>
</code>```

Why is this error occurring?

答:
I had the same with 2.2.1 !?!
I got it fixed by updating my rather old (1.5 year) R version…</p>

Title: sec_axis function in ggplot2

Body:
I want to create a secondary axis in ggplot2. I am running the second example in http://ggplot2.tidyverse.org/reference/sec_axis.html.

> p <- ggplot(mtcars, aes(cyl, mpg)) +
+     geom_point()
>
> # Create a simple secondary axis
> p + scale_y_continuous(sec.axis = sec_axis(~.+10))
Error in scale_y_continuous(sec.axis = sec_axis(~. + 10)) :
  unused argument (sec.axis = sec_axis(~. + 10))
>

Why is this error occurring?


问:
Search and replace with sed does not work with html tags
i have two questions:

1) I try to replace one couple  of html tags and value between them:
i try to replace this gmail	 on this skype

When i tried to do this:
sed -i -e "s/gmail	/skype	/g" test.txt

,i received error:

sed: -e expression #1, char 18: unknown option tos'`

I understand, that i should use string, ok, let's do use this pattern:

sed -i -e "s/'"gmail	"'/"'skype	'"/g" test3.txt

in this case, i have other error:

-su: td: No such file or directory

Where i have error, Please help.

2) I want to make replace only on special line. For example, i have:

```<code><tr>
    <td>click</td>
    <td>gmail</td>
    <td>message-type</td>
</tr>
</code>```

I want to replace only third line. How can i do it ?

答:
Combine the line number 3 with another delimiter like https://stackoverflow.com/a/22182719/3220113 (so you do not need backslashes):</p>

```<code>sed -i -e '3 s#<td>gmail</td>#<td>skype</td>#g' test.txt
</code>```

Body:
i have two questions:

1) I try to replace one couple  of html tags and value between them:
i try to replace this gmail	 on this skype

When i tried to do this:
sed -i -e "s/gmail	/skype	/g" test.txt

,i received error:

sed: -e expression #1, char 18: unknown option tos'`

I understand, that i should use string, ok, let's do use this pattern:

sed -i -e "s/'"gmail	"'/"'skype	'"/g" test3.txt

in this case, i have other error:

-su: td: No such file or directory

Where i have error, Please help.

2) I want to make replace only on special line. For example, i have:

    click
    gmail
    message-type

I want to replace only third line. How can i do it ?

Body:
Combine the line number 3 with another delimiter like https://stackoverflow.com/a/22182719/3220113 (so you do not need backslashes):

sed -i -e '3 s#<td>gmail</td>#<td>skype</td>#g' test.txt


问:
In CKEditor, how can I add a "text" label to a button?
```<code>editor.ui.addButton( 'ImageUpload',{
                label: 'Upload Image',
                command: 'popup_image_uploader',
                icon: this.path + 'images/icon.png'
            });
</code>```

That's my current code right now. When you load the page, you only see the icon.

But if you go to the demo here, you'll see that "Source" is a text.  I want to add the word "Upload Image" next to the icon.

答:
In the current ckeditor (4.6.x) the answers above do not work for me.

I dug around in ckeditor/skins/moono-list/editor.css and did a search for "source" to find how they did the Source button which has text. I found this:

```<code>.cke_button__source_label,
.cke_button__sourcedialog_label
{
    display:inline
}
</code>```

Notice that there are TWO underscores here before the name of your custom button. When I tried with only one underscore it did not work.

Anyway you would replace "source" or "sourcedialog" above with whatever you want and add that to your own css file.

Additionally, it seems to only work for button names that are entirely lowercase.

Body:
editor.ui.addButton( 'ImageUpload',{
                label: 'Upload Image',
                command: 'popup_image_uploader',
                icon: this.path + 'images/icon.png'
            });

That's my current code right now. When you load the page, you only see the icon.

But if you go to the demo here, you'll see that "Source" is a text.  I want to add the word "Upload Image" next to the icon.

Body:
In the current ckeditor (4.6.x) the answers above do not work for me.

I dug around in ckeditor/skins/moono-list/editor.css and did a search for "source" to find how they did the Source button which has text. I found this:

.cke_button__source_label,
.cke_button__sourcedialog_label
{
    display:inline
}

Notice that there are TWO underscores here before the name of your custom button. When I tried with only one underscore it did not work.

Anyway you would replace "source" or "sourcedialog" above with whatever you want and add that to your own css file.

Additionally, it seems to only work for button names that are entirely lowercase.


问:
Perl: Don't print any lines that are duplicates
What is a Perl one-liner to only print those lines that only ever appear once (that is, do not print if it appears more than once--the truly unique lines)?

For example, if I have a file that contains duplicate lines:

```<code>line1
line2
line2
line3
line1
line4
line5
</code>```

The output should be:

```<code>line3
line4
line5
</code>```

I can do perl -ne 'print if $a{$_}++' file to see only the lines that are duplicates...

```<code>line2
line1
</code>```

I can swap the if for its antonym, unless, and see only one occurrence of each line in the file...

```<code>perl -ne 'print unless $a{$_}++' file
line1
line2
line3
line4
line5
</code>```

I'm assuming I have to slurp the entire file in and process it using single \n delimiters for each line, maybe into a hash?  Just not sure how to do that.

答:
You only know if a line is unique after you've read all the lines, so you can't possibly start printing before you've reached the end of the file!

```<code># Varying order

perl -nle'++$lines{$_}; END { print for grep $lines{$_}==1, keys %lines; }' file
</code>```

or

```<code># Sorted

perl -nle'++$lines{$_}; END { print for sort grep $lines{$_}==1, keys %lines; }' file
</code>```

or

```<code># Original order

perl -nle'
   if ( my $orig_line_num = $line_nums_by_line{$_} ) {
      $lines_by_line_num[$orig_line_num] = undef;
   } else {
      $lines_by_line_num[$.] = $_;
      $line_nums_by_line{$_} = $.;
   }

   END { print for grep defined, @lines_by_line_num; }
' file
</code>```

Body:
What is a Perl one-liner to only print those lines that only ever appear once (that is, do not print if it appears more than once--the truly unique lines)?

For example, if I have a file that contains duplicate lines:

line1
line2
line2
line3
line1
line4
line5

The output should be:

line3
line4
line5

I can do perl -ne 'print if $a{$_}++' file to see only the lines that are duplicates...

line2
line1

I can swap the if for its antonym, unless, and see only one occurrence of each line in the file...

perl -ne 'print unless $a{$_}++' file
line1
line2
line3
line4
line5

I'm assuming I have to slurp the entire file in and process it using single \n delimiters for each line, maybe into a hash?  Just not sure how to do that.

Body:
You only know if a line is unique after you've read all the lines, so you can't possibly start printing before you've reached the end of the file!

# Varying order

perl -nle'++$lines{$_}; END { print for grep $lines{$_}==1, keys %lines; }' file

or

# Sorted

perl -nle'++$lines{$_}; END { print for sort grep $lines{$_}==1, keys %lines; }' file

or

# Original order

perl -nle'
   if ( my $orig_line_num = $line_nums_by_line{$_} ) {
      $lines_by_line_num[$orig_line_num] = undef;
   } else {
      $lines_by_line_num[$.] = $_;
      $line_nums_by_line{$_} = $.;
   }

   END { print for grep defined, @lines_by_line_num; }
' file


问:
How to add images to existing item with ebay API
I am using ebay-sdk for python. I uploaded some images to eBay Picture Services(EPS) successfully using the below code:

```<code>from ebaysdk.trading import Connection as Trading

api = Trading(config_file='ebay.yaml', siteid=71)

def upload_images(image_url):
    response = api.execute('UploadSiteHostedPictures', {"ExternalPictureURL": image_url,
                                                             "PictureSet": "Supersize"})
    return response.content

upload_images(MY_IMG_URL)
</code>```

eBay returns the URL of the uploaded images.

But how can I add the images to my existing eBay offers? Do I have to use ReviseItem?

An example using the ebay-sdk for python would be nice.

Edit:

```<code>    def revise_image(self, item_id):
    myitem = {
        "Item": {
            "Country": "DE",
            "ItemID": item_id,
            "PictureDetails": [
                {"PictureURL": MY_IMG1},
                {"PictureURL": MY_IMG2},
                {"PictureURL": MY_IMG3}
            ]
        }
    }
    response = self.api.execute('ReviseFixedPriceItem', myitem)
</code>```

I made the changes as suggested but it still only changes the main image. MY_IMG3 becomes the main image. MY_IMG1 and MY_IMG2 are not appended to the listing.

答:
This works.

```<code>def verifyAddItem(args):
        #"""http://www.utilities-online.info/xmltojson/#.UXli2it4avc   """
    try:
        api = Trading(debug=args.debug, siteid=site_id, appid=app_id, token=token_id, config_file=None, certid=cert_id, devid=dev_id)

        myitem = {
            "Item": {
                "Country": "GB",
                "Description": description,
                "ItemID": item_to_revise,
                "PictureDetails": {
                    "PictureURL": "http://www.itcircleconsult.com/eb2017/4a.png"
                    },
                }
            }

        api.execute('ReviseFixedPriceItem', myitem)
        dump(api)
</code>```

I have been working a lot with eBay and Python..

Check here for some working examples.. I often rip them apart and put them back together on the fly but you might find some use..

There is an I-ways checker and some BS4 ripping to revise items as well

https://github.com/johnashu/PRODUCTION/tree/master/Python/eBay%20API%20KIT%20-%20Maffas%20-%202017

another useful thing is check out the eBay API call index here:

http://developer.ebay.com/devzone/xml/docs/Reference/eBay/index.html#CallIndex

then use an XML to JSON convertor to change the calls you need into a more readable format in pythong..

Here:

http://www.utilities-online.info/xmltojson/#.WTW_P8b-vct

NOTES ON ADDING IMAGES AND HOSTING:

https://developer.ebay.com/devzone/xml/docs/reference/ebay/UploadSiteHostedPictures.html

Note: As of release 889, you do not need to use this call to upload self-hosted images before creating the listing. You can now specify up to 12 self-hosted or EPS hosted URLs at once in Item.PictureDetails.PictureURL using the AddItem or AddFixedPriceItem calls. However, you must use the UploadSiteHostedPictures call to upload binary attachments.

The supposed JSON needed it this.. unless it takes time to populate the pictures to the item?

We were both Missing  [] - Schoolboy error!

```<code>{
"Item": {
    "PictureDetails": [
    { "PictureURL": "http://pics.ebay.com/aw/pics/dot_clear.gif" },
    { "PictureURL": "fds" },
    { "PictureURL": "fds" }
    ]
}
}
</code>```

Body:
I am using ebay-sdk for python. I uploaded some images to eBay Picture Services(EPS) successfully using the below code:

from ebaysdk.trading import Connection as Trading

api = Trading(config_file='ebay.yaml', siteid=71)

def upload_images(image_url):
    response = api.execute('UploadSiteHostedPictures', {"ExternalPictureURL": image_url,
                                                             "PictureSet": "Supersize"})
    return response.content

upload_images(MY_IMG_URL)

eBay returns the URL of the uploaded images.

But how can I add the images to my existing eBay offers? Do I have to use ReviseItem?

An example using the ebay-sdk for python would be nice.

Edit:

    def revise_image(self, item_id):
    myitem = {
        "Item": {
            "Country": "DE",
            "ItemID": item_id,
            "PictureDetails": [
                {"PictureURL": MY_IMG1},
                {"PictureURL": MY_IMG2},
                {"PictureURL": MY_IMG3}
            ]
        }
    }
    response = self.api.execute('ReviseFixedPriceItem', myitem)

I made the changes as suggested but it still only changes the main image. MY_IMG3 becomes the main image. MY_IMG1 and MY_IMG2 are not appended to the listing.

Body:
This works.

def verifyAddItem(args):
        #"""http://www.utilities-online.info/xmltojson/#.UXli2it4avc   """
    try:
        api = Trading(debug=args.debug, siteid=site_id, appid=app_id, token=token_id, config_file=None, certid=cert_id, devid=dev_id)

        myitem = {
            "Item": {
                "Country": "GB",
                "Description": description,
                "ItemID": item_to_revise,
                "PictureDetails": {
                    "PictureURL": "http://www.itcircleconsult.com/eb2017/4a.png"
                    },
                }
            }

        api.execute('ReviseFixedPriceItem', myitem)
        dump(api)

I have been working a lot with eBay and Python..

Check here for some working examples.. I often rip them apart and put them back together on the fly but you might find some use..

There is an I-ways checker and some BS4 ripping to revise items as well

https://github.com/johnashu/PRODUCTION/tree/master/Python/eBay%20API%20KIT%20-%20Maffas%20-%202017

another useful thing is check out the eBay API call index here:

http://developer.ebay.com/devzone/xml/docs/Reference/eBay/index.html#CallIndex

then use an XML to JSON convertor to change the calls you need into a more readable format in pythong..

Here:

http://www.utilities-online.info/xmltojson/#.WTW_P8b-vct

NOTES ON ADDING IMAGES AND HOSTING:

https://developer.ebay.com/devzone/xml/docs/reference/ebay/UploadSiteHostedPictures.html

Note: As of release 889, you do not need to use this call to upload self-hosted images before creating the listing. You can now specify up to 12 self-hosted or EPS hosted URLs at once in Item.PictureDetails.PictureURL using the AddItem or AddFixedPriceItem calls. However, you must use the UploadSiteHostedPictures call to upload binary attachments.

The supposed JSON needed it this.. unless it takes time to populate the pictures to the item?

We were both Missing  [] - Schoolboy error!

{
"Item": {
    "PictureDetails": [
    { "PictureURL": "http://pics.ebay.com/aw/pics/dot_clear.gif" },
    { "PictureURL": "fds" },
    { "PictureURL": "fds" }
    ]
}
}


问:
Why is the type of tf.Variable([8.0], tf.float64) float 32 rather than float 64 in TensorFlow?
(Updated question)
I think the original question is confusing, and I found a simpler way to ask this question.

```<code>#!/usr/bin/python

import tensorflow as tf
x = tf.Variable([2], tf.float32)
print x.dtype
</code>```

If we try the above code segment, then the output is as follows:

```<code><dtype: 'int32_ref'>
</code>```

Since I explicitly specified the type of x as tf.float32, I had thought that the type should be float32. However, it seems like the type is int32.

Could somebody answer this question?

(original question)

I tried the following code to replace one element of a 2-D tensorflow array.

```<code>#!/usr/bin/python

import tensorflow as tf
import numpy as np

ref = tf.Variable(np.arange(0, 12).reshape((4, 3)).astype(np.float64))
indices = tf.constant([[2, 2]])
updates = tf.Variable([8.0], tf.float64)
ref = tf.scatter_nd_update(ref, indices, updates)

with tf.Session() as sess:
  init = tf.global_variables_initializer()
  sess.run(init)
  print sess.run(ref)
</code>```

Strangely, I encountered the following type error:

TypeError: Input 'updates' of 'ScatterNdUpdate' Op has type float32 that does not match type float64 of argument 'ref'.

After changing tf.Variable([8.0], tf.float64) to the following line, it worked.

```<code>updates = tf.Variable(np.array([8.0]).astype(np.float64), tf.float64)
</code>```

So, it seems like the type of tf.Variable([8.0], tf.float64) is not tf.float64, even though I explicitly specified the type as tf.float64. Could anyone tell me the reason? Thank you!

答:
The reason is really simple: your code create a tf.Variable which is trainable (your tf.float64 is interpreted as a True for the trainable argument. If you just add dtype, it will work:

```<code>    updates = tf.Variable([8.0], dtype=tf.float64)
</code>```

Actually, there was a similar Q&A.

Body:
(Updated question)
I think the original question is confusing, and I found a simpler way to ask this question.

#!/usr/bin/python

import tensorflow as tf
x = tf.Variable([2], tf.float32)
print x.dtype

If we try the above code segment, then the output is as follows:

<dtype: 'int32_ref'>

Since I explicitly specified the type of x as tf.float32, I had thought that the type should be float32. However, it seems like the type is int32.

Could somebody answer this question?

(original question)

I tried the following code to replace one element of a 2-D tensorflow array.

#!/usr/bin/python

import tensorflow as tf
import numpy as np

ref = tf.Variable(np.arange(0, 12).reshape((4, 3)).astype(np.float64))
indices = tf.constant([[2, 2]])
updates = tf.Variable([8.0], tf.float64)
ref = tf.scatter_nd_update(ref, indices, updates)

with tf.Session() as sess:
  init = tf.global_variables_initializer()
  sess.run(init)
  print sess.run(ref)

Strangely, I encountered the following type error:

TypeError: Input 'updates' of 'ScatterNdUpdate' Op has type float32 that does not match type float64 of argument 'ref'.

After changing tf.Variable([8.0], tf.float64) to the following line, it worked.

updates = tf.Variable(np.array([8.0]).astype(np.float64), tf.float64)

So, it seems like the type of tf.Variable([8.0], tf.float64) is not tf.float64, even though I explicitly specified the type as tf.float64. Could anyone tell me the reason? Thank you!

Body:
The reason is really simple: your code create a tf.Variable which is trainable (your tf.float64 is interpreted as a True for the trainable argument. If you just add dtype, it will work:

    updates = tf.Variable([8.0], dtype=tf.float64)

Actually, there was a similar Q&A.


问:
How to check conditions without multiple if statements?
I am working on a game for android in Xamarin, but I have two specific sections that are extremly DRY (don't repeat yourself).

The first section is when I want to change the soundtrack(audioplay) or background, where I have three different pitches for the same soundtrack based on level, and the same for background where the background canvas alternates.

For these methods the condition is based on an integer level that equals the level the player is in.

Example code

```<code>private void SetBackgrounds()
{
    if (level == 5)
    {
        gameAreaCanvas.SetBackgroundResource(Resource.Drawable.LevelUpOneBackground);

    }
    else if (level == 10)
    {
        gameAreaCanvas.SetBackgroundResource(Resource.Drawable.LevelUpTwoBackground);

    }
    else if (level == 15)
    {
        gameAreaCanvas.SetBackgroundResource(Resource.Drawable.LevelUpThreeBackground);

    }
}
</code>```

The same goes for different parts of the code where alot is based on an integer value which is the level. Every time the player advances the level integer increments by one, and then the activity has methods that checks what the integer level is. The code is working but is very inefficient obviously, because there is a lot of duplicated code with a small tweak.

For instance a level looks like this.

```<code>        if(level == 1) {

            levelDisplay.Text = "LEVEL 1";
            timer = new Timer();
            timer.Interval = 2000; /// DIFFERENT
            timer.Enabled = true;
            timer.Elapsed += Level1; /// DIFFERENT
            timer.Start();
        }
        ///LEVEL 2
        if (level == 2)
        {
            levelDisplay.Text = "LEVEL 2";
            timer = new Timer();
            timer.Interval = 2000; /// DIFFERENT
            timer.Enabled = true;
            timer.Elapsed += Level2; /// DIFFERENT
            timer.Start();
        }
</code>```

Is there a way to make this code less DRY? Input is appreciated.

答:
They're called switch statements and they look like this:

```<code>switch(level)
{
  case 1:
    doLevel1();
    break;
  case 2:
    doLevel2();
    break;
}
</code>```

More information can be found here: Switch Statement Tutorial

Body:
I am working on a game for android in Xamarin, but I have two specific sections that are extremly DRY (don't repeat yourself).

The first section is when I want to change the soundtrack(audioplay) or background, where I have three different pitches for the same soundtrack based on level, and the same for background where the background canvas alternates.

For these methods the condition is based on an integer level that equals the level the player is in.

Example code

private void SetBackgrounds()
{
    if (level == 5)
    {
        gameAreaCanvas.SetBackgroundResource(Resource.Drawable.LevelUpOneBackground);

    }
    else if (level == 10)
    {
        gameAreaCanvas.SetBackgroundResource(Resource.Drawable.LevelUpTwoBackground);

    }
    else if (level == 15)
    {
        gameAreaCanvas.SetBackgroundResource(Resource.Drawable.LevelUpThreeBackground);

    }
}

The same goes for different parts of the code where alot is based on an integer value which is the level. Every time the player advances the level integer increments by one, and then the activity has methods that checks what the integer level is. The code is working but is very inefficient obviously, because there is a lot of duplicated code with a small tweak.

For instance a level looks like this.

        if(level == 1) {

            levelDisplay.Text = "LEVEL 1";
            timer = new Timer();
            timer.Interval = 2000; /// DIFFERENT
            timer.Enabled = true;
            timer.Elapsed += Level1; /// DIFFERENT
            timer.Start();
        }
        ///LEVEL 2
        if (level == 2)
        {
            levelDisplay.Text = "LEVEL 2";
            timer = new Timer();
            timer.Interval = 2000; /// DIFFERENT
            timer.Enabled = true;
            timer.Elapsed += Level2; /// DIFFERENT
            timer.Start();
        }

Is there a way to make this code less DRY? Input is appreciated.

Body:
They're called switch statements and they look like this:

switch(level)
{
  case 1:
    doLevel1();
    break;
  case 2:
    doLevel2();
    break;
}

More information can be found here: Switch Statement Tutorial


问:
Limit File Types in CakePHP File Input
I just wanted to know if there is a way to limit the file input dialog to show only certain kinds of files.  My web page only can accept .bin or .gz file types, but the user can select other file types and try to upload them.

What would be the best way to prevent the wrong kind of file from being uploaded?

Here is my controller for file uploading:

```<code>    public function uploadFile()
    {
        $this->Session->write('isFileUpload', false);
        $this->Session->write('isFileLarge', false);

        if($this->request->is('post'))
        {
            $uploadedFile = array();

            // Check if the Document object is set
            // If it is set, process the file for uploading,
            if(isset($this->request->data['Document']))
            {
                $filename = $this->request->data['Document']['MyFile']['tmp_name'];

                $uploadedFile['MyFile']['name'] = $this->request->data['Document']['MyFile']['name'];
                $uploadedFile['MyFile']['type'] = $this->request->data['Document']['MyFile']['type'];
                $uploadedFile['MyFile']['size'] = $this->request->data['Document']['MyFile']['size'];

                // Move the file to the /home/spectracom folder
                $filePath = DS . 'home' . DS . $uploadedFile['MyFile']['name'];

                if (move_uploaded_file($filename, $filePath))
                {
                    $this->Session->write('isFileUpload', true);
                    $this->Session->write('isFileLarge', false);
                    $this->redirect('/tools/upgradebackup');
                }
                else
                {
                    $this->Session->write('isFileUpload', false);
                    $this->Session->write('isFileLarge', true);
                    $this->redirect('/tools/upgradebackup');
                }
            }
            else
            {
                $this->Session->write('isFileUpload', false);
                $this->Session->write('isFileLarge', true);
                $this->redirect('/tools/upgradebackup');
            }
        }
    }
</code>```

I basically check that the file exists, or else it is too large, and when it returns to the main upgrade page it sets the session variables.

Thanks

答:
Tested with Cakephp 3.4</p>

```<code>$this->Form->control('my_file', ['label' => 'Upload File','type' => 'file', 'accept' => 'application/msword']);
</code>```

Title: Limit File Types in CakePHP File Input

Body:
I just wanted to know if there is a way to limit the file input dialog to show only certain kinds of files.  My web page only can accept .bin or .gz file types, but the user can select other file types and try to upload them.

What would be the best way to prevent the wrong kind of file from being uploaded?

Here is my controller for file uploading:

    public function uploadFile()
    {
        $this->Session->write('isFileUpload', false);
        $this->Session->write('isFileLarge', false);

        if($this->request->is('post'))
        {
            $uploadedFile = array();

            // Check if the Document object is set
            // If it is set, process the file for uploading,
            if(isset($this->request->data['Document']))
            {
                $filename = $this->request->data['Document']['MyFile']['tmp_name'];

                $uploadedFile['MyFile']['name'] = $this->request->data['Document']['MyFile']['name'];
                $uploadedFile['MyFile']['type'] = $this->request->data['Document']['MyFile']['type'];
                $uploadedFile['MyFile']['size'] = $this->request->data['Document']['MyFile']['size'];

                // Move the file to the /home/spectracom folder
                $filePath = DS . 'home' . DS . $uploadedFile['MyFile']['name'];

                if (move_uploaded_file($filename, $filePath))
                {
                    $this->Session->write('isFileUpload', true);
                    $this->Session->write('isFileLarge', false);
                    $this->redirect('/tools/upgradebackup');
                }
                else
                {
                    $this->Session->write('isFileUpload', false);
                    $this->Session->write('isFileLarge', true);
                    $this->redirect('/tools/upgradebackup');
                }
            }
            else
            {
                $this->Session->write('isFileUpload', false);
                $this->Session->write('isFileLarge', true);
                $this->redirect('/tools/upgradebackup');
            }
        }
    }

I basically check that the file exists, or else it is too large, and when it returns to the main upgrade page it sets the session variables.

Thanks

Body:
Tested with Cakephp 3.4

$this->Form->control('my_file', ['label' => 'Upload File','type' => 'file', 'accept' => 'application/msword']);


问:
Access widget window beautifulsoup python mechanize
I am trying to scrape information off websites like this:

https://www.glassdoor.com/Overview/Working-at-7-Eleven-EI_IE3581.11,19.htm

using python + beautifulsoup + mechanize.

Accessing anything on the main-site is no problem. However, I also need the information that appears in a overlay-window that appears when one clicks on the "Rating Trends" button next to the bar with stars.

This overlay-window can also be accessed directly by using the url:

https://www.glassdoor.com/Reviews/7-Eleven-Reviews-E3581.htm#trends-overallRating

The html associated with this page is a modification of the original site's html.

However, regardless of what element I try to find (via findAll ) on that overlay-window website, beautifulsoup returns zero hits.

How can I fix this? I tried adding a sleep time between accessing the website and reading anything in, to no avail.

Thanks!

答:
If you're using the Chrome browser select the background of that page (without the additional information displayed) and select 'Inspect' from the context menu (for Windows anyway), then the 'Network' tab, so that you can see network traffic. Now click on 'Rating trends'. The entry marked 'xhr' will be https://www.glassdoor.ca/api/employer/3581-rating.htm?locationStr=&jobTitleStr=&filterCurrentEmployee=false&filterEmploymentStatus=REGULAR&filterEmploymentStatus=PART_TIME (I much hope!) and its contents will be the following.

```<code>{"employerId":3581,"ratings":[{"hasRating":true,"type":"overallRating","value":2.9},{"hasRating":true,"type":"ceoRating","value":0.54},{"hasRating":true,"type":"bizOutlook","value":0.35},{"hasRating":true,"type":"recommend","value":0.4},{"hasRating":true,"type":"compAndBenefits","value":2.4},{"hasRating":true,"type":"cultureAndValues","value":2.5},{"hasRating":true,"type":"careerOpportunities","value":2.5},{"hasRating":true,"type":"workLife","value":2.4},{"hasRating":true,"type":"seniorManagement","value":2.3}],"week":0,"year":0}
</code>```

Whether this URL can be altered for use in obtaining information for other employers, I regret, I cannot tell you.

Body:
If you're using the Chrome browser select the background of that page (without the additional information displayed) and select 'Inspect' from the context menu (for Windows anyway), then the 'Network' tab, so that you can see network traffic. Now click on 'Rating trends'. The entry marked 'xhr' will be https://www.glassdoor.ca/api/employer/3581-rating.htm?locationStr=&jobTitleStr=&filterCurrentEmployee=false&filterEmploymentStatus=REGULAR&filterEmploymentStatus=PART_TIME (I much hope!) and its contents will be the following.

{"employerId":3581,"ratings":[{"hasRating":true,"type":"overallRating","value":2.9},{"hasRating":true,"type":"ceoRating","value":0.54},{"hasRating":true,"type":"bizOutlook","value":0.35},{"hasRating":true,"type":"recommend","value":0.4},{"hasRating":true,"type":"compAndBenefits","value":2.4},{"hasRating":true,"type":"cultureAndValues","value":2.5},{"hasRating":true,"type":"careerOpportunities","value":2.5},{"hasRating":true,"type":"workLife","value":2.4},{"hasRating":true,"type":"seniorManagement","value":2.3}],"week":0,"year":0}

Whether this URL can be altered for use in obtaining information for other employers, I regret, I cannot tell you.