问:
Tab layout with more then one recycleview is not working android
In my project i am trying to display Recycleview in 3 tabs. in my fist tab i could able to display items in recycleview successfully. but in my second tab fragment its not working. please see my tab layout

```<code><?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/lib/zesteve.com.myapplication"
    android:layout_width="match_parent"
    xmlns:app1="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_height="wrap_content">

  <LinearLayout
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:orientation="vertical">

    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        app:tabGravity="fill"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        app:tabMode="fixed"
        android:elevation="10dp"
        style="@style/NavigationTab"/>

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </android.support.v4.view.ViewPager>

  </LinearLayout>

    <android.support.design.widget.FloatingActionButton
            app:backgroundTint="@color/colorPrimary"
            android:layout_width="56dp"
            android:layout_height="56dp"
            app:fabSize="normal"
            android:layout_gravity="bottom|right"
            android:src="@drawable/ic_action_fab_act_btn"
            android:id="@+id/post_new_event"
            android:layout_margin="16dp"/>

</FrameLayout>
</code>```

And Tabfragement.java

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

    public static TabLayout tabLayout;
    public static ViewPager viewPager;
    public static int int_items = 3 ;

    FloatingActionButton fab;

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

        View x =  inflater.inflate(R.layout.tab_layout,container, false);
        tabLayout = (TabLayout) x.findViewById(R.id.tabs);
        viewPager = (ViewPager) x.findViewById(R.id.viewpager);
        //tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);

        viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));

        fab = (FloatingActionButton) x.findViewById(R.id.post_new_event);

        fab.setBackgroundTintList(ColorStateList.valueOf(getResources().getColor(R.color.cpb_blue)));

        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(),PostNewEvent.class);
                startActivity(intent);
            }
        });

        tabLayout.post(new Runnable() {
            @Override
            public void run() {
                tabLayout.setupWithViewPager(viewPager);
            }
        });

        return x;

    }

    class MyAdapter extends FragmentStatePagerAdapter{

        public MyAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position)
        {
            switch (position){
                case 0 : return new PrimaryFragment();
                case 1 : return new CityFeedFragment();
                case 2 : return new BuzzFragment();
            }
            return null;
        }

        @Override
        public int getCount() {

            return int_items;

        }

        @Override
        public CharSequence getPageTitle(int position) {

            switch (position){
                case 0 :
                    return "Category";
                case 1 :
                    return "City Feeds";
                case 2 :
                    return "Buzz";
            }
            return null;
        }
    }

}
</code>```

My adapter for second tab

```<code>public class CityfeedAdapter extends RecyclerView.Adapter<CityfeedAdapter.MyViewHolder>{

    Context mContext;
    ArrayList<Cityfeed> cityfeedList = new ArrayList<Cityfeed>();
    private MaterialRippleLayout mRipple;

    public CityfeedAdapter(Context mContext, ArrayList<Cityfeed> cityfeedList){
        this.mContext = mContext;
        this.cityfeedList = cityfeedList;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.city_feed_card, parent, false);

        return new MyViewHolder(itemView,mContext,cityfeedList);
    }

    @Override
    public void onBindViewHolder(final MyViewHolder holder, int position) {
        Cityfeed catlist = cityfeedList.get(position);
        holder.title.setText(catlist.getName());
        holder.count.setText(catlist.getNumOfEvents() + " Events");

        // loading album cover using Picasso library
        Picasso.with(mContext).load(catlist.getThumbnail()).into(holder.thumbnail);
    }

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

    public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
        public TextView title, count;
        public ImageView thumbnail;

        ArrayList<Cityfeed> cityfeedList = new ArrayList<Cityfeed>();
        Context mContext;

        public MyViewHolder(View view , Context mContext, ArrayList<Cityfeed> cityfeedList ) {
            super(view);
            this.cityfeedList = cityfeedList;
            this.mContext = mContext;
            //view.setOnClickListener(this);
            title = (TextView) view.findViewById(R.id.title);
            count = (TextView) view.findViewById(R.id.count);
            thumbnail = (ImageView) view.findViewById(R.id.thumbnail);
            mRipple = (MaterialRippleLayout) view.findViewById(R.id.ripple);
            MaterialRippleLayout.on(mRipple).create();
            mRipple.setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {
            int position = getAdapterPosition();
            Cityfeed cityfeedList = this.cityfeedList.get(position);
            Intent intent = new Intent(this.mContext, EventPostList.class);
            intent.putExtra("EveId", cityfeedList.getEventId());
            intent.putExtra("EveName", cityfeedList.getName());
            this.mContext.startActivity(intent);

        }
    }
}
</code>```

Second Tab Fragment

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

    private RecyclerView recyclerView;
    private CityfeedAdapter adapter;
    private ArrayList<Cityfeed> cityfeedList;
    private Session session;
    private GridLayoutManager mLayoutManager;
    private ProgressDialog progressDialog;

    String ucl;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View root = LayoutInflater.from(container.getContext()).inflate(R.layout.cityfeed_layout,container,false);
        recyclerView = (RecyclerView) root.findViewById(R.id.crecycler_view);

        progressDialog = new ProgressDialog(getActivity());
        progressDialog.setCancelable(false);

        cityfeedList = new ArrayList<>();
        adapter = new CityfeedAdapter(getActivity(), cityfeedList);
        session = new Session(getActivity());
        load_data_from_server(0);

        mLayoutManager= new GridLayoutManager(getActivity(),3);
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.addItemDecoration(new GridSpacingItemDecoration(3, dpToPx(10), true));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(adapter);

        ucl = session.getUserLocation().get(session.KEY_UCITY);

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                //super.onScrolled(recyclerView, dx, dy);

                if(mLayoutManager.findLastCompletelyVisibleItemPosition()  == cityfeedList.size()-1){
                    load_data_from_server(cityfeedList.get(cityfeedList.size()-1).getEventId());
                }

            }
        });

        return root;
    }

    private void load_data_from_server(int id){
        progressDialog.setMessage("Loading Please Wait...");
        showDialog();

        AsyncTask<Integer,Void,Void> task = new AsyncTask<Integer, Void, Void>() {
            @Override
            protected Void doInBackground(Integer... integers) {

                OkHttpClient client = new OkHttpClient();
                okhttp3.Request request = new okhttp3.Request.Builder()
                        .url("http://api.zesteve.com/catagory.php?city="+ucl+"&id="+integers[0])
                        .build();
                try {
                    Response response = client.newCall(request).execute();
                    JSONArray array = new JSONArray(response.body().string());

                    for (int i=0; i<array.length(); i++){

                        JSONObject object =array.getJSONObject(i);

                        Cityfeed events = new Cityfeed(object.getString("eventname"),
                                object.getInt("count"),
                                object.getInt("eveid"),
                                object.getString("event_image"));

                        cityfeedList.add(events);
                    }

                }catch (IOException e){
                    e.printStackTrace();
                } catch (JSONException e) {
                    System.out.println("End of Catagory");
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                hideDialog();
                adapter.notifyDataSetChanged();
            }
        };
        task.execute(id);

    }

    public class GridSpacingItemDecoration extends RecyclerView.ItemDecoration {

        private int spanCount;
        private int spacing;
        private boolean includeEdge;

        public GridSpacingItemDecoration(int spanCount, int spacing, boolean includeEdge) {
            this.spanCount = spanCount;
            this.spacing = spacing;
            this.includeEdge = includeEdge;
        }

        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            int position = parent.getChildAdapterPosition(view); // item position
            int column = position % spanCount; // item column

            if (includeEdge) {
                outRect.left = spacing - column * spacing / spanCount; // spacing - column * ((1f / spanCount) * spacing)
                outRect.right = (column + 1) * spacing / spanCount; // (column + 1) * ((1f / spanCount) * spacing)

                if (position < spanCount) { // top edge
                    outRect.top = spacing;
                }
                outRect.bottom = spacing; // item bottom
            } else {
                outRect.left = column * spacing / spanCount; // column * ((1f / spanCount) * spacing)
                outRect.right = spacing - (column + 1) * spacing / spanCount; // spacing - (column + 1) * ((1f /    spanCount) * spacing)
                if (position >= spanCount) {
                    outRect.top = spacing; // item top
                }
            }
        }
    }

    private void showDialog() {
        if (!progressDialog.isShowing())
            progressDialog.show();
    }

    private void hideDialog() {
        if (progressDialog.isShowing())
            progressDialog.dismiss();
    }
    /**
     * Converting dp to pixel
     */
    private int dpToPx(int dp) {
        Resources r = getResources();
        return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics()));
    }

    @Override
    public void onResume() {
        super.onResume();
        load_data_from_server(0);
    }

}
</code>```

XML Layout for my Second Tab

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <include layout="@layout/content_cityfeed" />

</RelativeLayout>
</code>```

And

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/viewBg"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="zesteve.com.myapplication.CityFeedFragment"
    tools:showIn="@layout/cityfeed_layout">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/crecycler_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:clipToPadding="false"
        android:scrollbars="vertical" />

</RelativeLayout>
</code>```

This is my Cardview

```<code><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <android.support.v7.widget.CardView
        android:id="@+id/card_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_margin="@dimen/card_margin"
        android:elevation="8dp"
        card_view:cardCornerRadius="@dimen/card_album_radius">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <com.balysv.materialripple.MaterialRippleLayout
                android:id="@+id/ripple"
                android:layout_centerInParent="true"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                app:mrl_rippleOverlay="true"
                app:mrl_rippleColor="#000"
                app:mrl_rippleAlpha="0.2"
                app:mrl_rippleDimension="10dp"
                app:mrl_rippleHover="true"
                app:mrl_rippleRoundedCorners="10dp"
                app:mrl_rippleInAdapter="false"
                app:mrl_rippleDuration="350"
                app:mrl_rippleFadeDuration="75"
                app:mrl_rippleDelayClick="false"
                app:mrl_rippleBackground="#FFF"
                app:mrl_ripplePersistent="true">

                <ImageView
                    android:id="@+id/thumbnail"
                    android:layout_width="match_parent"
                    android:layout_height="160dp"
                    android:background="?attr/selectableItemBackgroundBorderless"
                    android:scaleType="fitXY" />

            </com.balysv.materialripple.MaterialRippleLayout>

            <LinearLayout
                android:id="@+id/framlayout"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                android:background="#80000000" >

                <TextView
                    android:id="@+id/title"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:paddingLeft="@dimen/album_title_padding"
                    android:paddingRight="@dimen/album_title_padding"
                    android:paddingTop="@dimen/album_title_Top"
                    android:paddingBottom="3dp"
                    android:textColor="@color/white"
                    android:textSize="@dimen/album_title" />

                <TextView
                    android:id="@+id/count"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:paddingBottom="@dimen/songs_count_padding_bottom"
                    android:paddingLeft="@dimen/album_title_padding"
                    android:paddingRight="@dimen/album_title_padding"
                    android:textColor="@color/white"
                    android:textSize="@dimen/songs_count" />
            </LinearLayout>

        </RelativeLayout>

    </android.support.v7.widget.CardView>

</FrameLayout>
</code>```

I hope i did't missed any thing. Recyleview not displaying any thing in my second tab fragment. My Json response is working fine when i check in browser, its showing the response, but not displaying in the fragment.

答:
There is an error in the api :

Try this while parsing the JSONArray :

```<code> Cityfeed events = new Cityfeed(object.has("eventname")?object.getString("eventname"):"",
            object.has("count")?object.getInt("count"):0,
            object.has("eveid")?object.getInt("eveid"):"",
            object.has("event_image")?object.getString("event_image"):"");
</code>```

Hope this helps.

Body:
In my project i am trying to display Recycleview in 3 tabs. in my fist tab i could able to display items in recycleview successfully. but in my second tab fragment its not working. please see my tab layout

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/lib/zesteve.com.myapplication"
    android:layout_width="match_parent"
    xmlns:app1="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_height="wrap_content">

  <LinearLayout
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:orientation="vertical">

    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        app:tabGravity="fill"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        app:tabMode="fixed"
        android:elevation="10dp"
        style="@style/NavigationTab"/>

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </android.support.v4.view.ViewPager>

  </LinearLayout>

    <android.support.design.widget.FloatingActionButton
            app:backgroundTint="@color/colorPrimary"
            android:layout_width="56dp"
            android:layout_height="56dp"
            app:fabSize="normal"
            android:layout_gravity="bottom|right"
            android:src="@drawable/ic_action_fab_act_btn"
            android:id="@+id/post_new_event"
            android:layout_margin="16dp"/>

</FrameLayout>

And Tabfragement.java

public class TabFragment extends Fragment {

    public static TabLayout tabLayout;
    public static ViewPager viewPager;
    public static int int_items = 3 ;

    FloatingActionButton fab;

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

        View x =  inflater.inflate(R.layout.tab_layout,container, false);
        tabLayout = (TabLayout) x.findViewById(R.id.tabs);
        viewPager = (ViewPager) x.findViewById(R.id.viewpager);
        //tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);

        viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));

        fab = (FloatingActionButton) x.findViewById(R.id.post_new_event);

        fab.setBackgroundTintList(ColorStateList.valueOf(getResources().getColor(R.color.cpb_blue)));

        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(),PostNewEvent.class);
                startActivity(intent);
            }
        });

        tabLayout.post(new Runnable() {
            @Override
            public void run() {
                tabLayout.setupWithViewPager(viewPager);
            }
        });

        return x;

    }

    class MyAdapter extends FragmentStatePagerAdapter{

        public MyAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position)
        {
            switch (position){
                case 0 : return new PrimaryFragment();
                case 1 : return new CityFeedFragment();
                case 2 : return new BuzzFragment();
            }
            return null;
        }

        @Override
        public int getCount() {

            return int_items;

        }

        @Override
        public CharSequence getPageTitle(int position) {

            switch (position){
                case 0 :
                    return "Category";
                case 1 :
                    return "City Feeds";
                case 2 :
                    return "Buzz";
            }
            return null;
        }
    }

}

My adapter for second tab

public class CityfeedAdapter extends RecyclerView.Adapter<CityfeedAdapter.MyViewHolder>{

    Context mContext;
    ArrayList<Cityfeed> cityfeedList = new ArrayList<Cityfeed>();
    private MaterialRippleLayout mRipple;

    public CityfeedAdapter(Context mContext, ArrayList<Cityfeed> cityfeedList){
        this.mContext = mContext;
        this.cityfeedList = cityfeedList;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.city_feed_card, parent, false);

        return new MyViewHolder(itemView,mContext,cityfeedList);
    }

    @Override
    public void onBindViewHolder(final MyViewHolder holder, int position) {
        Cityfeed catlist = cityfeedList.get(position);
        holder.title.setText(catlist.getName());
        holder.count.setText(catlist.getNumOfEvents() + " Events");

        // loading album cover using Picasso library
        Picasso.with(mContext).load(catlist.getThumbnail()).into(holder.thumbnail);
    }

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

    public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
        public TextView title, count;
        public ImageView thumbnail;

        ArrayList<Cityfeed> cityfeedList = new ArrayList<Cityfeed>();
        Context mContext;

        public MyViewHolder(View view , Context mContext, ArrayList<Cityfeed> cityfeedList ) {
            super(view);
            this.cityfeedList = cityfeedList;
            this.mContext = mContext;
            //view.setOnClickListener(this);
            title = (TextView) view.findViewById(R.id.title);
            count = (TextView) view.findViewById(R.id.count);
            thumbnail = (ImageView) view.findViewById(R.id.thumbnail);
            mRipple = (MaterialRippleLayout) view.findViewById(R.id.ripple);
            MaterialRippleLayout.on(mRipple).create();
            mRipple.setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {
            int position = getAdapterPosition();
            Cityfeed cityfeedList = this.cityfeedList.get(position);
            Intent intent = new Intent(this.mContext, EventPostList.class);
            intent.putExtra("EveId", cityfeedList.getEventId());
            intent.putExtra("EveName", cityfeedList.getName());
            this.mContext.startActivity(intent);

        }
    }
}

Second Tab Fragment

public class CityFeedFragment extends Fragment {

    private RecyclerView recyclerView;
    private CityfeedAdapter adapter;
    private ArrayList<Cityfeed> cityfeedList;
    private Session session;
    private GridLayoutManager mLayoutManager;
    private ProgressDialog progressDialog;

    String ucl;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View root = LayoutInflater.from(container.getContext()).inflate(R.layout.cityfeed_layout,container,false);
        recyclerView = (RecyclerView) root.findViewById(R.id.crecycler_view);

        progressDialog = new ProgressDialog(getActivity());
        progressDialog.setCancelable(false);

        cityfeedList = new ArrayList<>();
        adapter = new CityfeedAdapter(getActivity(), cityfeedList);
        session = new Session(getActivity());
        load_data_from_server(0);

        mLayoutManager= new GridLayoutManager(getActivity(),3);
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.addItemDecoration(new GridSpacingItemDecoration(3, dpToPx(10), true));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(adapter);

        ucl = session.getUserLocation().get(session.KEY_UCITY);

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                //super.onScrolled(recyclerView, dx, dy);

                if(mLayoutManager.findLastCompletelyVisibleItemPosition()  == cityfeedList.size()-1){
                    load_data_from_server(cityfeedList.get(cityfeedList.size()-1).getEventId());
                }

            }
        });

        return root;
    }

    private void load_data_from_server(int id){
        progressDialog.setMessage("Loading Please Wait...");
        showDialog();

        AsyncTask<Integer,Void,Void> task = new AsyncTask<Integer, Void, Void>() {
            @Override
            protected Void doInBackground(Integer... integers) {

                OkHttpClient client = new OkHttpClient();
                okhttp3.Request request = new okhttp3.Request.Builder()
                        .url("http://api.zesteve.com/catagory.php?city="+ucl+"&id="+integers[0])
                        .build();
                try {
                    Response response = client.newCall(request).execute();
                    JSONArray array = new JSONArray(response.body().string());

                    for (int i=0; i<array.length(); i++){

                        JSONObject object =array.getJSONObject(i);

                        Cityfeed events = new Cityfeed(object.getString("eventname"),
                                object.getInt("count"),
                                object.getInt("eveid"),
                                object.getString("event_image"));

                        cityfeedList.add(events);
                    }

                }catch (IOException e){
                    e.printStackTrace();
                } catch (JSONException e) {
                    System.out.println("End of Catagory");
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                hideDialog();
                adapter.notifyDataSetChanged();
            }
        };
        task.execute(id);

    }

    public class GridSpacingItemDecoration extends RecyclerView.ItemDecoration {

        private int spanCount;
        private int spacing;
        private boolean includeEdge;

        public GridSpacingItemDecoration(int spanCount, int spacing, boolean includeEdge) {
            this.spanCount = spanCount;
            this.spacing = spacing;
            this.includeEdge = includeEdge;
        }

        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            int position = parent.getChildAdapterPosition(view); // item position
            int column = position % spanCount; // item column

            if (includeEdge) {
                outRect.left = spacing - column * spacing / spanCount; // spacing - column * ((1f / spanCount) * spacing)
                outRect.right = (column + 1) * spacing / spanCount; // (column + 1) * ((1f / spanCount) * spacing)

                if (position < spanCount) { // top edge
                    outRect.top = spacing;
                }
                outRect.bottom = spacing; // item bottom
            } else {
                outRect.left = column * spacing / spanCount; // column * ((1f / spanCount) * spacing)
                outRect.right = spacing - (column + 1) * spacing / spanCount; // spacing - (column + 1) * ((1f /    spanCount) * spacing)
                if (position >= spanCount) {
                    outRect.top = spacing; // item top
                }
            }
        }
    }

    private void showDialog() {
        if (!progressDialog.isShowing())
            progressDialog.show();
    }

    private void hideDialog() {
        if (progressDialog.isShowing())
            progressDialog.dismiss();
    }
    /**
     * Converting dp to pixel
     */
    private int dpToPx(int dp) {
        Resources r = getResources();
        return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics()));
    }

    @Override
    public void onResume() {
        super.onResume();
        load_data_from_server(0);
    }

}

XML Layout for my Second Tab

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <include layout="@layout/content_cityfeed" />

</RelativeLayout>

And

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/viewBg"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="zesteve.com.myapplication.CityFeedFragment"
    tools:showIn="@layout/cityfeed_layout">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/crecycler_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:clipToPadding="false"
        android:scrollbars="vertical" />

</RelativeLayout>

This is my Cardview

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <android.support.v7.widget.CardView
        android:id="@+id/card_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_margin="@dimen/card_margin"
        android:elevation="8dp"
        card_view:cardCornerRadius="@dimen/card_album_radius">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <com.balysv.materialripple.MaterialRippleLayout
                android:id="@+id/ripple"
                android:layout_centerInParent="true"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                app:mrl_rippleOverlay="true"
                app:mrl_rippleColor="#000"
                app:mrl_rippleAlpha="0.2"
                app:mrl_rippleDimension="10dp"
                app:mrl_rippleHover="true"
                app:mrl_rippleRoundedCorners="10dp"
                app:mrl_rippleInAdapter="false"
                app:mrl_rippleDuration="350"
                app:mrl_rippleFadeDuration="75"
                app:mrl_rippleDelayClick="false"
                app:mrl_rippleBackground="#FFF"
                app:mrl_ripplePersistent="true">

                <ImageView
                    android:id="@+id/thumbnail"
                    android:layout_width="match_parent"
                    android:layout_height="160dp"
                    android:background="?attr/selectableItemBackgroundBorderless"
                    android:scaleType="fitXY" />

            </com.balysv.materialripple.MaterialRippleLayout>

            <LinearLayout
                android:id="@+id/framlayout"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                android:background="#80000000" >

                <TextView
                    android:id="@+id/title"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:paddingLeft="@dimen/album_title_padding"
                    android:paddingRight="@dimen/album_title_padding"
                    android:paddingTop="@dimen/album_title_Top"
                    android:paddingBottom="3dp"
                    android:textColor="@color/white"
                    android:textSize="@dimen/album_title" />

                <TextView
                    android:id="@+id/count"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:paddingBottom="@dimen/songs_count_padding_bottom"
                    android:paddingLeft="@dimen/album_title_padding"
                    android:paddingRight="@dimen/album_title_padding"
                    android:textColor="@color/white"
                    android:textSize="@dimen/songs_count" />
            </LinearLayout>

        </RelativeLayout>

    </android.support.v7.widget.CardView>

</FrameLayout>

I hope i did't missed any thing. Recyleview not displaying any thing in my second tab fragment. My Json response is working fine when i check in browser, its showing the response, but not displaying in the fragment.

Body:
There is an error in the api :

Try this while parsing the JSONArray :

 Cityfeed events = new Cityfeed(object.has("eventname")?object.getString("eventname"):"",
            object.has("count")?object.getInt("count"):0,
            object.has("eveid")?object.getInt("eveid"):"",
            object.has("event_image")?object.getString("event_image"):"");

Hope this helps.


来源: stackexchange

问:
Why won't wordpress load my jQuery script?
My wordpress site won't load the script into my page. I put the following function in functions.php:

```<code>function nav_script () {

    wp_enqueue_script( 'script', get_stylesheet_directory_uri() .'/js/script.js', array('jQuery'), '1.0.0', true);

}

add_action('wp_enqueue_scripts', 'nav_script');
</code>```

and the script containted in the scripts.js is as follows:

```<code>$(document).ready(function() {
    var stickyNavTop = $('.blog-nav').offset().top;

        var stickyNav = function(){
        var scrollTop = $(window).scrollTop();

                    if (scrollTop > stickyNavTop) {
                        $('.blog-nav').addClass('sticky');
                    }
                    else {
                        $('.blog-nav').removeClass('sticky');
                    }
                };

            stickyNav();

        $(window).scroll(function() {
            stickyNav();
    });
});
</code>```

When I view the source code of the page I don't see the script, so it didn't get loaded for some reason... I have the wp_head in the head and the wp_footer before the body ending tag, so I have zero clue of what can be happening, anyone out there can help? The function works in a normal html as I tried in JSFiddle...

Editing... Guys I achieved something by adding the script "manually" to the function, like this:

```<code>    function nav_script () {
        ?>
        <script>

            $(document).ready(function() {
                                var stickyNavTop = $('.blog-nav').offset().top;

                                    var stickyNav = function(){
                                    var scrollTop = $(window).scrollTop();

                                    if (scrollTop > stickyNavTop) {
                                            $('.blog-nav').addClass('sticky');
                                    } else {
                                            $('.blog-nav').removeClass('sticky');
                                    }
                                    };

                                    stickyNav();

                                    $(window).scroll(function() {
                                        stickyNav();
                                });
                            });

        </script>
        <?php
    }

add_action('wp_head', 'nav_script');
</code>```

But I've noticed two things:
ONE: it won't work if I don't insert the         CDN in the head;
TWO: It will only work if I reload the website, which is suggesting me some plugin conflict...

答:
WordPress do not recognize $ as short for jQuery just add

var $ = jQuery

on top

ContentLicense: CC BY-SA 3.0

Body:
My wordpress site won't load the script into my page. I put the following function in functions.php:

function nav_script () {

    wp_enqueue_script( 'script', get_stylesheet_directory_uri() .'/js/script.js', array('jQuery'), '1.0.0', true);

}

add_action('wp_enqueue_scripts', 'nav_script');

and the script containted in the scripts.js is as follows:

$(document).ready(function() {
    var stickyNavTop = $('.blog-nav').offset().top;

        var stickyNav = function(){
        var scrollTop = $(window).scrollTop();

                    if (scrollTop > stickyNavTop) {
                        $('.blog-nav').addClass('sticky');
                    }
                    else {
                        $('.blog-nav').removeClass('sticky');
                    }
                };

            stickyNav();

        $(window).scroll(function() {
            stickyNav();
    });
});

When I view the source code of the page I don't see the script, so it didn't get loaded for some reason... I have the wp_head in the head and the wp_footer before the body ending tag, so I have zero clue of what can be happening, anyone out there can help? The function works in a normal html as I tried in JSFiddle...

Editing... Guys I achieved something by adding the script "manually" to the function, like this:

    function nav_script () {
        ?>

        <?php
    }

add_action('wp_head', 'nav_script');

But I've noticed two things:
ONE: it won't work if I don't insert the         CDN in the head;
TWO: It will only work if I reload the website, which is suggesting me some plugin conflict...


问:
How to check if a pandas Series contains Timestamps?
Following seems to work at least in some cases:

```<code>series.dtype == np.dtype('<M8[ns]')
</code>```

but it doesn't look pretty and I'm not sure if it works always (with all(?) kinds of Timestamps).

Is there a nicer way for testing whether a column contains Timestamps?

答:
try this it should work:

```<code>pd.core.dtypes.common.is_datetime_or_timedelta_dtype(series)
</code>```

if you go through pd.core.dtypes.common.is_ you will find many options for checking timestamps. If you want to combine them then you can use logical operators like:

```<code>pd.core.dtypes.common.is_datetime64_ns_dtype(ser)|pd.core.dtypes.common.is_timedelta64_ns_dtype(ser)
</code>```

Body:
Following seems to work at least in some cases:

series.dtype == np.dtype('<M8[ns]')

but it doesn't look pretty and I'm not sure if it works always (with all(?) kinds of Timestamps).

Is there a nicer way for testing whether a column contains Timestamps?

Body:
try this it should work:

pd.core.dtypes.common.is_datetime_or_timedelta_dtype(series)

if you go through pd.core.dtypes.common.is_ you will find many options for checking timestamps. If you want to combine them then you can use logical operators like:

pd.core.dtypes.common.is_datetime64_ns_dtype(ser)|pd.core.dtypes.common.is_timedelta64_ns_dtype(ser)


问:
How to create a stroke around a custom mask?
I'm trying to create a border around a mask using a UIimage. When I create the mask in code it looks fine:

```<code>@IBOutlet weak var imageToBeMasked: UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()
    let mask = UIImageView(image: Image)
    imageToBeMasked.mask = mask
}
</code>```

But when I try and create a stroke around it appears to not use the mask at all:

```<code>  @IBOutlet weak var imageToBeMasked: UIImageView!

  override func viewDidLoad() {
    super.viewDidLoad()

    let mask = UIImageView(image: Image)

    // the layer used to mask the image view
    let maskLayer = CAShapeLayer()
    maskLayer.path = UIBezierPath(rect: mask.bounds).cgPath
    imageToBeMasked.layer.mask = maskLayer

    // the layer used to draw the border
    let strokeLayer = CAShapeLayer()
    strokeLayer.frame = imageToBeMasked.bounds
    strokeLayer.fillColor = UIColor.clear.cgColor
    strokeLayer.path = UIBezierPath(rect: mask.bounds).cgPath
    strokeLayer.strokeColor = UIColor.black.cgColor
    strokeLayer.lineWidth = 4
    imageToBeMasked.layer.addSublayer(strokeLayer)
}
</code>```

Any clue on how to solve this issue?

答:
The CALayer is not affected by the mask itself. The quickest way would be creating a new image which is slightly bigger than the original, place it behind the original image and tint it with a color.

```<code>let templateImage = originalImage.withRenderingMode(.alwaysTemplate)
strokeImageView.image = templateImage
strokeImageView.tintColor = .black
</code>```

Body:
I'm trying to create a border around a mask using a UIimage. When I create the mask in code it looks fine:

@IBOutlet weak var imageToBeMasked: UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()
    let mask = UIImageView(image: Image)
    imageToBeMasked.mask = mask
}

But when I try and create a stroke around it appears to not use the mask at all:

  @IBOutlet weak var imageToBeMasked: UIImageView!

  override func viewDidLoad() {
    super.viewDidLoad()

    let mask = UIImageView(image: Image)

    // the layer used to mask the image view
    let maskLayer = CAShapeLayer()
    maskLayer.path = UIBezierPath(rect: mask.bounds).cgPath
    imageToBeMasked.layer.mask = maskLayer

    // the layer used to draw the border
    let strokeLayer = CAShapeLayer()
    strokeLayer.frame = imageToBeMasked.bounds
    strokeLayer.fillColor = UIColor.clear.cgColor
    strokeLayer.path = UIBezierPath(rect: mask.bounds).cgPath
    strokeLayer.strokeColor = UIColor.black.cgColor
    strokeLayer.lineWidth = 4
    imageToBeMasked.layer.addSublayer(strokeLayer)
}

Any clue on how to solve this issue?

Body:
The CALayer is not affected by the mask itself. The quickest way would be creating a new image which is slightly bigger than the original, place it behind the original image and tint it with a color.

let templateImage = originalImage.withRenderingMode(.alwaysTemplate)
strokeImageView.image = templateImage
strokeImageView.tintColor = .black


问:
React Native Router Flux
I am new to react native, and trying to build an app to practise. I have arrived to the routing part, but it is not working properly. I have now three components. The app, the router and one called game.

I have this in the routing:

```<code>import React from 'react';
import { Scene, Router } from 'react-native-router-flux'
import { GameComponent } from './game'

const RouterComponent = () => {
   return (
       <Router>
           <Scene key="root">
               <Scene
                   key="game"
                   component={GameComponent}
                   title="New Game"
               />
           </Scene>
        </Router>
    );
 }
export default RouterComponent;
</code>```

And this in the app:

```<code>import { Actions } from 'react-native-router-flux';

export default class App extends React.Component {
    render() {
        return (
            <View style={styles.container}>
                <Text>Basketball App</Text>
                <Button
                     onPress={() => Actions.game()}
                     title="New Game">
                </Button>
            </View>
        );
    }
</code>```

But i receive the following error message: undefined is not a function.
What am I missing?

Thanks a lot in advance

答:
You also need to define the Home Screen in your Router

 Import your GameComponent

```<code>import GameComponent from './game';
</code>```

 Create your Router

```<code>const RouterComponent = () => {
     return (
       <Router>
           <Scene key="root">
               <Scene key="home" component={Home} title="Home" />
               <Scene key="game" component={GameComponent} title="New Game" />
           </Scene>
        </Router>
      );
}
</code>```

 Create your Home Screen

```<code>class Home extends Component {
  render() {
    return (
      <View style={{flex:1}}>
          <Text>Basketball App</Text>
          <Button
               onPress={() => Actions.game() }
               title="New Game">
          </Button>
      </View>
    );
  }
}
</code>```

Main App

```<code>export default class App extends React.Component {
    render() {
        return (
            <RouterComponent />
        );
    }
}
</code>```

Title: React Native Router Flux

Body:
I am new to react native, and trying to build an app to practise. I have arrived to the routing part, but it is not working properly. I have now three components. The app, the router and one called game.

I have this in the routing:

import React from 'react';
import { Scene, Router } from 'react-native-router-flux'
import { GameComponent } from './game'

const RouterComponent = () => {
   return (
       <Router>
           <Scene key="root">
               <Scene
                   key="game"
                   component={GameComponent}
                   title="New Game"
               />
           </Scene>
        </Router>
    );
 }
export default RouterComponent;

And this in the app:

import { Actions } from 'react-native-router-flux';

export default class App extends React.Component {
    render() {
        return (
            <View style={styles.container}>
                <Text>Basketball App</Text>
                <Button
                     onPress={() => Actions.game()}
                     title="New Game">
                </Button>
            </View>
        );
    }

But i receive the following error message: undefined is not a function.
What am I missing?

Thanks a lot in advance

Body:
You also need to define the Home Screen in your Router

 Import your GameComponent

import GameComponent from './game';

 Create your Router

const RouterComponent = () => {
     return (
       <Router>
           <Scene key="root">
               <Scene key="home" component={Home} title="Home" />
               <Scene key="game" component={GameComponent} title="New Game" />
           </Scene>
        </Router>
      );
}

 Create your Home Screen

class Home extends Component {
  render() {
    return (
      <View style={{flex:1}}>
          <Text>Basketball App</Text>
          <Button
               onPress={() => Actions.game() }
               title="New Game">
          </Button>
      </View>
    );
  }
}

Main App

export default class App extends React.Component {
    render() {
        return (
            <RouterComponent />
        );
    }
}


问:
Windows 10 constantly prompts for permission to use precise location
I have a very simple application that uses realtime location data to obtain relevant information, developed in C# as a UWP 10.0 application.

My interaction with the geolocation API is very simple: I only checked Location in the "Package Manifest" under "Capabilities" and I only use the following API call:

```<code>var locator = new Windows.Devices.Geolocation.Geolocator();
var location = await locator.GetGeopositionAsync();
</code>```

When this call is first made, Windows 10 throws up an "Allow this application to use your precise location [yes | no]" dialog. Selecting "yes" seems to "save" this choice for around 5 minutes or so; subsequent attempts at obtaining the user's position within the next five minutes go through (I believe they return the cached value, as it never seems to change), but more than 5 minutes later, the permission dialog is always shown once more (even though the user has already authorized it).

From my reading of the geolocation API documentation on MSDN, I can find nothing to suggest that this is the intended behavior. Under privacy settings in the metro control panel, this application is under the list of apps allowed to use the precise location. What's more, other apps in that list with precise location enabled have never prompted me to allow them access to the precise location past the first time.

What am I doing wrong here and how can I prevent this dialog from constantly popping up?

EDIT

With await Geolocator.RequestAccessAsync(), the permissions are cached so long as the exe is not modified/re-compiled.

答:
I was able to replicate your problem. But according to official documentation, it clearly mentions, that you need to call RequestAccessAsync() before any calls.

So when I made change from your lines of codes, to below, permission Request window showed up only once and subsequent calls were made directly.

```<code>GeolocationAccessStatus accessStatus = await Geolocator.RequestAccessAsync();
if (accessStatus == GeolocationAccessStatus.Allowed)
{
    Geolocator locator = new Geolocator();
    Geoposition location = await locator.GetGeopositionAsync();
    locText.Text = location.Coordinate.Point.Position.Latitude + Environment.NewLine + location.Coordinate.Point.Position.Longitude;
}
</code>```

Body:
I have a very simple application that uses realtime location data to obtain relevant information, developed in C# as a UWP 10.0 application.

My interaction with the geolocation API is very simple: I only checked Location in the "Package Manifest" under "Capabilities" and I only use the following API call:

var locator = new Windows.Devices.Geolocation.Geolocator();
var location = await locator.GetGeopositionAsync();

When this call is first made, Windows 10 throws up an "Allow this application to use your precise location [yes | no]" dialog. Selecting "yes" seems to "save" this choice for around 5 minutes or so; subsequent attempts at obtaining the user's position within the next five minutes go through (I believe they return the cached value, as it never seems to change), but more than 5 minutes later, the permission dialog is always shown once more (even though the user has already authorized it).

From my reading of the geolocation API documentation on MSDN, I can find nothing to suggest that this is the intended behavior. Under privacy settings in the metro control panel, this application is under the list of apps allowed to use the precise location. What's more, other apps in that list with precise location enabled have never prompted me to allow them access to the precise location past the first time.

What am I doing wrong here and how can I prevent this dialog from constantly popping up?

EDIT

With await Geolocator.RequestAccessAsync(), the permissions are cached so long as the exe is not modified/re-compiled.

Body:
I was able to replicate your problem. But according to official documentation, it clearly mentions, that you need to call RequestAccessAsync() before any calls.

So when I made change from your lines of codes, to below, permission Request window showed up only once and subsequent calls were made directly.

GeolocationAccessStatus accessStatus = await Geolocator.RequestAccessAsync();
if (accessStatus == GeolocationAccessStatus.Allowed)
{
    Geolocator locator = new Geolocator();
    Geoposition location = await locator.GetGeopositionAsync();
    locText.Text = location.Coordinate.Point.Position.Latitude + Environment.NewLine + location.Coordinate.Point.Position.Longitude;
}


问:
Error installing node-sass dependency
I am trying to npm install a package.json with the following dependencies:

```<code>  "devDependencies": {
    "browser-sync": "^2.8.2",
    "del": "^1.2.0",
    "gulp": "^3.9.0",
    "gulp-autoprefixer": "^2.3.1",
    "gulp-babel": "^5.2.0",
    "gulp-concat": "^2.6.0",
    "gulp-eslint": "^1.0.0",
    "gulp-filesize": "0.0.6",
    "gulp-header": "^1.2.2",
    "gulp-imagemin": "^2.3.0",
    "gulp-jshint": "^1.11.2",
    "gulp-livereload": "^3.8.0",
    "gulp-minify-css": "^1.2.0",
    "gulp-newer": "^0.5.1",
    "gulp-notify": "^2.2.0",
    "gulp-plumber": "^1.0.1",
    "gulp-rename": "^1.2.2",
    "gulp-sass": "^2.0.4",
    "gulp-sourcemaps": "^1.5.2",
    "gulp-svgmin": "^1.2.0",
    "gulp-svgstore": "^5.0.4",
    "gulp-uglify": "^1.2.0",
    "imagemin-pngquant": "^4.1.2"
  },
  "dependencies": {
    "node-sass": "^3.2.0"
  }
</code>```

But it fails with the node-sass package.
A part of the output is this:

```<code>Cannot download "https://github.com/sass/node-sass/releases/download/v3.2.0/darwin-x64-51_binding.node": HTTP error 404 Not Found
</code>```

And then:

```<code>node-sass@3.2.0 postinstall: `node scripts/build.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the node-sass@3.2.0 postinstall script 'node scripts/build.js'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the node-sass package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     node scripts/build.js
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs node-sass
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls node-sass
npm ERR! There is likely additional logging output above.
</code>```

Node version 7.5.0 and npm version 4.1.2, OSX Sierra

Any suggestions?

答:
I had same issue using node 8.1.3. I solved downgrading to latest long term supported version of nodejs (now is the 6.11.0).

The problem is that node-sass doesn't supports some nodejs versions....

Title: Error installing node-sass dependency

Body:
I am trying to npm install a package.json with the following dependencies:

  "devDependencies": {
    "browser-sync": "^2.8.2",
    "del": "^1.2.0",
    "gulp": "^3.9.0",
    "gulp-autoprefixer": "^2.3.1",
    "gulp-babel": "^5.2.0",
    "gulp-concat": "^2.6.0",
    "gulp-eslint": "^1.0.0",
    "gulp-filesize": "0.0.6",
    "gulp-header": "^1.2.2",
    "gulp-imagemin": "^2.3.0",
    "gulp-jshint": "^1.11.2",
    "gulp-livereload": "^3.8.0",
    "gulp-minify-css": "^1.2.0",
    "gulp-newer": "^0.5.1",
    "gulp-notify": "^2.2.0",
    "gulp-plumber": "^1.0.1",
    "gulp-rename": "^1.2.2",
    "gulp-sass": "^2.0.4",
    "gulp-sourcemaps": "^1.5.2",
    "gulp-svgmin": "^1.2.0",
    "gulp-svgstore": "^5.0.4",
    "gulp-uglify": "^1.2.0",
    "imagemin-pngquant": "^4.1.2"
  },
  "dependencies": {
    "node-sass": "^3.2.0"
  }

But it fails with the node-sass package.
A part of the output is this:

Cannot download "https://github.com/sass/node-sass/releases/download/v3.2.0/darwin-x64-51_binding.node": HTTP error 404 Not Found

And then:

node-sass@3.2.0 postinstall: `node scripts/build.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the node-sass@3.2.0 postinstall script 'node scripts/build.js'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the node-sass package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     node scripts/build.js
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs node-sass
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls node-sass
npm ERR! There is likely additional logging output above.

Node version 7.5.0 and npm version 4.1.2, OSX Sierra

Any suggestions?


问:
fixed positioned text while container div moved
When my function is called to make sidebar width change from 0px to 418px, I'd like the text inside the list to stay fixed. However, if I simply use position:fixed, it would show the text before the sidebar is shown. Is there anyway to make the text stay aligned while its parent div changes size?

```<code>#sidebar ul li {
    display:inline;
    list-style-type:none;
    float:left;
    margin:0;
    border-bottom:1px solid #c6d0da;
    height:57px;
    padding:10px 0px;
}
</code>```

Javascript function to increase sidebar size:

```<code>function menu() {
    document.getElementById("sidebar").style.width = "418px";
    document.getElementById("content").style.marginLeft = "450px";
}
</code>```

答:
I updated you code, but it brokes a little the css inside the sidebar.
I changed you  innerHtml by regrouping picture and a with a div, and i used a div instead of your a element.

Please, don't use Ids like that, an Id should be unique. Use class instead. If you want to write a better javaScript code, use JQuery too. It's very, very easier to use than native javascript.

Plunker

```<code>#icon-li > div {
  white-space: nowrap;
}
#icon-li > div > * {
  display:inline-block;
  white-space: nowrap;
}
</code>```

Body:
When my function is called to make sidebar width change from 0px to 418px, I'd like the text inside the list to stay fixed. However, if I simply use position:fixed, it would show the text before the sidebar is shown. Is there anyway to make the text stay aligned while its parent div changes size?

#sidebar ul li {
    display:inline;
    list-style-type:none;
    float:left;
    margin:0;
    border-bottom:1px solid #c6d0da;
    height:57px;
    padding:10px 0px;
}

Javascript function to increase sidebar size:

function menu() {
    document.getElementById("sidebar").style.width = "418px";
    document.getElementById("content").style.marginLeft = "450px";
}

Body:
I updated you code, but it brokes a little the css inside the sidebar.
I changed you  innerHtml by regrouping picture and a with a div, and i used a div instead of your a element.

Please, don't use Ids like that, an Id should be unique. Use class instead. If you want to write a better javaScript code, use JQuery too. It's very, very easier to use than native javascript.

Plunker

#icon-li > div {
  white-space: nowrap;
}
#icon-li > div > * {
  display:inline-block;
  white-space: nowrap;
}


问:
Pass this to addEventListener() as parameter
I want to add change event to a group of checkboxes, how can I access this in my event function, so that when I do the event I can access value of the checkbox.

This is my current code:

var checkboxes = document.getElementsByClassName('cb');
Array.from(checkboxes).forEach(function(){
  this.addEventListener("change", cbChange(this), false);
});

function cbChange(ele){
  console.log(ele.value);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input class="cb" type="checkbox" name="candidate" value="1"/>
<input class="cb" type="checkbox" name="candidate" value="2"/>
<input class="cb" type="checkbox" name="candidate" value="3"/>
<input class="cb" type="checkbox" name="candidate" value="4"/></code>```

答:
Inside the forEach callback, this  does not refer to a DOM element. It doesn't refer to any useful value.

Secondly, you are immediately calling cbChange and pass its return value to addEventListener, which is undefined. But addEventListener expects to be passed a function, so you either have to pass cbChange or a function that calls cbChange.

Lastly, while you could define the event handler to accept the element as first argument, it's much simpler if it accepts the event object, because that is the default API.

Having said all that, the simplest solution would be:

```<code>var checkboxes = document.getElementsByClassName('cb');
Array.from(checkboxes).forEach(function(element){
//                                      ^^^^^^^
  element.addEventListener("change", cbChange, false);
//^^^^^^^
});

function cbChange(){
  console.log(this.value);
//            ^^^^
}
</code>```

Since inside an event handler, this refers to the element the handler is bound to, using this inside cbChange just works.

And here are some alternatives:

```<code>// Use the event object
var checkboxes = document.getElementsByClassName('cb');
Array.from(checkboxes).forEach(function(element){
  element.addEventListener("change", cbChange, false);
});

function cbChange(event){
  console.log(event.target.value);
}

// Using a wrapper that calls `cbChange`
var checkboxes = document.getElementsByClassName('cb');
Array.from(checkboxes).forEach(function(element){
  element.addEventListener("change", function() { cbChange(this); }, false);
});

function cbChange(ele){
  console.log(ele.value);
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to add change event to a group of checkboxes, how can I access this in my event function, so that when I do the event I can access value of the checkbox.

This is my current code:

var checkboxes = document.getElementsByClassName('cb');
Array.from(checkboxes).forEach(function(){
  this.addEventListener("change", cbChange(this), false);
});

function cbChange(ele){
  console.log(ele.value);
}

<input class="cb" type="checkbox" name="candidate" value="1"/>
<input class="cb" type="checkbox" name="candidate" value="2"/>
<input class="cb" type="checkbox" name="candidate" value="3"/>
<input class="cb" type="checkbox" name="candidate" value="4"/>

Body:
Inside the forEach callback, this  does not refer to a DOM element. It doesn't refer to any useful value.

Secondly, you are immediately calling cbChange and pass its return value to addEventListener, which is undefined. But addEventListener expects to be passed a function, so you either have to pass cbChange or a function that calls cbChange.

Lastly, while you could define the event handler to accept the element as first argument, it's much simpler if it accepts the event object, because that is the default API.

Having said all that, the simplest solution would be:

var checkboxes = document.getElementsByClassName('cb');
Array.from(checkboxes).forEach(function(element){
//                                      ^^^^^^^
  element.addEventListener("change", cbChange, false);
//^^^^^^^
});

function cbChange(){
  console.log(this.value);
//            ^^^^
}

Since inside an event handler, this refers to the element the handler is bound to, using this inside cbChange just works.

And here are some alternatives:

// Use the event object
var checkboxes = document.getElementsByClassName('cb');
Array.from(checkboxes).forEach(function(element){
  element.addEventListener("change", cbChange, false);
});

function cbChange(event){
  console.log(event.target.value);
}

// Using a wrapper that calls `cbChange`
var checkboxes = document.getElementsByClassName('cb');
Array.from(checkboxes).forEach(function(element){
  element.addEventListener("change", function() { cbChange(this); }, false);
});

function cbChange(ele){
  console.log(ele.value);
}


问:
Count years of increasing profits
I want to count how many years a company has increased the profit from now. So if the previous year had lower profits than this year it counts as 1 and goes one year back in past to count until there is one years profit higher than the year after that. So it must be a ongoing trend from this year (2017) so that it counts the years.

(Years of increases should be 5 not 4, sorry!)

In the picture it has to count until 2011 because there was a year(2012) without increasing profits relative to last year(2011).

So maybe its even possible with a Excel Function. Otherwise VBA is probably the way to do this.

EDIT: Is it possible to count years of steady profits, too? Like if 2015 = 5 and 2016 = 5 then this should not stop streak.

答:
edit: formula for the better explained requirements in comments (see previous versions in history):

```<code>=COLUMN(I2) - MAX(($C2:I2 < $B2:H2) * COLUMN($C2:I2), COLUMN($B2))
</code>```

Title: Count years of increasing profits

Body:
edit: formula for the better explained requirements in comments (see previous versions in history):

=COLUMN(I2) - MAX(($C2:I2 < $B2:H2) * COLUMN($C2:I2), COLUMN($B2))


问:
REST API Status Code for user not exist
Status code for object not found.

I'm making GET users/57 REST API call and this user(id=57) doesn't exist.
Shall I use 404 Status or what can be the status code used for this

答:
The 404 status code, or a Not Found error, means that the user is able to communicate with the server but it is unable to locate the requested file or resource.

This page of REST error codes and reasons to use them may help you in future.

Title: REST API Status Code for user not exist


问:
Pandas pivot_table preserve order
```<code>>>> df
   A   B   C      D
0  foo one small  1
1  foo one large  2
2  foo one large  2
3  foo two small  3
4  foo two small  3
5  bar one large  4
6  bar one small  5
7  bar two small  6
8  bar two large  7
>>> table = pivot_table(df, values='D', index=['A', 'B'],
...                     columns=['C'], aggfunc=np.sum)
>>> table
          small  large
foo  one  1      4
     two  6      NaN
bar  one  5      4
     two  6      7
</code>```

I want the output to be as shown above, but I get a sorted output.
bar comes above foo and so on.

答:
I think pivot_table doesn't have an option for sorting, but groupby has:

```<code>df.groupby(['A', 'B', 'C'], sort=False)['D'].sum().unstack('C')
Out:
C        small  large
A   B
foo one    1.0    4.0
    two    6.0    NaN
bar one    5.0    4.0
    two    6.0    7.0
</code>```

You pass the grouping columns to groupby and for the ones you want to show as column values, you use unstack.

If you don't want the index names, rename them as None:

```<code>df.groupby(['A', 'B', 'C'], sort=False)['D'].sum().rename_axis([None, None, None]).unstack(level=2)
Out:
         small  large
foo one    1.0    4.0
    two    6.0    NaN
bar one    5.0    4.0
    two    6.0    7.0
</code>```

Title: Pandas pivot_table preserve order

Body:
>>> df
   A   B   C      D
0  foo one small  1
1  foo one large  2
2  foo one large  2
3  foo two small  3
4  foo two small  3
5  bar one large  4
6  bar one small  5
7  bar two small  6
8  bar two large  7
>>> table = pivot_table(df, values='D', index=['A', 'B'],
...                     columns=['C'], aggfunc=np.sum)
>>> table
          small  large
foo  one  1      4
     two  6      NaN
bar  one  5      4
     two  6      7

I want the output to be as shown above, but I get a sorted output.
bar comes above foo and so on.

Body:
I think pivot_table doesn't have an option for sorting, but groupby has:

df.groupby(['A', 'B', 'C'], sort=False)['D'].sum().unstack('C')
Out:
C        small  large
A   B
foo one    1.0    4.0
    two    6.0    NaN
bar one    5.0    4.0
    two    6.0    7.0

You pass the grouping columns to groupby and for the ones you want to show as column values, you use unstack.

If you don't want the index names, rename them as None:

df.groupby(['A', 'B', 'C'], sort=False)['D'].sum().rename_axis([None, None, None]).unstack(level=2)
Out:
         small  large
foo one    1.0    4.0
    two    6.0    NaN
bar one    5.0    4.0
    two    6.0    7.0


问:
Why can't I access a variable declared in derived class with the object of base class
Good Evening everyone

I have created two classes namely Shape, Rectangle with Draw() method in both the classes, Rectangle class  is a derived class from Shape. I have declared a public variable  in Rectangle called num and initialized a value to it.

In the main class I have created an object of type class in following manner.

```<code>Shape s = new Rectangle();
</code>```

Now when I am trying to access num variable of rectangle class it gives error saying

“ /Users/apple/Projects/Practice/Practice/Program.cs(33,33): Error
  CS1061: 'Shape' does not contain a definition for 'num' and no
  extension method 'num' accepting a first argument of type 'Shape'
  could be found (are you missing a using directive or an assembly
  reference?) (CS1061) (Practice)”

My Understanding : The statement new Rectangle(); creates an object of type Rectangle in the memory and its reference is stored in object s of type Shape. So the object s should have access to variable num defined in rectangle class. Please make me understand this concept why we can’t access num variable from Object of type Shape.

Pls find the attached screenshot.

答:
Try to change

```<code>Shape s - new Rectangle();
</code>```

to

```<code>Rectangle s = new Rectangle();
</code>```

Shape s has no num since it is Shape not Rectangle

Body:
Good Evening everyone

I have created two classes namely Shape, Rectangle with Draw() method in both the classes, Rectangle class  is a derived class from Shape. I have declared a public variable  in Rectangle called num and initialized a value to it.

In the main class I have created an object of type class in following manner.

Shape s = new Rectangle();

Now when I am trying to access num variable of rectangle class it gives error saying

“ /Users/apple/Projects/Practice/Practice/Program.cs(33,33): Error
  CS1061: 'Shape' does not contain a definition for 'num' and no
  extension method 'num' accepting a first argument of type 'Shape'
  could be found (are you missing a using directive or an assembly
  reference?) (CS1061) (Practice)”

My Understanding : The statement new Rectangle(); creates an object of type Rectangle in the memory and its reference is stored in object s of type Shape. So the object s should have access to variable num defined in rectangle class. Please make me understand this concept why we can’t access num variable from Object of type Shape.

Pls find the attached screenshot.

Body:
Try to change

Shape s - new Rectangle();

to

Rectangle s = new Rectangle();

Shape s has no num since it is Shape not Rectangle


问:
what is the time complexity (big O) of a recursive function?
Does a recursive function have a time complexity of it's own.
Like the the time complexity of a for loop which is looping 'n' time is Big O(n).
Similarly does a recursive function have a fixed time complexity or does it depend on the problem.

答:
In addition, recursive function like this:

```<code>func linear(n):
    return (n <= 1) ? 1 : n * linear(n-1)
</code>```

Has complexity O(n).

But after this example

```<code>func exponential(n):
    if n <= 1: return 1
    exponential(n-1)
    exponential(n-1)
</code>```

You can think it degrades 2n, although real complexity is O(2^n)

This graph image would make more clear

Body:
In addition, recursive function like this:

func linear(n):
    return (n <= 1) ? 1 : n * linear(n-1)

Has complexity O(n).

But after this example

func exponential(n):
    if n <= 1: return 1
    exponential(n-1)
    exponential(n-1)

You can think it degrades 2n, although real complexity is O(2^n)

This graph image would make more clear


答:
there are couple of reasons why a bootloader wont work:

the bootloader is not in the first sector of the USB/Floppy/etc.

the bootloader is not EXACTLY 512 bytes long

you are missing the 0xAA55 signature at the last 2 bytes of the bootloader

in your example i assume you have the wrong bootloader size ( it is not 512 bytes )

try replacing

```<code>rb 7E00h-2-$
db 055h,0AAh
</code>```

with

```<code>TIMES 510-($-$$) DB 0
DW 0xAA55
</code>```

this ensures that your file is exactly 512 bytes long and that is has the required bootloader signature

Title: FASM - Boot sector on USB don't work

Body:
in first, sorry for my bad english, i'm french.
At the moment, i learn asm with fasm to test boot sector programming.

I have make a simple boot program, i have compiled it and i write boot.bin in first sector of my usb.

But when i boot on my PC or in virtualbox, drive isn't found....

Boot sector code:

;=======================================================================
;   a simpliest 1.44 bootable image by shoorick ;)
;=======================================================================
_bs equ 512
_st equ 18
_hd equ 2
_tr equ 80
;=======================================================================
    org 7C00h
    jmp start
    nop
;=====================================================
    db  "HE-HE OS";     ; 8
    dw  _bs             ; b/s
    db  1               ; s/c
    dw  1               ; rs
    db  2               ; fats
    dw  224             ; rde
    dw  2880            ; as
    db  0F0h            ; media
    dw  9               ; s/fat
    dw  _st             ; s/t
    dw  _hd             ; h
    dd  0               ; hs
    dd  0               ; --
    db  0               ; drv
    db  0               ; --
    db  29h             ; ebr
    dd  0               ; sn
    db  "NO NAME    ";  ; 11
    db  "FAT12   ";     ; 8
;=====================================================
start:
    mov   ax,cs
    mov   ds,ax
    mov   cx,count
    mov   si,hello
    mov   bx,7
    mov   ah,0Eh
@@:
    lodsb
    int   10h
    loop  @B
    xor   ah,ah
    int   16h
    int   19h

hello   db "Hi! This is disk-invalid!"
count = $ - hello

;=======================================================================
    rb 7E00h-2-$
    db 055h,0AAh
;=======================================================================

This code is provide by examples of fasm's website.

Body:
there are couple of reasons why a bootloader wont work:

the bootloader is not in the first sector of the USB/Floppy/etc.

the bootloader is not EXACTLY 512 bytes long

you are missing the 0xAA55 signature at the last 2 bytes of the bootloader

in your example i assume you have the wrong bootloader size ( it is not 512 bytes )

try replacing

rb 7E00h-2-$
db 055h,0AAh

with

TIMES 510-($-$$) DB 0
DW 0xAA55

this ensures that your file is exactly 512 bytes long and that is has the required bootloader signature


问:
How to concat data from two observables
I have two observables:       </p>

```<code> Observable <Profile> profileObservable = briteDatabase.createQuery(UserMapper.Table.NAME, sql, String.valueOf(userId)).mapToOneOrDefault(UserMapper.MAPPER, null);
 Observable <List<Car>> carObservable = briteDatabase.createQuery(CarMapper.Table.NAME, sql, String.valueOf(userId)).mapToOneOrDefault(CarMapper.MAPPER, null);

 public class Profile {
 int id;
 String name;
 ArrayList<Car> car;
 ...
 }

 public class Car {
 int id;
 String brand;
 ...
 }
</code>```

<p>I need to get list of cars from carObservable and put it to profileObservable (put list of car to Profile), inside method like this: </p>

```<code>    @Override
public Observable<Profile> getProfile(String userId) {
    String sql = String.format("SELECT %s FROM %s WHERE %s=?", TextUtils.join(",", UserMapper.PROJECTION), UserMapper.Table.NAME, UserMapper.Columns.ID);

    Observable <Profile> profileObservable = briteDatabase.createQuery(UserMapper.Table.NAME, sql, String.valueOf(userId)).mapToOneOrDefault(UserMapper.MAPPER, null);

    Observable <List<Car>> carsObservable = getCars(String userId);

    /*
     Some important method to concat and return Observable <Profile>. I'm only beginner at RxJava(

   */

}
</code>```

答:
Did you try the concat operator, I dont know if I understand quite well your use case, but in case you just need to go through the list of car and then profile, just concat one after the other

```<code>@Test
public void testContact() {
    Observable.concat(Observable.just("Hello"),
                      Observable.just("reactive"),
                      Observable.just("world"))
            .subscribe(System.out::println);
}
</code>```

If you want to initiate in the RxJava world take a look here https://github.com/politrons/reactive

Title: How to concat data from two observables

Body:
I have two observables:

 Observable <Profile> profileObservable = briteDatabase.createQuery(UserMapper.Table.NAME, sql, String.valueOf(userId)).mapToOneOrDefault(UserMapper.MAPPER, null);
 Observable <List<Car>> carObservable = briteDatabase.createQuery(CarMapper.Table.NAME, sql, String.valueOf(userId)).mapToOneOrDefault(CarMapper.MAPPER, null);

 public class Profile {
 int id;
 String name;
 ArrayList<Car> car;
 ...
 }

 public class Car {
 int id;
 String brand;
 ...
 }

I need to get list of cars from carObservable and put it to profileObservable (put list of car to Profile), inside method like this:

    @Override
public Observable<Profile> getProfile(String userId) {
    String sql = String.format("SELECT %s FROM %s WHERE %s=?", TextUtils.join(",", UserMapper.PROJECTION), UserMapper.Table.NAME, UserMapper.Columns.ID);

    Observable <Profile> profileObservable = briteDatabase.createQuery(UserMapper.Table.NAME, sql, String.valueOf(userId)).mapToOneOrDefault(UserMapper.MAPPER, null);

    Observable <List<Car>> carsObservable = getCars(String userId);

    /*
     Some important method to concat and return Observable <Profile>. I'm only beginner at RxJava(

   */

}

Body:
Did you try the concat operator, I dont know if I understand quite well your use case, but in case you just need to go through the list of car and then profile, just concat one after the other

@Test
public void testContact() {
    Observable.concat(Observable.just("Hello"),
                      Observable.just("reactive"),
                      Observable.just("world"))
            .subscribe(System.out::println);
}

If you want to initiate in the RxJava world take a look here https://github.com/politrons/reactive


问:
Inserting a record with many columns into a MariaDB Columnstore table takes a long time
I have a table with 50 columns in a MariaDB columnstore and it takes more than 5 seconds to insert a single record. I am very surprised to see this.

I am not sure if it is expected since there are too many columns or there could be some settings that I might have done wrong.

```<code>CREATE TABLE `mytable` (
   id` int(11) NOT NULL COMMENT 'autoincrement=1',
   // mostly int(10) and varchar(20) columns
) ENGINE=Columnstore DEFAULT CHARSET=latin1;
</code>```

Thanks

答:
Because of the way data is stored, it must unpack 50 compressed blobs, each holding up to 64K rows' worth of one column, add the new cell, then recompute the min, max, etc, and recompress it.

It is much better to gather lots of rows (thousands) and insert them all at once.  Then it might take not much more than 5 seconds for the entire batch, thereby being only an average of a few milliseconds per row.

Would you describe your application?  Columnstore is not the solution for everyone; it has a rather narrow niche.  Perhaps InnoDB would be better for your app.

Body:
I have a table with 50 columns in a MariaDB columnstore and it takes more than 5 seconds to insert a single record. I am very surprised to see this.

I am not sure if it is expected since there are too many columns or there could be some settings that I might have done wrong.

CREATE TABLE `mytable` (
   id` int(11) NOT NULL COMMENT 'autoincrement=1',
   // mostly int(10) and varchar(20) columns
) ENGINE=Columnstore DEFAULT CHARSET=latin1;

Thanks


问:
Grails, need to read a textfile using the url in order to get a ssl-certificate
To order a certificat, tomcat-8.5.9, the publisher sent us a textfile an told us to make it accessable from our url e.g. https://my.site.com/theTextFile.txt

How can I do that? Do I need to include it in my GrailsProject or can I put directly on the server?

答:
I think it means what it says on the tin, and all depends on your setup:

https://my.site.com/theTextFile.txt =

does your site run SSL ? if so what is in front of port 80 ? apache or equivalent webserver  then yes as you say you could add the text file to your virtual folder of your app and serve it but obviously that may be serving your port 8080 traffic so you could introduce a rewrite rule in apache to take care of it or you could put the text file in your grails application:

As an example in my url mapping I have a line like this:

"/googleXXXXXXX.html" (view: '/googleVerification')

The contents of the view is simply

google-site-verification: googlea6XXXXX

So do the same

"/theTextFile.txt" (view: '/textFile')

In the root of your grails-app/views/textFile contains:

SOMETEXT


问:
Exploding values in an array and not including it in the mysql_query
I have the values in the database IT213|---|IT214|---|IT215
and want to explode those values.

```<code>$subject_query=mysql_query("select * from students where id='$get_id'") or die(mysql_error());
$subject_row =mysql_fetch_array($subject_query);
$explode = explode("|---|", $subject_row['subject']);
foreach($explode as $subjects)
    {
    $query=mysql_query("select * from subject where code != ('$subjects') ") or die(mysql_error());
    }
while($row=mysql_fetch_array($query)) { ?>
    <option>
    //echo to show values that are not included in the database
    </option>
    <?php }  ?>
</code>```

How do i not include the values to be echoed from the list of values that are already in my database?

For example, i already have IT215 in my database, i want my option box to not include IT215 in the Option box.(Selections are from IT215, IT216, IT217 down to IT216 and IT217 only)

答:
Queries can do plenty of powerful things.

```<code>SELECT * FROM subject
WHERE FIND_IN_SET(code, (
    SELECT REPLACE(subject, '|---|', ',')
    FROM students
    WHERE id = ?
)) = 0
</code>```

Of course ideally I'd tear your database apart and normalise it so that you can achieve the result with joins instead, but I'll take what I can get.

I'd also probably slap you for using functions that don't even exists anymore because they were so bad. Pick up PDO, it's so much better.

Body:
I have the values in the database IT213|---|IT214|---|IT215
and want to explode those values.

$subject_query=mysql_query("select * from students where id='$get_id'") or die(mysql_error());
$subject_row =mysql_fetch_array($subject_query);
$explode = explode("|---|", $subject_row['subject']);
foreach($explode as $subjects)
    {
    $query=mysql_query("select * from subject where code != ('$subjects') ") or die(mysql_error());
    }
while($row=mysql_fetch_array($query)) { ?>
    <option>
    //echo to show values that are not included in the database
    </option>
    <?php }  ?>

How do i not include the values to be echoed from the list of values that are already in my database?

For example, i already have IT215 in my database, i want my option box to not include IT215 in the Option box.(Selections are from IT215, IT216, IT217 down to IT216 and IT217 only)

Body:
Queries can do plenty of powerful things.

SELECT * FROM subject
WHERE FIND_IN_SET(code, (
    SELECT REPLACE(subject, '|---|', ',')
    FROM students
    WHERE id = ?
)) = 0

Of course ideally I'd tear your database apart and normalise it so that you can achieve the result with joins instead, but I'll take what I can get.

I'd also probably slap you for using functions that don't even exists anymore because they were so bad. Pick up PDO, it's so much better.


问:
Module not found: Error: Cannot resolve module 'fs' in
I am trying to integrate ADAL JS sample code:

https://github.com/AzureAD/azure-activedirectory-library-for-nodejs/blob/master/sample/client-credentials-sample.js

into a sharepoint framework client webpart:

my code is very simple, I already installed with NPM, adal, fs, node-fs, etc.

```<code>However I see this error

./~/adal-node/lib/util.js
Module not found: Error: Cannot resolve module 'fs' in /Users/luis.valencia/Documents/GraphSamples/Sample1/node_modules/adal-node/lib
resolve module fs in /Users/luis.valencia/Documents/GraphSamples/Sample1/node_modules/adal-node/lib
  looking for modules in /Users/luis.valencia/Documents/GraphSamples/Sample1/node_modules/adal-node/lib
    /Users/luis.valencia/Documents/GraphSamples/Sample1/node_modules/adal-node/lib/fs doesn't exist (module as directory)
    resolve 'file' fs in /Users/luis.valencia/Documents/GraphSamples/Sample1/node_modules/adal-node/lib
      resolve file
</code>```

and the code I have is this:

I even commented the require JS line, but it looks like adal js library itself uses FS which doesnt seem to be correctly installed?

```<code>import {
  BaseClientSideWebPart,
  IPropertyPaneSettings,
  IWebPartContext,
  PropertyPaneTextField
} from '@microsoft/sp-client-preview';

import styles from './Hellomsgraph.module.scss';
import * as strings from 'hellomsgraphStrings';
import { IHellomsgraphWebPartProps } from './IHellomsgraphWebPartProps';
import * as MicrosoftGraph from "microsoft-graph"

const accessToken:string = "";
//var fs = require('fs');
var adal = require('adal-node');
var AuthenticationContext = adal.AuthenticationContext;

export default class HellomsgraphWebPart extends BaseClientSideWebPart<IHellomsgraphWebPartProps> {

  public constructor(context: IWebPartContext) {
    super(context);
  }

  public render(): void {
    this.domElement.innerHTML = `
      <div class="${styles.hellomsgraph}">
        <div class="${styles.container}">
          <div class="ms-Grid-row ms-bgColor-themeDark ms-fontColor-white ${styles.row}">
            <div class="ms-Grid-col ms-u-lg10 ms-u-xl8 ms-u-xlPush2 ms-u-lgPush1">
              <span class="ms-font-xl ms-fontColor-white">Welcome to SharePoint!</span>
              <p class="ms-font-l ms-fontColor-white">Customize SharePoint experiences using Web Parts.</p>
              <p class="ms-font-l ms-fontColor-white">${this.properties.description}</p>
              <a href="https://github.com/SharePoint/sp-dev-docs/wiki" class="ms-Button ${styles.button}">
                <span class="ms-Button-label">Learn more</span>
              </a>
            </div>
          </div>
        </div>
      </div>`;
  }

  protected get propertyPaneSettings(): IPropertyPaneSettings {
    return {
      pages: [
        {
          header: {
            description: strings.PropertyPaneDescription
          },
          groups: [
            {
              groupName: strings.BasicGroupName,
              groupFields: [
                PropertyPaneTextField('description', {
                  label: strings.DescriptionFieldLabel
                })
              ]
            }
          ]
        }
      ]
    };
  }
}
</code>```

答:
add this to webpack.config.js

```<code>target: 'node',
</code>```

See here and here

Body:
I am trying to integrate ADAL JS sample code:

https://github.com/AzureAD/azure-activedirectory-library-for-nodejs/blob/master/sample/client-credentials-sample.js

into a sharepoint framework client webpart:

my code is very simple, I already installed with NPM, adal, fs, node-fs, etc.

However I see this error

./~/adal-node/lib/util.js
Module not found: Error: Cannot resolve module 'fs' in /Users/luis.valencia/Documents/GraphSamples/Sample1/node_modules/adal-node/lib
resolve module fs in /Users/luis.valencia/Documents/GraphSamples/Sample1/node_modules/adal-node/lib
  looking for modules in /Users/luis.valencia/Documents/GraphSamples/Sample1/node_modules/adal-node/lib
    /Users/luis.valencia/Documents/GraphSamples/Sample1/node_modules/adal-node/lib/fs doesn't exist (module as directory)
    resolve 'file' fs in /Users/luis.valencia/Documents/GraphSamples/Sample1/node_modules/adal-node/lib
      resolve file

and the code I have is this:

I even commented the require JS line, but it looks like adal js library itself uses FS which doesnt seem to be correctly installed?

import {
  BaseClientSideWebPart,
  IPropertyPaneSettings,
  IWebPartContext,
  PropertyPaneTextField
} from '@microsoft/sp-client-preview';

import styles from './Hellomsgraph.module.scss';
import * as strings from 'hellomsgraphStrings';
import { IHellomsgraphWebPartProps } from './IHellomsgraphWebPartProps';
import * as MicrosoftGraph from "microsoft-graph"

const accessToken:string = "";
//var fs = require('fs');
var adal = require('adal-node');
var AuthenticationContext = adal.AuthenticationContext;

export default class HellomsgraphWebPart extends BaseClientSideWebPart<IHellomsgraphWebPartProps> {

  public constructor(context: IWebPartContext) {
    super(context);
  }

  public render(): void {
    this.domElement.innerHTML = `

              Welcome to SharePoint!

Customize SharePoint experiences using Web Parts.

${this.properties.description}

                Learn more

`;
  }

  protected get propertyPaneSettings(): IPropertyPaneSettings {
    return {
      pages: [
        {
          header: {
            description: strings.PropertyPaneDescription
          },
          groups: [
            {
              groupName: strings.BasicGroupName,
              groupFields: [
                PropertyPaneTextField('description', {
                  label: strings.DescriptionFieldLabel
                })
              ]
            }
          ]
        }
      ]
    };
  }
}

Body:
add this to webpack.config.js

target: 'node',

See here and here


问:
How to define a variable string format specifier
I have this line of code

```<code>// valueX is a long double (long double is a huge floating point)
NSString *value = [NSString stringWithFormat: @"%.10Lg", valueX];
</code>```

This format specifier is specifying up to 10 decimal digits but I don't want to hard code this to 10.

I have this variable numberOfDigits that I want to be used to define the number of digits. For those itching to down vote this question, it is not so easy as it seems. I cannot substitute the 10 with %@ because %.10Lg is a format specifier by itself.

OK, I can create a bunch of strings like @"%.5Lg", @"%.8Lg", @"%.9Lg"... and switch that, but I wonder if there is another way...

答:
There is, if you read the manual pages for format specifiers.  You can replace the precision with *, which means it will get taken from a parameter instead.

```<code>int numDigits = 10;
NSString *value = [NSString stringWithFormat:@"%.*Lg", numDigits, valueX];
</code>```

I couldn't find this in the core foundation reference, but I know that this is written in the man 3 printf man page.

Body:
I have this line of code

// valueX is a long double (long double is a huge floating point)
NSString *value = [NSString stringWithFormat: @"%.10Lg", valueX];

This format specifier is specifying up to 10 decimal digits but I don't want to hard code this to 10.

I have this variable numberOfDigits that I want to be used to define the number of digits. For those itching to down vote this question, it is not so easy as it seems. I cannot substitute the 10 with %@ because %.10Lg is a format specifier by itself.

OK, I can create a bunch of strings like @"%.5Lg", @"%.8Lg", @"%.9Lg"... and switch that, but I wonder if there is another way...

Body:
There is, if you read the manual pages for format specifiers.  You can replace the precision with *, which means it will get taken from a parameter instead.

int numDigits = 10;
NSString *value = [NSString stringWithFormat:@"%.*Lg", numDigits, valueX];

I couldn't find this in the core foundation reference, but I know that this is written in the man 3 printf man page.


问:
Working with mutable values in vcr
I have a vcr casette like this

```<code>---
http_interactions:
- request:
    method: post
    uri: https://control.msg91.com/api/sendotp.php?message=Your%20otp%20is%200805&mobile=919446733017&otp=0805&sender=TESTER
    body:
      encoding: UTF-8
      string: ''
    headers:
      Accept-Encoding:
      - gzip;q=1.0,deflate;q=0.6,identity;q=0.3
      Accept:
      - "*/*"
      User-Agent:
      - Ruby
      Host:
      - control.msg91.com
      Cache-Control:
      - no-cache
  response:
    status:
      code: 200
      message: OK
    headers:
      Server:
      - nginx
      Date:
      - Sat, 08 Jul 2017 13:54:17 GMT
      Content-Type:
      - text/html
      Transfer-Encoding:
      - chunked
      Connection:
      - keep-alive
      Set-Cookie:
      - PHPSESSID=od25ntah2t8nf47i947dmevbv0; expires=Sun, 09-Jul-2017 13:54:17 GMT;
        Max-Age=86400; path=/; HttpOnly
      Expires:
      - Thu, 19 Nov 1981 08:52:00 GMT
      Cache-Control:
      - no-store, no-cache, must-revalidate, post-check=0, pre-check=0
      Pragma:
      - no-cache
      X-Frame-Options:
      - SAMEORIGIN
      X-Xss-Protection:
      - 1; mode=block
    body:
      encoding: UTF-8
      string: '{"message":"376768737871373032333335","type":"success"}'
    http_version:
  recorded_at: Sat, 08 Jul 2017 13:54:17 GMT
recorded_with: VCR 3.0.3
</code>```

In the uri there is otp and message fields which are random values on each requests. As these two are mutable(always changing) how can I ignore these 2 fields in vcr so that vcr works normal?

答:
Looks like vcr has a built in solution available for this.

Adding this to the VCR config block works

```<code>  config.default_cassette_options = {
      :match_requests_on => [:method,
                             VCR.request_matchers.uri_without_params(:otp, :message)]
  }
</code>```

Here otp and message are the two things that I need to ignore

Title: Working with mutable values in vcr

Body:
I have a vcr casette like this

---
http_interactions:
- request:
    method: post
    uri: https://control.msg91.com/api/sendotp.php?message=Your%20otp%20is%200805&mobile=919446733017&otp=0805&sender=TESTER
    body:
      encoding: UTF-8
      string: ''
    headers:
      Accept-Encoding:
      - gzip;q=1.0,deflate;q=0.6,identity;q=0.3
      Accept:
      - "*/*"
      User-Agent:
      - Ruby
      Host:
      - control.msg91.com
      Cache-Control:
      - no-cache
  response:
    status:
      code: 200
      message: OK
    headers:
      Server:
      - nginx
      Date:
      - Sat, 08 Jul 2017 13:54:17 GMT
      Content-Type:
      - text/html
      Transfer-Encoding:
      - chunked
      Connection:
      - keep-alive
      Set-Cookie:
      - PHPSESSID=od25ntah2t8nf47i947dmevbv0; expires=Sun, 09-Jul-2017 13:54:17 GMT;
        Max-Age=86400; path=/; HttpOnly
      Expires:
      - Thu, 19 Nov 1981 08:52:00 GMT
      Cache-Control:
      - no-store, no-cache, must-revalidate, post-check=0, pre-check=0
      Pragma:
      - no-cache
      X-Frame-Options:
      - SAMEORIGIN
      X-Xss-Protection:
      - 1; mode=block
    body:
      encoding: UTF-8
      string: '{"message":"376768737871373032333335","type":"success"}'
    http_version:
  recorded_at: Sat, 08 Jul 2017 13:54:17 GMT
recorded_with: VCR 3.0.3

In the uri there is otp and message fields which are random values on each requests. As these two are mutable(always changing) how can I ignore these 2 fields in vcr so that vcr works normal?

Body:
Looks like vcr has a built in solution available for this.

Adding this to the VCR config block works

  config.default_cassette_options = {
      :match_requests_on => [:method,
                             VCR.request_matchers.uri_without_params(:otp, :message)]
  }

Here otp and message are the two things that I need to ignore