问:
make Scrollable or fixed mode in Tablayout for dynamic number of Tabs

I want tabMode scrollable with tabFilled with tabs(having single line title). As number of Tab and their title is dynamic in my app. How could I handle them
  when I set given property. Title of tabs come's in two lines.when number of tab is greater.

```<code>    app:tabGravity="fill"
    app:tabMaxWidth="0dp"
    app:tabMode="fixed"
</code>```

and when number of tabs are less and tabMode is set to scrollable. then extra space shown like below.

how could I make a Tablayout to work in all phones and with one line text .
Simply remove spaces for second screen and make single line for 1st Image.

I know I have to change it's tabMode and tabGravity for these two cases but How could I know when to change it's tabMode and tabGravity. It may be a case that I have only three tab's but their title are long and they are filling entire space. and some time we have 5 tabs with little title . They easily fit's in screen.

答:
try this one

```<code>public class SlidingTabLayout extends HorizontalScrollView {
    /**
     * Allows complete control over the colors drawn in the tab layout. Set with
     * {@link #setCustomTabColorizer(TabColorizer)}.
     */
    public interface TabColorizer {

        /**
         * @return return the color of the indicator used when {@code position} is selected.
         */
        int getIndicatorColor(int position);

    }

    private static final int TITLE_OFFSET_DIPS = 24;
    private static final int TAB_VIEW_PADDING_DIPS = 16;
    private static final int TAB_VIEW_TEXT_SIZE_SP = 12;

    private int mTitleOffset;

    private int mTabViewLayoutId;
    private int mTabViewTextViewId;
    private boolean mDistributeEvenly;

    private ViewPager mViewPager;
    private SparseArray<String> mContentDescriptions = new SparseArray<String>();
    private ViewPager.OnPageChangeListener mViewPagerPageChangeListener;

    private final SlidingTabStrip mTabStrip;

    public SlidingTabLayout(Context context) {
        this(context, null);
    }

    public SlidingTabLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public SlidingTabLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        // Disable the Scroll Bar
        setHorizontalScrollBarEnabled(false);
        // Make sure that the Tab Strips fills this View
        setFillViewport(true);

        mTitleOffset = (int) (TITLE_OFFSET_DIPS * getResources().getDisplayMetrics().density);

        mTabStrip = new SlidingTabStrip(context);
        addView(mTabStrip, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
    }

    /**
     * Set the custom {@link TabColorizer} to be used.
     *
     * If you only require simple custmisation then you can use
     * {@link #setSelectedIndicatorColors(int...)} to achieve
     * similar effects.
     */
    public void setCustomTabColorizer(TabColorizer tabColorizer) {
        mTabStrip.setCustomTabColorizer(tabColorizer);
    }

    public void setDistributeEvenly(boolean distributeEvenly) {
        mDistributeEvenly = distributeEvenly;
    }

    /**
     * Sets the colors to be used for indicating the selected tab. These colors are treated as a
     * circular array. Providing one color will mean that all tabs are indicated with the same color.
     */
    public void setSelectedIndicatorColors(int... colors) {
        mTabStrip.setSelectedIndicatorColors(colors);
    }

    /**
     * Set the {@link ViewPager.OnPageChangeListener}. When using {@link SlidingTabLayout} you are
     * required to set any {@link ViewPager.OnPageChangeListener} through this method. This is so
     * that the layout can update it's scroll position correctly.
     *
     * @see ViewPager#setOnPageChangeListener(ViewPager.OnPageChangeListener)
     */
    public void setOnPageChangeListener(ViewPager.OnPageChangeListener listener) {
        mViewPagerPageChangeListener = listener;
    }

    /**
     * Set the custom layout to be inflated for the tab views.
     *
     * @param layoutResId Layout id to be inflated
     * @param textViewId id of the {@link TextView} in the inflated view
     */
    public void setCustomTabView(int layoutResId, int textViewId) {
        mTabViewLayoutId = layoutResId;
        mTabViewTextViewId = textViewId;
    }

    /**
     * Sets the associated view pager. Note that the assumption here is that the pager content
     * (number of tabs and tab titles) does not change after this call has been made.
     */
    public void setViewPager(ViewPager viewPager) {
        mTabStrip.removeAllViews();

        mViewPager = viewPager;
        if (viewPager != null) {
            viewPager.setOnPageChangeListener(new InternalViewPagerListener());
            populateTabStrip();
        }
    }

    /**
     * Create a default view to be used for tabs. This is called if a custom tab view is not set via
     * {@link #setCustomTabView(int, int)}.
     */
    @SuppressLint("NewApi") protected TextView createDefaultTabView(Context context) {
        TextView textView = new TextView(context);
        textView.setGravity(Gravity.CENTER);
        textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, TAB_VIEW_TEXT_SIZE_SP);
        textView.setTypeface(Typeface.DEFAULT_BOLD);
        textView.setLayoutParams(new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));

        TypedValue outValue = new TypedValue();
        getContext().getTheme().resolveAttribute(android.R.attr.selectableItemBackground,
                outValue, true);
        textView.setBackgroundResource(outValue.resourceId);
        textView.setAllCaps(true);

        int padding = (int) (TAB_VIEW_PADDING_DIPS * getResources().getDisplayMetrics().density);
        textView.setPadding(padding, padding, padding, padding);

        return textView;
    }

    /*private void populateTabStrip() {
        final PagerAdapter adapter = mViewPager.getAdapter();
        final View.OnClickListener tabClickListener = new TabClickListener();

        for (int i = 0; i < adapter.getCount(); i++) {
            View tabView = null;
            TextView tabTitleView = null;

            if (mTabViewLayoutId != 0) {
                // If there is a custom tab view layout id set, try and inflate it
                tabView = LayoutInflater.from(getContext()).inflate(mTabViewLayoutId, mTabStrip,
                        false);
                tabTitleView = (TextView) tabView.findViewById(mTabViewTextViewId);
            }

            if (tabView == null) {
                tabView = createDefaultTabView(getContext());
            }

            if (tabTitleView == null && TextView.class.isInstance(tabView)) {
                tabTitleView = (TextView) tabView;
            }

            if (mDistributeEvenly) {
                LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) tabView.getLayoutParams();
                lp.width = 0;
                lp.weight = 1;
            }

            tabTitleView.setText(adapter.getPageTitle(i));
            tabView.setOnClickListener(tabClickListener);
            String desc = mContentDescriptions.get(i, null);
            if (desc != null) {
                tabView.setContentDescription(desc);
            }

            mTabStrip.addView(tabView);
            if (i == mViewPager.getCurrentItem()) {
                tabView.setSelected(true);
            }
        }
    }*/

    @SuppressWarnings("deprecation")    private void populateTabStrip() {
        final PagerAdapter adapter = mViewPager.getAdapter();
        final View.OnClickListener tabClickListener = new TabClickListener();

        for (int i = 0; i < adapter.getCount(); i++) {
            View tabView = null;
            TextView tabTitleView = null;

            if (mTabViewLayoutId != 0) {
                // If there is a custom tab view layout id set, try and inflate it
                tabView = LayoutInflater.from(getContext()).inflate(mTabViewLayoutId, mTabStrip, false);
                tabTitleView = (TextView) tabView.findViewById(mTabViewTextViewId);
            }

            if (tabView == null) {
                tabView = createDefaultTabView(getContext());
            }

            if (tabTitleView == null && TextView.class.isInstance(tabView)) {
                tabTitleView = (TextView) tabView;
            }

            if (mDistributeEvenly) {
                LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) tabView.getLayoutParams();
                lp.width = 0;
                lp.weight = 1;
            }

            tabTitleView.setText(adapter.getPageTitle(i));
            tabView.setOnClickListener(tabClickListener);
            String desc = mContentDescriptions.get(i, null);
            if (desc != null) {
                tabView.setContentDescription(desc);
            }

            mTabStrip.addView(tabView);
            if (i == mViewPager.getCurrentItem()) {
                tabView.setSelected(true);
            }
            tabTitleView.setTextColor(getResources().getColorStateList(R.drawable.selector));
            tabTitleView.setTextSize(14);
        }
    }

    public void setContentDescription(int i, String desc) {
        mContentDescriptions.put(i, desc);
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();

        if (mViewPager != null) {
            scrollToTab(mViewPager.getCurrentItem(), 0);
        }
    }

    private void scrollToTab(int tabIndex, int positionOffset) {
        final int tabStripChildCount = mTabStrip.getChildCount();
        if (tabStripChildCount == 0 || tabIndex < 0 || tabIndex >= tabStripChildCount) {
            return;
        }

        View selectedChild = mTabStrip.getChildAt(tabIndex);
        if (selectedChild != null) {
            int targetScrollX = selectedChild.getLeft() + positionOffset;

            if (tabIndex > 0 || positionOffset > 0) {
                // If we're not at the first child and are mid-scroll, make sure we obey the offset
                targetScrollX -= mTitleOffset;
            }

            scrollTo(targetScrollX, 0);
        }
    }

    private class InternalViewPagerListener implements ViewPager.OnPageChangeListener {
        private int mScrollState;

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            int tabStripChildCount = mTabStrip.getChildCount();
            if ((tabStripChildCount == 0) || (position < 0) || (position >= tabStripChildCount)) {
                return;
            }

            mTabStrip.onViewPagerPageChanged(position, positionOffset);

            View selectedTitle = mTabStrip.getChildAt(position);
            int extraOffset = (selectedTitle != null)
                    ? (int) (positionOffset * selectedTitle.getWidth())
                    : 0;
            scrollToTab(position, extraOffset);

            if (mViewPagerPageChangeListener != null) {
                mViewPagerPageChangeListener.onPageScrolled(position, positionOffset,
                        positionOffsetPixels);
            }
        }

        @Override
        public void onPageScrollStateChanged(int state) {
            mScrollState = state;

            if (mViewPagerPageChangeListener != null) {
                mViewPagerPageChangeListener.onPageScrollStateChanged(state);
            }
        }

        @Override
        public void onPageSelected(int position) {
            if (mScrollState == ViewPager.SCROLL_STATE_IDLE) {
                mTabStrip.onViewPagerPageChanged(position, 0f);
                scrollToTab(position, 0);
            }
            for (int i = 0; i < mTabStrip.getChildCount(); i++) {
                mTabStrip.getChildAt(i).setSelected(position == i);
            }
            if (mViewPagerPageChangeListener != null) {
                mViewPagerPageChangeListener.onPageSelected(position);
            }
        }

    }

    private class TabClickListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            for (int i = 0; i < mTabStrip.getChildCount(); i++) {
                if (v == mTabStrip.getChildAt(i)) {
                    mViewPager.setCurrentItem(i);
                    return;
                }
            }
        }
    }

}
</code>```

SlidingTabStrip.java

```<code>class SlidingTabStrip extends LinearLayout {

    private static final int DEFAULT_BOTTOM_BORDER_THICKNESS_DIPS = 0;
    private static final byte DEFAULT_BOTTOM_BORDER_COLOR_ALPHA = 0x26;
    private static final int SELECTED_INDICATOR_THICKNESS_DIPS = 3;
    private static final int DEFAULT_SELECTED_INDICATOR_COLOR = 0xFF33B5E5;

    private final int mBottomBorderThickness;
    private final Paint mBottomBorderPaint;

    private final int mSelectedIndicatorThickness;
    private final Paint mSelectedIndicatorPaint;

    private final int mDefaultBottomBorderColor;

    private int mSelectedPosition;
    private float mSelectionOffset;

    private SlidingTabLayout.TabColorizer mCustomTabColorizer;
    private final SimpleTabColorizer mDefaultTabColorizer;

    SlidingTabStrip(Context context) {
        this(context, null);
    }

    SlidingTabStrip(Context context, AttributeSet attrs) {
        super(context, attrs);
        setWillNotDraw(false);

        final float density = getResources().getDisplayMetrics().density;

        TypedValue outValue = new TypedValue();
        context.getTheme().resolveAttribute(R.attr.colorForeground, outValue, true);
        final int themeForegroundColor =  outValue.data;

        mDefaultBottomBorderColor = setColorAlpha(themeForegroundColor, DEFAULT_BOTTOM_BORDER_COLOR_ALPHA);

        mDefaultTabColorizer = new SimpleTabColorizer();
        mDefaultTabColorizer.setIndicatorColors(DEFAULT_SELECTED_INDICATOR_COLOR);

        mBottomBorderThickness = (int) (DEFAULT_BOTTOM_BORDER_THICKNESS_DIPS * density);
        mBottomBorderPaint = new Paint();
        mBottomBorderPaint.setColor(mDefaultBottomBorderColor);

        mSelectedIndicatorThickness = (int) (SELECTED_INDICATOR_THICKNESS_DIPS * density);
        mSelectedIndicatorPaint = new Paint();
    }

    void setCustomTabColorizer(SlidingTabLayout.TabColorizer customTabColorizer) {
        mCustomTabColorizer = customTabColorizer;
        invalidate();
    }

    void setSelectedIndicatorColors(int... colors) {
        // Make sure that the custom colorizer is removed
        mCustomTabColorizer = null;
        mDefaultTabColorizer.setIndicatorColors(colors);
        invalidate();
    }

    void onViewPagerPageChanged(int position, float positionOffset) {
        mSelectedPosition = position;
        mSelectionOffset = positionOffset;
        invalidate();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        final int height = getHeight();
        final int childCount = getChildCount();
        final SlidingTabLayout.TabColorizer tabColorizer = mCustomTabColorizer != null
                ? mCustomTabColorizer
                : mDefaultTabColorizer;

        // Thick colored underline below the current selection
        if (childCount > 0) {
            View selectedTitle = getChildAt(mSelectedPosition);
            int left = selectedTitle.getLeft();
            int right = selectedTitle.getRight();
            int color = tabColorizer.getIndicatorColor(mSelectedPosition);

            if (mSelectionOffset > 0f && mSelectedPosition < (getChildCount() - 1)) {
                int nextColor = tabColorizer.getIndicatorColor(mSelectedPosition + 1);
                if (color != nextColor) {
                    color = blendColors(nextColor, color, mSelectionOffset);
                }

                // Draw the selection partway between the tabs
                View nextTitle = getChildAt(mSelectedPosition + 1);
                left = (int) (mSelectionOffset * nextTitle.getLeft() +
                        (1.0f - mSelectionOffset) * left);
                right = (int) (mSelectionOffset * nextTitle.getRight() +
                        (1.0f - mSelectionOffset) * right);
            }

            mSelectedIndicatorPaint.setColor(color);

            canvas.drawRect(left, height - mSelectedIndicatorThickness, right,
                    height, mSelectedIndicatorPaint);
        }

        // Thin underline along the entire bottom edge
        canvas.drawRect(0, height - mBottomBorderThickness, getWidth(), height, mBottomBorderPaint);
    }

    /**
     * Set the alpha value of the {@code color} to be the given {@code alpha} value.
     */
    private static int setColorAlpha(int color, byte alpha) {
        return Color.argb(alpha, Color.red(color), Color.green(color), Color.blue(color));
    }

    /**
     * Blend {@code color1} and {@code color2} using the given ratio.
     *
     * @param ratio of which to blend. 1.0 will return {@code color1}, 0.5 will give an even blend,
     *              0.0 will return {@code color2}.
     */
    private static int blendColors(int color1, int color2, float ratio) {
        final float inverseRation = 1f - ratio;
        float r = (Color.red(color1) * ratio) + (Color.red(color2) * inverseRation);
        float g = (Color.green(color1) * ratio) + (Color.green(color2) * inverseRation);
        float b = (Color.blue(color1) * ratio) + (Color.blue(color2) * inverseRation);
        return Color.rgb((int) r, (int) g, (int) b);
    }

    private static class SimpleTabColorizer implements SlidingTabLayout.TabColorizer {
        private int[] mIndicatorColors;

        @Override
        public final int getIndicatorColor(int position) {
            return mIndicatorColors[position % mIndicatorColors.length];
        }

        void setIndicatorColors(int... colors) {
            mIndicatorColors = colors;
        }
    }
}
</code>```

USE in xml like this

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

    <com.helper.SlidingTabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorPrimary">

    </com.helper.SlidingTabLayout>

    <FrameLayout
        android:id="@+id/content_frame"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">

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

        </android.support.v4.view.ViewPager>

    </FrameLayout>

</LinearLayout>
</code>```

In java class Where you are using this add below code

```<code>ViewPager pager = (ViewPager) rootView.findViewById(R.id.pager);
            pager.setAdapter(YourPagerAdapter);
 SlidingTabLayout tabs = (SlidingTabLayout) rootView.findViewById(R.id.tabs);
            tabs.setDistributeEvenly(true);
            tabs.setSelectedIndicatorColors(android.R.color.white,android.R.color.white,android.R.color.white);
            tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
                @Override
                public int getIndicatorColor(int position) {
                    return getResources().getColor(R.color.tabsScrollColor);
                }
            });

            tabs.setViewPager(pager);
</code>```

Body:
I want tabMode scrollable with tabFilled with tabs(having single line title). As number of Tab and their title is dynamic in my app. How could I handle them
  when I set given property. Title of tabs come's in two lines.when number of tab is greater.

    app:tabGravity="fill"
    app:tabMaxWidth="0dp"
    app:tabMode="fixed"

and when number of tabs are less and tabMode is set to scrollable. then extra space shown like below.

how could I make a Tablayout to work in all phones and with one line text .
Simply remove spaces for second screen and make single line for 1st Image.

I know I have to change it's tabMode and tabGravity for these two cases but How could I know when to change it's tabMode and tabGravity. It may be a case that I have only three tab's but their title are long and they are filling entire space. and some time we have 5 tabs with little title . They easily fit's in screen.

Body:
try this one

public class SlidingTabLayout extends HorizontalScrollView {
    /**
     * Allows complete control over the colors drawn in the tab layout. Set with
     * {@link #setCustomTabColorizer(TabColorizer)}.
     */
    public interface TabColorizer {

        /**
         * @return return the color of the indicator used when {@code position} is selected.
         */
        int getIndicatorColor(int position);

    }

    private static final int TITLE_OFFSET_DIPS = 24;
    private static final int TAB_VIEW_PADDING_DIPS = 16;
    private static final int TAB_VIEW_TEXT_SIZE_SP = 12;

    private int mTitleOffset;

    private int mTabViewLayoutId;
    private int mTabViewTextViewId;
    private boolean mDistributeEvenly;

    private ViewPager mViewPager;
    private SparseArray<String> mContentDescriptions = new SparseArray<String>();
    private ViewPager.OnPageChangeListener mViewPagerPageChangeListener;

    private final SlidingTabStrip mTabStrip;

    public SlidingTabLayout(Context context) {
        this(context, null);
    }

    public SlidingTabLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public SlidingTabLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        // Disable the Scroll Bar
        setHorizontalScrollBarEnabled(false);
        // Make sure that the Tab Strips fills this View
        setFillViewport(true);

        mTitleOffset = (int) (TITLE_OFFSET_DIPS * getResources().getDisplayMetrics().density);

        mTabStrip = new SlidingTabStrip(context);
        addView(mTabStrip, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
    }

    /**
     * Set the custom {@link TabColorizer} to be used.
     *
     * If you only require simple custmisation then you can use
     * {@link #setSelectedIndicatorColors(int...)} to achieve
     * similar effects.
     */
    public void setCustomTabColorizer(TabColorizer tabColorizer) {
        mTabStrip.setCustomTabColorizer(tabColorizer);
    }

    public void setDistributeEvenly(boolean distributeEvenly) {
        mDistributeEvenly = distributeEvenly;
    }

    /**
     * Sets the colors to be used for indicating the selected tab. These colors are treated as a
     * circular array. Providing one color will mean that all tabs are indicated with the same color.
     */
    public void setSelectedIndicatorColors(int... colors) {
        mTabStrip.setSelectedIndicatorColors(colors);
    }

    /**
     * Set the {@link ViewPager.OnPageChangeListener}. When using {@link SlidingTabLayout} you are
     * required to set any {@link ViewPager.OnPageChangeListener} through this method. This is so
     * that the layout can update it's scroll position correctly.
     *
     * @see ViewPager#setOnPageChangeListener(ViewPager.OnPageChangeListener)
     */
    public void setOnPageChangeListener(ViewPager.OnPageChangeListener listener) {
        mViewPagerPageChangeListener = listener;
    }

    /**
     * Set the custom layout to be inflated for the tab views.
     *
     * @param layoutResId Layout id to be inflated
     * @param textViewId id of the {@link TextView} in the inflated view
     */
    public void setCustomTabView(int layoutResId, int textViewId) {
        mTabViewLayoutId = layoutResId;
        mTabViewTextViewId = textViewId;
    }

    /**
     * Sets the associated view pager. Note that the assumption here is that the pager content
     * (number of tabs and tab titles) does not change after this call has been made.
     */
    public void setViewPager(ViewPager viewPager) {
        mTabStrip.removeAllViews();

        mViewPager = viewPager;
        if (viewPager != null) {
            viewPager.setOnPageChangeListener(new InternalViewPagerListener());
            populateTabStrip();
        }
    }

    /**
     * Create a default view to be used for tabs. This is called if a custom tab view is not set via
     * {@link #setCustomTabView(int, int)}.
     */
    @SuppressLint("NewApi") protected TextView createDefaultTabView(Context context) {
        TextView textView = new TextView(context);
        textView.setGravity(Gravity.CENTER);
        textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, TAB_VIEW_TEXT_SIZE_SP);
        textView.setTypeface(Typeface.DEFAULT_BOLD);
        textView.setLayoutParams(new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));

        TypedValue outValue = new TypedValue();
        getContext().getTheme().resolveAttribute(android.R.attr.selectableItemBackground,
                outValue, true);
        textView.setBackgroundResource(outValue.resourceId);
        textView.setAllCaps(true);

        int padding = (int) (TAB_VIEW_PADDING_DIPS * getResources().getDisplayMetrics().density);
        textView.setPadding(padding, padding, padding, padding);

        return textView;
    }

    /*private void populateTabStrip() {
        final PagerAdapter adapter = mViewPager.getAdapter();
        final View.OnClickListener tabClickListener = new TabClickListener();

        for (int i = 0; i < adapter.getCount(); i++) {
            View tabView = null;
            TextView tabTitleView = null;

            if (mTabViewLayoutId != 0) {
                // If there is a custom tab view layout id set, try and inflate it
                tabView = LayoutInflater.from(getContext()).inflate(mTabViewLayoutId, mTabStrip,
                        false);
                tabTitleView = (TextView) tabView.findViewById(mTabViewTextViewId);
            }

            if (tabView == null) {
                tabView = createDefaultTabView(getContext());
            }

            if (tabTitleView == null && TextView.class.isInstance(tabView)) {
                tabTitleView = (TextView) tabView;
            }

            if (mDistributeEvenly) {
                LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) tabView.getLayoutParams();
                lp.width = 0;
                lp.weight = 1;
            }

            tabTitleView.setText(adapter.getPageTitle(i));
            tabView.setOnClickListener(tabClickListener);
            String desc = mContentDescriptions.get(i, null);
            if (desc != null) {
                tabView.setContentDescription(desc);
            }

            mTabStrip.addView(tabView);
            if (i == mViewPager.getCurrentItem()) {
                tabView.setSelected(true);
            }
        }
    }*/

    @SuppressWarnings("deprecation")    private void populateTabStrip() {
        final PagerAdapter adapter = mViewPager.getAdapter();
        final View.OnClickListener tabClickListener = new TabClickListener();

        for (int i = 0; i < adapter.getCount(); i++) {
            View tabView = null;
            TextView tabTitleView = null;

            if (mTabViewLayoutId != 0) {
                // If there is a custom tab view layout id set, try and inflate it
                tabView = LayoutInflater.from(getContext()).inflate(mTabViewLayoutId, mTabStrip, false);
                tabTitleView = (TextView) tabView.findViewById(mTabViewTextViewId);
            }

            if (tabView == null) {
                tabView = createDefaultTabView(getContext());
            }

            if (tabTitleView == null && TextView.class.isInstance(tabView)) {
                tabTitleView = (TextView) tabView;
            }

            if (mDistributeEvenly) {
                LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) tabView.getLayoutParams();
                lp.width = 0;
                lp.weight = 1;
            }

            tabTitleView.setText(adapter.getPageTitle(i));
            tabView.setOnClickListener(tabClickListener);
            String desc = mContentDescriptions.get(i, null);
            if (desc != null) {
                tabView.setContentDescription(desc);
            }

            mTabStrip.addView(tabView);
            if (i == mViewPager.getCurrentItem()) {
                tabView.setSelected(true);
            }
            tabTitleView.setTextColor(getResources().getColorStateList(R.drawable.selector));
            tabTitleView.setTextSize(14);
        }
    }

    public void setContentDescription(int i, String desc) {
        mContentDescriptions.put(i, desc);
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();

        if (mViewPager != null) {
            scrollToTab(mViewPager.getCurrentItem(), 0);
        }
    }

    private void scrollToTab(int tabIndex, int positionOffset) {
        final int tabStripChildCount = mTabStrip.getChildCount();
        if (tabStripChildCount == 0 || tabIndex < 0 || tabIndex >= tabStripChildCount) {
            return;
        }

        View selectedChild = mTabStrip.getChildAt(tabIndex);
        if (selectedChild != null) {
            int targetScrollX = selectedChild.getLeft() + positionOffset;

            if (tabIndex > 0 || positionOffset > 0) {
                // If we're not at the first child and are mid-scroll, make sure we obey the offset
                targetScrollX -= mTitleOffset;
            }

            scrollTo(targetScrollX, 0);
        }
    }

    private class InternalViewPagerListener implements ViewPager.OnPageChangeListener {
        private int mScrollState;

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            int tabStripChildCount = mTabStrip.getChildCount();
            if ((tabStripChildCount == 0) || (position < 0) || (position >= tabStripChildCount)) {
                return;
            }

            mTabStrip.onViewPagerPageChanged(position, positionOffset);

            View selectedTitle = mTabStrip.getChildAt(position);
            int extraOffset = (selectedTitle != null)
                    ? (int) (positionOffset * selectedTitle.getWidth())
                    : 0;
            scrollToTab(position, extraOffset);

            if (mViewPagerPageChangeListener != null) {
                mViewPagerPageChangeListener.onPageScrolled(position, positionOffset,
                        positionOffsetPixels);
            }
        }

        @Override
        public void onPageScrollStateChanged(int state) {
            mScrollState = state;

            if (mViewPagerPageChangeListener != null) {
                mViewPagerPageChangeListener.onPageScrollStateChanged(state);
            }
        }

        @Override
        public void onPageSelected(int position) {
            if (mScrollState == ViewPager.SCROLL_STATE_IDLE) {
                mTabStrip.onViewPagerPageChanged(position, 0f);
                scrollToTab(position, 0);
            }
            for (int i = 0; i < mTabStrip.getChildCount(); i++) {
                mTabStrip.getChildAt(i).setSelected(position == i);
            }
            if (mViewPagerPageChangeListener != null) {
                mViewPagerPageChangeListener.onPageSelected(position);
            }
        }

    }

    private class TabClickListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            for (int i = 0; i < mTabStrip.getChildCount(); i++) {
                if (v == mTabStrip.getChildAt(i)) {
                    mViewPager.setCurrentItem(i);
                    return;
                }
            }
        }
    }

}

SlidingTabStrip.java

class SlidingTabStrip extends LinearLayout {

    private static final int DEFAULT_BOTTOM_BORDER_THICKNESS_DIPS = 0;
    private static final byte DEFAULT_BOTTOM_BORDER_COLOR_ALPHA = 0x26;
    private static final int SELECTED_INDICATOR_THICKNESS_DIPS = 3;
    private static final int DEFAULT_SELECTED_INDICATOR_COLOR = 0xFF33B5E5;

    private final int mBottomBorderThickness;
    private final Paint mBottomBorderPaint;

    private final int mSelectedIndicatorThickness;
    private final Paint mSelectedIndicatorPaint;

    private final int mDefaultBottomBorderColor;

    private int mSelectedPosition;
    private float mSelectionOffset;

    private SlidingTabLayout.TabColorizer mCustomTabColorizer;
    private final SimpleTabColorizer mDefaultTabColorizer;

    SlidingTabStrip(Context context) {
        this(context, null);
    }

    SlidingTabStrip(Context context, AttributeSet attrs) {
        super(context, attrs);
        setWillNotDraw(false);

        final float density = getResources().getDisplayMetrics().density;

        TypedValue outValue = new TypedValue();
        context.getTheme().resolveAttribute(R.attr.colorForeground, outValue, true);
        final int themeForegroundColor =  outValue.data;

        mDefaultBottomBorderColor = setColorAlpha(themeForegroundColor, DEFAULT_BOTTOM_BORDER_COLOR_ALPHA);

        mDefaultTabColorizer = new SimpleTabColorizer();
        mDefaultTabColorizer.setIndicatorColors(DEFAULT_SELECTED_INDICATOR_COLOR);

        mBottomBorderThickness = (int) (DEFAULT_BOTTOM_BORDER_THICKNESS_DIPS * density);
        mBottomBorderPaint = new Paint();
        mBottomBorderPaint.setColor(mDefaultBottomBorderColor);

        mSelectedIndicatorThickness = (int) (SELECTED_INDICATOR_THICKNESS_DIPS * density);
        mSelectedIndicatorPaint = new Paint();
    }

    void setCustomTabColorizer(SlidingTabLayout.TabColorizer customTabColorizer) {
        mCustomTabColorizer = customTabColorizer;
        invalidate();
    }

    void setSelectedIndicatorColors(int... colors) {
        // Make sure that the custom colorizer is removed
        mCustomTabColorizer = null;
        mDefaultTabColorizer.setIndicatorColors(colors);
        invalidate();
    }

    void onViewPagerPageChanged(int position, float positionOffset) {
        mSelectedPosition = position;
        mSelectionOffset = positionOffset;
        invalidate();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        final int height = getHeight();
        final int childCount = getChildCount();
        final SlidingTabLayout.TabColorizer tabColorizer = mCustomTabColorizer != null
                ? mCustomTabColorizer
                : mDefaultTabColorizer;

        // Thick colored underline below the current selection
        if (childCount > 0) {
            View selectedTitle = getChildAt(mSelectedPosition);
            int left = selectedTitle.getLeft();
            int right = selectedTitle.getRight();
            int color = tabColorizer.getIndicatorColor(mSelectedPosition);

            if (mSelectionOffset > 0f && mSelectedPosition < (getChildCount() - 1)) {
                int nextColor = tabColorizer.getIndicatorColor(mSelectedPosition + 1);
                if (color != nextColor) {
                    color = blendColors(nextColor, color, mSelectionOffset);
                }

                // Draw the selection partway between the tabs
                View nextTitle = getChildAt(mSelectedPosition + 1);
                left = (int) (mSelectionOffset * nextTitle.getLeft() +
                        (1.0f - mSelectionOffset) * left);
                right = (int) (mSelectionOffset * nextTitle.getRight() +
                        (1.0f - mSelectionOffset) * right);
            }

            mSelectedIndicatorPaint.setColor(color);

            canvas.drawRect(left, height - mSelectedIndicatorThickness, right,
                    height, mSelectedIndicatorPaint);
        }

        // Thin underline along the entire bottom edge
        canvas.drawRect(0, height - mBottomBorderThickness, getWidth(), height, mBottomBorderPaint);
    }

    /**
     * Set the alpha value of the {@code color} to be the given {@code alpha} value.
     */
    private static int setColorAlpha(int color, byte alpha) {
        return Color.argb(alpha, Color.red(color), Color.green(color), Color.blue(color));
    }

    /**
     * Blend {@code color1} and {@code color2} using the given ratio.
     *
     * @param ratio of which to blend. 1.0 will return {@code color1}, 0.5 will give an even blend,
     *              0.0 will return {@code color2}.
     */
    private static int blendColors(int color1, int color2, float ratio) {
        final float inverseRation = 1f - ratio;
        float r = (Color.red(color1) * ratio) + (Color.red(color2) * inverseRation);
        float g = (Color.green(color1) * ratio) + (Color.green(color2) * inverseRation);
        float b = (Color.blue(color1) * ratio) + (Color.blue(color2) * inverseRation);
        return Color.rgb((int) r, (int) g, (int) b);
    }

    private static class SimpleTabColorizer implements SlidingTabLayout.TabColorizer {
        private int[] mIndicatorColors;

        @Override
        public final int getIndicatorColor(int position) {
            return mIndicatorColors[position % mIndicatorColors.length];
        }

        void setIndicatorColors(int... colors) {
            mIndicatorColors = colors;
        }
    }
}

USE in xml like this

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

    <com.helper.SlidingTabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorPrimary">

    </com.helper.SlidingTabLayout>

    <FrameLayout
        android:id="@+id/content_frame"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">

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

        </android.support.v4.view.ViewPager>

    </FrameLayout>

</LinearLayout>

In java class Where you are using this add below code

ViewPager pager = (ViewPager) rootView.findViewById(R.id.pager);
            pager.setAdapter(YourPagerAdapter);
 SlidingTabLayout tabs = (SlidingTabLayout) rootView.findViewById(R.id.tabs);
            tabs.setDistributeEvenly(true);
            tabs.setSelectedIndicatorColors(android.R.color.white,android.R.color.white,android.R.color.white);
            tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
                @Override
                public int getIndicatorColor(int position) {
                    return getResources().getColor(R.color.tabsScrollColor);
                }
            });

            tabs.setViewPager(pager);


来源: stackexchange

问:
Add property in class dynamically
I have a list of product class, e.g:

```<code>{
   Name = "Product 1",
   Category = "TV",
   Region = "China"
},
{
   Name = "Product 2",
   Category = "Watch",
   Region = "Germany"
},
{
   Name = "Product 3",
   Category = "Smartphone",
   Region = "USA"
}
</code>```

and unsorted product price list for every year (in format product, year and amount), e.g:

```<code>Product 1, 2016, $2000
Product 2, 2016, $300
Product 1, 2017, $1800
Product 3, 2017, $500
Product 2, 2017, $290
</code>```

I need to display the products with price - to show the comparison of price for every year. The end result should look like this:

```<code>Name           Category      Year 2016   Year 2017
Product 1      TV              2000        1800
Product 2      Watch            300         290
Product 3      Smartphone        -          500
</code>```

Since the price list will expand every year, therefore I plan to keep a list of string as properties in class.

```<code>List<string> Headers = new List<string> {
    "Name",
    "Category",
    "Region"
};

foreach (string year in distinctYear)
{
    Headers.Add("Y" + year);
}
</code>```

Until here, I'm stuck, how can I convert them into a class, so that I could assign the value like this:

```<code>{
   Name = "Product 1",
   Category = "TV",
   Y2016 = 2000,
   Y2017 = 1800
},
{
   Name = "Product 2",
   Category = "Watch",
   Region = "Germany",
   Y2016 = 300,
   Y2017 = 290
},
{
   Name = "Product 3",
   Category = "Smartphone",
   Region = "USA",
   Y2017 = 500
}
</code>```

Any help or suggestion is much appreciated.

答:
I combine both ProductList and PriceList classes into a dictionary:

```<code>foreach (var item in ProductList)
{
    var dict = new Dictionary<string, object>();
    dict["Name"] = item.Name;
    dict["Category"] = item.Category;
    dict["Region"] = item.Region;
    foreach (var i in item.PriceList)
    {
        dict[i.Year] = i.Amount;
    }
    list.Add(dict);
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Add property in class dynamically

Body:
I have a list of product class, e.g:

{
   Name = "Product 1",
   Category = "TV",
   Region = "China"
},
{
   Name = "Product 2",
   Category = "Watch",
   Region = "Germany"
},
{
   Name = "Product 3",
   Category = "Smartphone",
   Region = "USA"
}

and unsorted product price list for every year (in format product, year and amount), e.g:

Product 1, 2016, $2000
Product 2, 2016, $300
Product 1, 2017, $1800
Product 3, 2017, $500
Product 2, 2017, $290

I need to display the products with price - to show the comparison of price for every year. The end result should look like this:

Name           Category      Year 2016   Year 2017
Product 1      TV              2000        1800
Product 2      Watch            300         290
Product 3      Smartphone        -          500

Since the price list will expand every year, therefore I plan to keep a list of string as properties in class.

List<string> Headers = new List<string> {
    "Name",
    "Category",
    "Region"
};

foreach (string year in distinctYear)
{
    Headers.Add("Y" + year);
}

Until here, I'm stuck, how can I convert them into a class, so that I could assign the value like this:

{
   Name = "Product 1",
   Category = "TV",
   Y2016 = 2000,
   Y2017 = 1800
},
{
   Name = "Product 2",
   Category = "Watch",
   Region = "Germany",
   Y2016 = 300,
   Y2017 = 290
},
{
   Name = "Product 3",
   Category = "Smartphone",
   Region = "USA",
   Y2017 = 500
}

Any help or suggestion is much appreciated.

Body:
I combine both ProductList and PriceList classes into a dictionary:

foreach (var item in ProductList)
{
    var dict = new Dictionary<string, object>();
    dict["Name"] = item.Name;
    dict["Category"] = item.Category;
    dict["Region"] = item.Region;
    foreach (var i in item.PriceList)
    {
        dict[i.Year] = i.Amount;
    }
    list.Add(dict);
}

ContentLicense: CC BY-SA 4.0


问:
RDD subtract dosen't work for user defined types
I tried this simple example

```<code> scala> rdd2.collect
    res45: Array[Person] = Array(Person(Mary,28,New York), Person(Bill,17,Philadelphia), Person(Craig,34,Philadelphia), Person(Leah,26,Rochester))

    scala> rdd3.collect
    res44: Array[Person] = Array(Person(Mary,28,New York), Person(Bill,17,Philadelphia), Person(Craig,35,Philadelphia), Person(Leah,26,Rochester))

    scala> rdd2.subtract(rdd3).collect
    res46: Array[Person] = Array(Person(Mary,28,New York), Person(Leah,26,Rochester), Person(Bill,17,Philadelphia), Person(Craig,34,Philadelphia))
</code>```

I expect rdd2.subtract(rdd3).collect only should be Person(Craig,34,Philadelphia) but I get rdd2 as my output Can anyone please explain this ?

答:
This is one of the known issues with scala REPL where equality conditions dont work properly in REPL. try the following to fix it. This issue occurs only in the REPL and would go away when you are running he application via spark-submit.
This issue is explained in detail in this ticket.</p>

```<code>scala> :paste -raw  // make sure you are using Scala 2.11 for the raw option to work.
// Entering paste mode (ctrl-D to finish)

package mytest;
case class Person(name: String, age: Int, city: String);

// Exiting paste mode, now interpreting.

scala> import mytest.Person

scala> val rdd2 = sc.parallelize(Seq(Person("Mary",28,"New York"), Person("Bill",17,"Philadelphia"), Person("Craig",34,"Philadelphia"), Person("Leah",26,"Rochester")))
rdd2: org.apache.spark.rdd.RDD[mytest.Person] = ParallelCollectionRDD[6] at parallelize at <console>:25

scala> val rdd3 = sc.parallelize(Seq(Person("Mary",28,"New York"), Person("Bill",17,"Philadelphia"), Person("Craig",35,"Philadelphia"), Person("Leah",26,"Rochester")))
rdd3: org.apache.spark.rdd.RDD[mytest.Person] = ParallelCollectionRDD[7] at parallelize at <console>:25

scala> rdd2.subtract(rdd3).collect
res1: Array[mytest.Person] = Array(Person(Craig,34,Philadelphia))
</code>```

Body:
I tried this simple example

 scala> rdd2.collect
    res45: Array[Person] = Array(Person(Mary,28,New York), Person(Bill,17,Philadelphia), Person(Craig,34,Philadelphia), Person(Leah,26,Rochester))

    scala> rdd3.collect
    res44: Array[Person] = Array(Person(Mary,28,New York), Person(Bill,17,Philadelphia), Person(Craig,35,Philadelphia), Person(Leah,26,Rochester))

    scala> rdd2.subtract(rdd3).collect
    res46: Array[Person] = Array(Person(Mary,28,New York), Person(Leah,26,Rochester), Person(Bill,17,Philadelphia), Person(Craig,34,Philadelphia))

I expect rdd2.subtract(rdd3).collect only should be Person(Craig,34,Philadelphia) but I get rdd2 as my output Can anyone please explain this ?

Body:
This is one of the known issues with scala REPL where equality conditions dont work properly in REPL. try the following to fix it. This issue occurs only in the REPL and would go away when you are running he application via spark-submit.
This issue is explained in detail in this ticket.

scala> :paste -raw  // make sure you are using Scala 2.11 for the raw option to work.
// Entering paste mode (ctrl-D to finish)

package mytest;
case class Person(name: String, age: Int, city: String);

// Exiting paste mode, now interpreting.

scala> import mytest.Person

scala> val rdd2 = sc.parallelize(Seq(Person("Mary",28,"New York"), Person("Bill",17,"Philadelphia"), Person("Craig",34,"Philadelphia"), Person("Leah",26,"Rochester")))
rdd2: org.apache.spark.rdd.RDD[mytest.Person] = ParallelCollectionRDD[6] at parallelize at <console>:25

scala> val rdd3 = sc.parallelize(Seq(Person("Mary",28,"New York"), Person("Bill",17,"Philadelphia"), Person("Craig",35,"Philadelphia"), Person("Leah",26,"Rochester")))
rdd3: org.apache.spark.rdd.RDD[mytest.Person] = ParallelCollectionRDD[7] at parallelize at <console>:25

scala> rdd2.subtract(rdd3).collect
res1: Array[mytest.Person] = Array(Person(Craig,34,Philadelphia))


问:
Why compiler don't prevent us, when we try to add duplicate object in Hashset?
As I know HashSet not do not take duplicate object, When I try below code it simply add first one and ignore second one.Why there is no checked Exception for this. How add() is implemented for HashSet?

```<code>public static void main (String[] args) throws java.lang.Exception
{
    HashSet Hs = new HashSet();
    Hs.add("A");
    Hs.add("A");
    System.out.println(Hs);
}
</code>```

OUTPUT- [A]

答:
what happens internally when you pass duplicate elements in the
  add() method of the Set object , It will return false and do not add
  to the HashSet , as the element is already present .So far so good .
  But the main problem arises that how it returns false . So here is the
  answer When you open the HashSet implementation of the add() method in
  Java Apis that is rt.jar , you will find the following code in it.

```<code>public class HashSet<E>
extends AbstractSet<E>
implements Set<E>, Cloneable, java.io.Serializable
{
    private transient HashMap<E,Object> map;
    // Dummy value to associate with an Object in the backing Map
    private static final Object PRESENT = new Object();
    public HashSet() {
        map = new HashMap<>();
    }
    // SOME CODE ,i.e Other methods in Hash Set
    public boolean add(E e) {
        return map.put(e, PRESENT)==null;
    }
    // SOME CODE ,i.e Other methods in Hash Set
}
</code>```

So , we are achieving uniqueness in Set,internally in java  through HashMap . Whenever you create an object of HashSet it will create an object of HashMap as you can see in the italic lines in the above code .

Body:
As I know HashSet not do not take duplicate object, When I try below code it simply add first one and ignore second one.Why there is no checked Exception for this. How add() is implemented for HashSet?

public static void main (String[] args) throws java.lang.Exception
{
    HashSet Hs = new HashSet();
    Hs.add("A");
    Hs.add("A");
    System.out.println(Hs);
}

OUTPUT- [A]

Body:
what happens internally when you pass duplicate elements in the
  add() method of the Set object , It will return false and do not add
  to the HashSet , as the element is already present .So far so good .
  But the main problem arises that how it returns false . So here is the
  answer When you open the HashSet implementation of the add() method in
  Java Apis that is rt.jar , you will find the following code in it.

public class HashSet<E>
extends AbstractSet<E>
implements Set<E>, Cloneable, java.io.Serializable
{
    private transient HashMap<E,Object> map;
    // Dummy value to associate with an Object in the backing Map
    private static final Object PRESENT = new Object();
    public HashSet() {
        map = new HashMap<>();
    }
    // SOME CODE ,i.e Other methods in Hash Set
    public boolean add(E e) {
        return map.put(e, PRESENT)==null;
    }
    // SOME CODE ,i.e Other methods in Hash Set
}

So , we are achieving uniqueness in Set,internally in java  through HashMap . Whenever you create an object of HashSet it will create an object of HashMap as you can see in the italic lines in the above code .


问:
GCC optimization issues and behavior
I have an optimisation issue with gcc running on Eclipse.
I have a program which runs well with -O0 optimization level, but I need to turn ON other levels of optimization because my software uses too much flash memory space.
But when I use -O1 optimization level (for instance) my code doesn't work anymore and I need to do strange modifications as described below with the UART peripheral managing functions.

Code running well with -O0

```<code>void function(...)
{
   // Send char one by one on UART peripheral
   UART_put_char(...)

   // Wait end of transmission on UART
   while(end_of_transmission_flag == flase);
}

void UART_TxCompleteCallback()
{
   // Change flag state
   end_of_transmission_flag = true;
}
</code>```

Code with modification for -O1

```<code>void function(...)
{
   // Send char one by one on UART peripheral
   UART_put_char(...)

   // Wait end of transmission on UART
   while(end_of_transmission_flag == flase)
   {
      Dummy = Dummy == 0 ? 1 : 0;
   }
}

void UART_TxCompleteCallback()
{
   // Change flag state
   end_of_transmission_flag = true;
}
</code>```

I would like to know why gcc is forcing me to do this kind of modifications, do I need to change my "way of think" about the design of my code. Or is there an explanation with this behavior ?

Thanks for your advices.

答:
As said in the comments, you should declare end_of_transmission_flag as volatile to make sure the compiler does not remove the loop during its optimization. By declaring the variable volatile, the compiler knows the variable will be updated somewhere else.

But to debug your issue you should not change all the files with '-O1' in once, but you should try to move some file in -O1 and keep some file in -O0.

You can also disable GCC optimization locally:

```<code>#pragma GCC push_options
#pragma GCC optimize ("O0")

// your code

#pragma GCC pop_options
</code>```

Be aware in embedded you must respect the order of the operation when you access hardware register. Compilation optimization sometimes/often change the order. Using volatile with the address of the registers ensures the order of the operation.

Title: GCC optimization issues and behavior

Body:
I have an optimisation issue with gcc running on Eclipse.
I have a program which runs well with -O0 optimization level, but I need to turn ON other levels of optimization because my software uses too much flash memory space.
But when I use -O1 optimization level (for instance) my code doesn't work anymore and I need to do strange modifications as described below with the UART peripheral managing functions.

Code running well with -O0

void function(...)
{
   // Send char one by one on UART peripheral
   UART_put_char(...)

   // Wait end of transmission on UART
   while(end_of_transmission_flag == flase);
}

void UART_TxCompleteCallback()
{
   // Change flag state
   end_of_transmission_flag = true;
}

Code with modification for -O1

void function(...)
{
   // Send char one by one on UART peripheral
   UART_put_char(...)

   // Wait end of transmission on UART
   while(end_of_transmission_flag == flase)
   {
      Dummy = Dummy == 0 ? 1 : 0;
   }
}

void UART_TxCompleteCallback()
{
   // Change flag state
   end_of_transmission_flag = true;
}

I would like to know why gcc is forcing me to do this kind of modifications, do I need to change my "way of think" about the design of my code. Or is there an explanation with this behavior ?

Thanks for your advices.

Body:
As said in the comments, you should declare end_of_transmission_flag as volatile to make sure the compiler does not remove the loop during its optimization. By declaring the variable volatile, the compiler knows the variable will be updated somewhere else.

But to debug your issue you should not change all the files with '-O1' in once, but you should try to move some file in -O1 and keep some file in -O0.

You can also disable GCC optimization locally:

#pragma GCC push_options
#pragma GCC optimize ("O0")

// your code

#pragma GCC pop_options

Be aware in embedded you must respect the order of the operation when you access hardware register. Compilation optimization sometimes/often change the order. Using volatile with the address of the registers ensures the order of the operation.


问:
Why doesn’t git show that I’m ahead of origin?
Ubuntu 16.04

I know that I have organized a remote repository.

I can execute:

```<code>git add .
git commit -am "Savepoint"
</code>```

Then I can check:

```<code>michael@Thinkpad:~/PycharmProjects/photoarchive_2$ git status
On branch master
nothing to commit, working directory clean
</code>```

But I know that I'm ahead of origin.

I execute:

```<code>git push origin master
</code>```

And now I can see my commit at the remote repository.

I expect git to show me the information like:

```<code>Your branch is ahead of 'origin/master' by 3 commits.
</code>```

Could you tell me there is no such information shown?

ADDED LATER:

```<code>git show-branch -a
* [master] Started working with Image
 ! [origin/master] Started working with Image
--
*+ [master] Started working with Image
</code>```

答:
Maybe you need to track the remote branch?

```<code>$ git branch --set-upstream-to=origin/master master
</code>```

See this related question for details about --set-upstream. In short, it tells git what remote branch you push the local one to.

Body:
Ubuntu 16.04

I know that I have organized a remote repository.

I can execute:

git add .
git commit -am "Savepoint"

Then I can check:

michael@Thinkpad:~/PycharmProjects/photoarchive_2$ git status
On branch master
nothing to commit, working directory clean

But I know that I'm ahead of origin.

I execute:

git push origin master

And now I can see my commit at the remote repository.

I expect git to show me the information like:

Your branch is ahead of 'origin/master' by 3 commits.

Could you tell me there is no such information shown?

ADDED LATER:

git show-branch -a
* [master] Started working with Image
 ! [origin/master] Started working with Image
--
*+ [master] Started working with Image

Body:
Maybe you need to track the remote branch?

$ git branch --set-upstream-to=origin/master master

See this related question for details about --set-upstream. In short, it tells git what remote branch you push the local one to.


问:
Image Pixel Intensity and Measure of Colourfulness in Python
I want to measure the average pixel intensity and measure of colourfulness of a image. For this i'm following this approach (kindly let me know if there's any alternative approach for the same):

a) Calculate Average Pixel Intensity:

```<code>im = Image.open('images-16.jpeg')
stat = ImageStat.Stat(im)
r,g,b = stat.mean
mean = sqrt(0.241* (r ** 2) + 0.691* (g ** 2) + 0.068* (b ** 2))
print(mean)
</code>```

b) To measure colourfulness:

Dividing color space into 64 cubic blocks with four equal partitions along each dimension

```<code>w,h=im.size
bw,bh = 8, 8 #block size
img = np.array(im)
sz = img.itemsize
shape = (h-bh+1, w-bw+1, bh, bw)
strides = (w*sz, sz, w*sz, sz)
blocks = np.lib.stride_tricks.as_strided(img, shape=shape, strides=strides)
print (blocks[1,1])
</code>```

Calculate Euclidean distances between the geometric centers Ci of each cube i
Not able to compute (say d(a,b)=rgb(Ca)-rgb(Cb))

Distribution D1 is generated as the color distribution of a hypothetical image such that for each of 64 sample points, the frequency is 1/64 -

pixels = im.load()
all_pixels = []
for x in range(218): #put your block width size
for y in range(218): #your block heigh size
    cpixel = pixels[x, y]
    all_pixels.append(cpixel)

Distribution D2 is computed from the given image by finding the frequency of occurrence of color within each of the 64 cubes How can i do this?

Calculate Earth Mover's Distance: (D1,D2,d(a,b)) - d(a,b) is calculated above

Is this the right way to do it? Any supporting documents to achieve this? Any help with the code is appreciated. Thanks.

答:
You will need pyemd library.</p>

```<code>from pyemd import emd
import numpy as np
from PIL import Image
import skimage.color

im = Image.open("t4.jpg")
pix = im.load()

h1 = [1.0/64] * 64
h2 = [0.0] * 64
hist1 = np.array(h1)

w,h = im.size

for x in xrange(w):
    for y in xrange(h):
        cbin = pix[x,y][0]/64*16 + pix[x,y][1]/64*4 + pix[x,y][2]/64
        h2[cbin]+=1
hist2 = np.array(h2)/w/h

# compute center of cubes

c = np.zeros((64,3))
for i in xrange(64):
    b = (i%4) * 64 + 32
    g = (i%16/4) * 64 + 32
    r = (i/16) * 64 + 32
    c[i]=(r,g,b)

c_luv = skimage.color.rgb2luv(c.reshape(8,8,3)).reshape(64,3)

d = np.zeros((64,64))

for x in xrange(64):
    d[x,x]=0
    for y in xrange(x):
        dist = np.sqrt( np.square(c_luv[x,0]-c_luv[y,0]) +
                   np.square(c_luv[x,1]-c_luv[y,1]) +
                   np.square(c_luv[x,2]-c_luv[y,2]))
        d[x,y] = dist
        d[y,x] = dist

colorfullness = emd(hist1, hist2, d)

print colorfullness
</code>```

Body:
I want to measure the average pixel intensity and measure of colourfulness of a image. For this i'm following this approach (kindly let me know if there's any alternative approach for the same):

a) Calculate Average Pixel Intensity:

im = Image.open('images-16.jpeg')
stat = ImageStat.Stat(im)
r,g,b = stat.mean
mean = sqrt(0.241* (r ** 2) + 0.691* (g ** 2) + 0.068* (b ** 2))
print(mean)

b) To measure colourfulness:

Dividing color space into 64 cubic blocks with four equal partitions along each dimension

w,h=im.size
bw,bh = 8, 8 #block size
img = np.array(im)
sz = img.itemsize
shape = (h-bh+1, w-bw+1, bh, bw)
strides = (w*sz, sz, w*sz, sz)
blocks = np.lib.stride_tricks.as_strided(img, shape=shape, strides=strides)
print (blocks[1,1])

Calculate Euclidean distances between the geometric centers Ci of each cube i
Not able to compute (say d(a,b)=rgb(Ca)-rgb(Cb))

Distribution D1 is generated as the color distribution of a hypothetical image such that for each of 64 sample points, the frequency is 1/64 -

pixels = im.load()
all_pixels = []
for x in range(218): #put your block width size
for y in range(218): #your block heigh size
    cpixel = pixels[x, y]
    all_pixels.append(cpixel)

Distribution D2 is computed from the given image by finding the frequency of occurrence of color within each of the 64 cubes How can i do this?

Calculate Earth Mover's Distance: (D1,D2,d(a,b)) - d(a,b) is calculated above

Is this the right way to do it? Any supporting documents to achieve this? Any help with the code is appreciated. Thanks.

Body:
You will need pyemd library.

from pyemd import emd
import numpy as np
from PIL import Image
import skimage.color

im = Image.open("t4.jpg")
pix = im.load()

h1 = [1.0/64] * 64
h2 = [0.0] * 64
hist1 = np.array(h1)

w,h = im.size

for x in xrange(w):
    for y in xrange(h):
        cbin = pix[x,y][0]/64*16 + pix[x,y][1]/64*4 + pix[x,y][2]/64
        h2[cbin]+=1
hist2 = np.array(h2)/w/h

# compute center of cubes

c = np.zeros((64,3))
for i in xrange(64):
    b = (i%4) * 64 + 32
    g = (i%16/4) * 64 + 32
    r = (i/16) * 64 + 32
    c[i]=(r,g,b)

c_luv = skimage.color.rgb2luv(c.reshape(8,8,3)).reshape(64,3)

d = np.zeros((64,64))

for x in xrange(64):
    d[x,x]=0
    for y in xrange(x):
        dist = np.sqrt( np.square(c_luv[x,0]-c_luv[y,0]) +
                   np.square(c_luv[x,1]-c_luv[y,1]) +
                   np.square(c_luv[x,2]-c_luv[y,2]))
        d[x,y] = dist
        d[y,x] = dist

colorfullness = emd(hist1, hist2, d)

print colorfullness


问:
Div with text wont stay centered
I'm creating a simple image gallery. Above the images I name the place where the pictures were taken, but the second and every another row has issues - div with the name is being pushed to the right instead of staying centered. Here is how it looks: http://prntscr.com/fg10u4

@import url(https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css);
.locationName {
  text-align: center;
  padding: 0px 0px 20px 20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row" id="locations">

  <div class="locationName">
    City
  </div>

  <div class="col-lg-4 col-sm-6">
    <div class="thumbnail">
      <img src="2.jpg">
    </div>
  </div>

  <div class="col-lg-4 col-sm-6">
    <div class="thumbnail">
      <img src="1.jpg">
    </div>
  </div>

  <div class="col-lg-4 col-sm-6">
    <div class="thumbnail">
      <img src="2.jpg">
    </div>
  </div>
</div></code>```

Obviously the code is doubled inside the "row" div.

答:
i saw your issue. actually there is a conflict with the boxes height. to quickly fix this you can increase your thumbs height equal. or you can see the example  code below.</p>

```<code>    <div class="row" id="locations">
  <div class="col-lg-12 col-sm-12 locationName">City</div>
  <div class="col-lg-4 col-sm-6">
    <div class="thumbnail"> <img src="2.jpg"> </div>
  </div>
  <div class="col-lg-4 col-sm-6">
    <div class="thumbnail"> <img src="1.jpg"> </div>
  </div>
  <div class="col-lg-4 col-sm-6">
    <div class="thumbnail"> <img src="2.jpg"> </div>
  </div>
  <div class="col-lg-12 col-sm-12 locationName"> City </div>
  <div class="col-lg-4 col-sm-6">
    <div class="thumbnail"> <img src="2.jpg"> </div>
  </div>
  <div class="col-lg-4 col-sm-6">
    <div class="thumbnail"> <img src="1.jpg"> </div>
  </div>
  <div class="col-lg-4 col-sm-6">
    <div class="thumbnail"> <img src="2.jpg"> </div>
  </div>
</div>
</code>```

Title: Div with text wont stay centered

Body:
I'm creating a simple image gallery. Above the images I name the place where the pictures were taken, but the second and every another row has issues - div with the name is being pushed to the right instead of staying centered. Here is how it looks: http://prntscr.com/fg10u4

@import url(https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css);
.locationName {
  text-align: center;
  padding: 0px 0px 20px 20px;
}

    City

Obviously the code is doubled inside the "row" div.

Body:
i saw your issue. actually there is a conflict with the boxes height. to quickly fix this you can increase your thumbs height equal. or you can see the example  code below.

    <div class="row" id="locations">
  <div class="col-lg-12 col-sm-12 locationName">City</div>
  <div class="col-lg-4 col-sm-6">
    <div class="thumbnail"> <img src="2.jpg"> </div>
  </div>
  <div class="col-lg-4 col-sm-6">
    <div class="thumbnail"> <img src="1.jpg"> </div>
  </div>
  <div class="col-lg-4 col-sm-6">
    <div class="thumbnail"> <img src="2.jpg"> </div>
  </div>
  <div class="col-lg-12 col-sm-12 locationName"> City </div>
  <div class="col-lg-4 col-sm-6">
    <div class="thumbnail"> <img src="2.jpg"> </div>
  </div>
  <div class="col-lg-4 col-sm-6">
    <div class="thumbnail"> <img src="1.jpg"> </div>
  </div>
  <div class="col-lg-4 col-sm-6">
    <div class="thumbnail"> <img src="2.jpg"> </div>
  </div>
</div>


问:
Failed building wheel for spacy
I'm trying to install spacy by running pip install spacy for python version 3.6.1 but continuously i'm getting errors like below,how to get rid of this issue? previously i was having cl.exe not found error, after that i added visual studio path in environment variables where cl.exe exists.

```<code>     Failed building wheel for spacy
  Running setup.py clean for spacy
  Running setup.py bdist_wheel for murmurhash ... error
  Complete output from command c:\users\sh00428701\appdata\local\programs\python\python36\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\SH0042~1\\AppData\\Local\\Temp\\pip-build-joi6voav\\murmurhash\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d C:\Users\SH0042~1\AppData\Local\Temp\tmpa6tzdkovpip-wheel- --python-tag cp36:
  running bdist_wheel
  running build
  running build_py
----------------------------------------
  Failed building wheel for murmurhash
  Running setup.py clean for murmurhash
  Running setup.py bdist_wheel for cymem ... error
  Complete output from command c:\users\sh00428701\appdata\local\programs\python\python36\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\SH0042~1\\AppData\\Local\\Temp\\pip-build-joi6voav\\cymem\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d C:\Users\SH0042~1\AppData\Local\Temp\tmpz7p6hkiwpip-wheel- --python-tag cp36:

 ----------------------------------------
  Failed building wheel for cymem
  Running setup.py clean for cymem
  Running setup.py bdist_wheel for preshed ... error
  Complete output from command c:\users\sh00428701\appdata\local\programs\python\python36\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\SH0042~1\\AppData\\Local\\Temp\\pip-build-joi6voav\\preshed\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d C:\Users\SH0042~1\AppData\Local\Temp\tmpwppgmyp9pip-wheel- --python-tag cp36:

  ----------------------------------------
  Failed building wheel for preshed
  Running setup.py clean for preshed
  Running setup.py bdist_wheel for thinc ... error
 ----------------------------------------
  Failed building wheel for thinc
  Running setup.py clean for thinc
  Running setup.py bdist_wheel for ujson ... error
  ----------------------------------------
  Failed building wheel for ujson
  Running setup.py clean for ujson
  Running setup.py bdist_wheel for cytoolz ... error
  ----------------------------------------
  Failed building wheel for cytoolz
  Running setup.py clean for cytoolz
Failed to build spacy murmurhash cymem preshed thinc ujson cytoolz
Installing collected packages: murmurhash, cymem, preshed, wrapt, tqdm, toolz, cytoolz, plac, pyreadline, dill, termcolor, pathlib, thinc, ujson, regex, spacy
  Running setup.py install for murmurhash ... error

   C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\bin\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -Ic:\users\sh00428701\appdata\local\programs\python\python36\include -IC:\Users\SH0042~1\AppData\Local\Temp\pip-build-joi6voav\murmurhash\murmurhash\include -Ic:\users\sh00428701\appdata\local\programs\python\python36\include -Ic:\users\sh00428701\appdata\local\programs\python\python36\include /EHsc /Tpmurmurhash/mrmr.cpp /Fobuild\temp.win-amd64-3.6\Release\murmurhash/mrmr.obj /Ox /EHsc
    mrmr.cpp
    c1xx: fatal error C1083: Cannot open source file: 'murmurhash/mrmr.cpp': No such file or directory
    error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\bin\\cl.exe' failed with exit status 2

    ----------------------------------------
Command "c:\users\sh00428701\appdata\local\programs\python\python36\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\SH0042~1\\AppData\\Local\\Temp\\pip-build-joi6voav\\murmurhash\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Users\SH0042~1\AppData\Local\Temp\pip-_j1cxej1-record\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in C:\Users\SH0042~1\AppData\Local\Temp\pip-build-joi6voav\murmurhash\
</code>```

答:
I installed these packages, then it works: </p>

```<code>sudo apt-get install python-dev
sudo apt-get install python3-dev
sudo apt-get install libevent-dev
</code>```

Title: Failed building wheel for spacy

Body:
I'm trying to install spacy by running pip install spacy for python version 3.6.1 but continuously i'm getting errors like below,how to get rid of this issue? previously i was having cl.exe not found error, after that i added visual studio path in environment variables where cl.exe exists.

     Failed building wheel for spacy
  Running setup.py clean for spacy
  Running setup.py bdist_wheel for murmurhash ... error
  Complete output from command c:\users\sh00428701\appdata\local\programs\python\python36\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\SH0042~1\\AppData\\Local\\Temp\\pip-build-joi6voav\\murmurhash\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d C:\Users\SH0042~1\AppData\Local\Temp\tmpa6tzdkovpip-wheel- --python-tag cp36:
  running bdist_wheel
  running build
  running build_py
----------------------------------------
  Failed building wheel for murmurhash
  Running setup.py clean for murmurhash
  Running setup.py bdist_wheel for cymem ... error
  Complete output from command c:\users\sh00428701\appdata\local\programs\python\python36\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\SH0042~1\\AppData\\Local\\Temp\\pip-build-joi6voav\\cymem\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d C:\Users\SH0042~1\AppData\Local\Temp\tmpz7p6hkiwpip-wheel- --python-tag cp36:

 ----------------------------------------
  Failed building wheel for cymem
  Running setup.py clean for cymem
  Running setup.py bdist_wheel for preshed ... error
  Complete output from command c:\users\sh00428701\appdata\local\programs\python\python36\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\SH0042~1\\AppData\\Local\\Temp\\pip-build-joi6voav\\preshed\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d C:\Users\SH0042~1\AppData\Local\Temp\tmpwppgmyp9pip-wheel- --python-tag cp36:

  ----------------------------------------
  Failed building wheel for preshed
  Running setup.py clean for preshed
  Running setup.py bdist_wheel for thinc ... error
 ----------------------------------------
  Failed building wheel for thinc
  Running setup.py clean for thinc
  Running setup.py bdist_wheel for ujson ... error
  ----------------------------------------
  Failed building wheel for ujson
  Running setup.py clean for ujson
  Running setup.py bdist_wheel for cytoolz ... error
  ----------------------------------------
  Failed building wheel for cytoolz
  Running setup.py clean for cytoolz
Failed to build spacy murmurhash cymem preshed thinc ujson cytoolz
Installing collected packages: murmurhash, cymem, preshed, wrapt, tqdm, toolz, cytoolz, plac, pyreadline, dill, termcolor, pathlib, thinc, ujson, regex, spacy
  Running setup.py install for murmurhash ... error

   C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\bin\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -Ic:\users\sh00428701\appdata\local\programs\python\python36\include -IC:\Users\SH0042~1\AppData\Local\Temp\pip-build-joi6voav\murmurhash\murmurhash\include -Ic:\users\sh00428701\appdata\local\programs\python\python36\include -Ic:\users\sh00428701\appdata\local\programs\python\python36\include /EHsc /Tpmurmurhash/mrmr.cpp /Fobuild\temp.win-amd64-3.6\Release\murmurhash/mrmr.obj /Ox /EHsc
    mrmr.cpp
    c1xx: fatal error C1083: Cannot open source file: 'murmurhash/mrmr.cpp': No such file or directory
    error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\bin\\cl.exe' failed with exit status 2

    ----------------------------------------
Command "c:\users\sh00428701\appdata\local\programs\python\python36\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\SH0042~1\\AppData\\Local\\Temp\\pip-build-joi6voav\\murmurhash\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Users\SH0042~1\AppData\Local\Temp\pip-_j1cxej1-record\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in C:\Users\SH0042~1\AppData\Local\Temp\pip-build-joi6voav\murmurhash\

Body:
I installed these packages, then it works:

sudo apt-get install python-dev
sudo apt-get install python3-dev
sudo apt-get install libevent-dev


问:
php array how get in array value for using foreach
I have multiple array, I want particular value get using foreach below my code

Notice: Undefined index: transId in  on line 52

```<code>$test = array(
    'messages' => Array
    (
        'resultCode' => 'Ok',
        'message' => Array
        (
            'code' => 'I00001',
            'text' => 'Successful',
        ),

    ),
    'transactionResponse' => Array
    (
        'responseCode' => '1',
        'authCode' => 'Z7K31J',
        'avsResultCode' => 'Y',
        'cvvResultCode' => 'P',
        'cavvResultCode' => '2',
        'transId' => '40004672975',
        'refTransID' => Array
        (
        ),

        'transHash' => '163382584395AB06470CF365AD6F7381',
        'testRequest' => '0',
        'accountNumber' => 'XXXX4242',
        'accountType' => 'Visa',
        'messages' => Array
        (
            'message' => Array
                (
                    'code' => '1',
                    'description' => 'This transaction has been approved',
                ),

        ),
        'transHashSha2' => Array
        (
        ),
    ),
);
</code>```

above my array, execute $test in foreach

I want display value of transid, response, transhash

```<code>foreach ($test as $key => $value) {
    $response = $value['resultCode'];
    $transId = $value['transId'];
    $authCode = $value['authCode'];
    $transHash = $value['transHash'];
}
</code>```

答:
You dont need foreach:</p>

```<code>$response = $test['messages']['resultCode'];
$transId = $test['transactionResponse']['transId'];
$authCode = $test['transactionResponse']['authCode'];
$transHash = $test['transactionResponse']['transHash'];
</code>```

Body:
I have multiple array, I want particular value get using foreach below my code

Notice: Undefined index: transId in  on line 52

$test = array(
    'messages' => Array
    (
        'resultCode' => 'Ok',
        'message' => Array
        (
            'code' => 'I00001',
            'text' => 'Successful',
        ),

    ),
    'transactionResponse' => Array
    (
        'responseCode' => '1',
        'authCode' => 'Z7K31J',
        'avsResultCode' => 'Y',
        'cvvResultCode' => 'P',
        'cavvResultCode' => '2',
        'transId' => '40004672975',
        'refTransID' => Array
        (
        ),

        'transHash' => '163382584395AB06470CF365AD6F7381',
        'testRequest' => '0',
        'accountNumber' => 'XXXX4242',
        'accountType' => 'Visa',
        'messages' => Array
        (
            'message' => Array
                (
                    'code' => '1',
                    'description' => 'This transaction has been approved',
                ),

        ),
        'transHashSha2' => Array
        (
        ),
    ),
);

above my array, execute $test in foreach

I want display value of transid, response, transhash

foreach ($test as $key => $value) {
    $response = $value['resultCode'];
    $transId = $value['transId'];
    $authCode = $value['authCode'];
    $transHash = $value['transHash'];
}

Body:
You dont need foreach:

$response = $test['messages']['resultCode'];
$transId = $test['transactionResponse']['transId'];
$authCode = $test['transactionResponse']['authCode'];
$transHash = $test['transactionResponse']['transHash'];


问:
when i try to register by my app i didn't get any respnse
I am trying to save my data to server. can any one help me?

when i am trying to save data through browser it is working fine but when i try it through this code doesn'n give any response??

```<code>public class Register extends AppCompatActivity implements View.OnClickListener {

private static final String TAG = "dRegister";
EditText etName, etEmail, etMobile, etPassword, /*etRePassword*/
        etCity;
Button register;

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

    etName = (EditText) findViewById(R.id.name);
    etEmail = (EditText) findViewById(R.id.email);
    etMobile = (EditText) findViewById(R.id.mobile);
    etCity = (EditText) findViewById(R.id.etCity);
    etPassword = (EditText) findViewById(R.id.password);
    //etRePassword = (EditText) findViewById(R.id.rePassword);
    register = (Button) findViewById(R.id.bRegister);
    register.setOnClickListener(this);

}

@Override
public void onClick(View v) {
    final String name = etName.getText().toString();
    final String email = etEmail.getText().toString();
    final String password = etPassword.getText().toString();
    final String city = etCity.getText().toString();
    final String phoneno = etMobile.getText().toString();

    StringRequest registerRequest = new StringRequest(Request.Method.POST,RegisterRequest.REGISTER_REQUEST_URL, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            Log.d(TAG, response + " Response");
            if(response.equals("SUCCESS")){
                startActivity(new Intent(Register.this,MainActivity.class));
            }
            else{
                Toast.makeText(Register.this, "You have not Registered!", Toast.LENGTH_SHORT).show();
            }

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.d(TAG, "Error " + error.toString());
            if(error.networkResponse == null){
                if(error.getClass().equals(TimeoutError.class));
                Toast.makeText(Register.this, "oops Time out error!", Toast.LENGTH_SHORT).show();
            }
        }
    }){
        @Override
        public Map<String, String> getHeaders()throws AuthFailureError{
            Map<String, String> headers = new HashMap<>();
            headers.put("name",name);
            headers.put("email",email);
            headers.put("password",password);
            headers.put("city",city);
            headers.put("phoneno",phoneno);
            return headers;
        }
    };
    registerRequest.setRetryPolicy(new DefaultRetryPolicy(1000 * 15,
            DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

    /*Response.Listener<String> responseListener = new Response.Listener<String>() {

        @Override
        public void onResponse(String response) {
            Log.d(TAG, response + "");
            try {
                JSONObject jsonResponse = new JSONObject(response);
                boolean success = jsonResponse.getBoolean("success");
                if (success) {
                    Intent intent = new Intent(Register.this, MainActivity.class);
                    startActivity(intent);
                } else {
                    AlertDialog.Builder builder = new AlertDialog.Builder(Register.this);
                    builder.setMessage("Registration failed").setNegativeButton("Retry", null)
                            .create().show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };
    RegisterRequest registerRequest = new RegisterRequest(name, email, city, phoneno, password, responseListener){
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            //super.getHeaders();
            Map<String,String> headers = new HashMap<>();
            String credential = "raju@gmail.com:123";
            String auth = "Basic "+ Base64.encodeToString(credential.getBytes(),Base64.NO_WRAP);
            //headers.put("Content-Type");
            headers.put("Authorization",auth);
            //
            return headers;
        }
    };*/
            RequestQueue queue = Volley.newRequestQueue(Register.this);
            registerRequest.setShouldCache(false);
            queue.add(registerRequest);
}
}
</code>```

Here Is my server code....

```<code>@RequestMapping(value = "/savemobileUser", method = RequestMethod.POST)
public @ResponseBody String saveUser(@RequestBody MobileUserModel mobileUser) {

    MobileUserModel user = new MobileUserModel();
    user.setActivationKey(mobileUser.getActivationKey());
    user.setCity(mobileUser.getCity());
    user.setEmail(mobileUser.getEmail());

    user.setImeino(mobileUser.getImeino());

    user.setName(mobileUser.getName());

    user.setPassword(mobileUser.getPassword());

    user.setPhoneno(mobileUser.getPhoneno());

    userrepository.save(user);

    System.out.println("Saved");

    // return "User has been saved Successfully";
    return "SUCCESS";

}
</code>```

答:
Put following inside your onClick method:</p>

```<code>switch (v.getId()) {
        case R.id.bRegister:

            // add your registration process code here

            break;
}
</code>```

Body:
I am trying to save my data to server. can any one help me?

when i am trying to save data through browser it is working fine but when i try it through this code doesn'n give any response??

public class Register extends AppCompatActivity implements View.OnClickListener {

private static final String TAG = "dRegister";
EditText etName, etEmail, etMobile, etPassword, /*etRePassword*/
        etCity;
Button register;

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

    etName = (EditText) findViewById(R.id.name);
    etEmail = (EditText) findViewById(R.id.email);
    etMobile = (EditText) findViewById(R.id.mobile);
    etCity = (EditText) findViewById(R.id.etCity);
    etPassword = (EditText) findViewById(R.id.password);
    //etRePassword = (EditText) findViewById(R.id.rePassword);
    register = (Button) findViewById(R.id.bRegister);
    register.setOnClickListener(this);

}

@Override
public void onClick(View v) {
    final String name = etName.getText().toString();
    final String email = etEmail.getText().toString();
    final String password = etPassword.getText().toString();
    final String city = etCity.getText().toString();
    final String phoneno = etMobile.getText().toString();

    StringRequest registerRequest = new StringRequest(Request.Method.POST,RegisterRequest.REGISTER_REQUEST_URL, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            Log.d(TAG, response + " Response");
            if(response.equals("SUCCESS")){
                startActivity(new Intent(Register.this,MainActivity.class));
            }
            else{
                Toast.makeText(Register.this, "You have not Registered!", Toast.LENGTH_SHORT).show();
            }

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.d(TAG, "Error " + error.toString());
            if(error.networkResponse == null){
                if(error.getClass().equals(TimeoutError.class));
                Toast.makeText(Register.this, "oops Time out error!", Toast.LENGTH_SHORT).show();
            }
        }
    }){
        @Override
        public Map<String, String> getHeaders()throws AuthFailureError{
            Map<String, String> headers = new HashMap<>();
            headers.put("name",name);
            headers.put("email",email);
            headers.put("password",password);
            headers.put("city",city);
            headers.put("phoneno",phoneno);
            return headers;
        }
    };
    registerRequest.setRetryPolicy(new DefaultRetryPolicy(1000 * 15,
            DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

    /*Response.Listener<String> responseListener = new Response.Listener<String>() {

        @Override
        public void onResponse(String response) {
            Log.d(TAG, response + "");
            try {
                JSONObject jsonResponse = new JSONObject(response);
                boolean success = jsonResponse.getBoolean("success");
                if (success) {
                    Intent intent = new Intent(Register.this, MainActivity.class);
                    startActivity(intent);
                } else {
                    AlertDialog.Builder builder = new AlertDialog.Builder(Register.this);
                    builder.setMessage("Registration failed").setNegativeButton("Retry", null)
                            .create().show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };
    RegisterRequest registerRequest = new RegisterRequest(name, email, city, phoneno, password, responseListener){
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            //super.getHeaders();
            Map<String,String> headers = new HashMap<>();
            String credential = "raju@gmail.com:123";
            String auth = "Basic "+ Base64.encodeToString(credential.getBytes(),Base64.NO_WRAP);
            //headers.put("Content-Type");
            headers.put("Authorization",auth);
            //
            return headers;
        }
    };*/
            RequestQueue queue = Volley.newRequestQueue(Register.this);
            registerRequest.setShouldCache(false);
            queue.add(registerRequest);
}
}

Here Is my server code....

@RequestMapping(value = "/savemobileUser", method = RequestMethod.POST)
public @ResponseBody String saveUser(@RequestBody MobileUserModel mobileUser) {

    MobileUserModel user = new MobileUserModel();
    user.setActivationKey(mobileUser.getActivationKey());
    user.setCity(mobileUser.getCity());
    user.setEmail(mobileUser.getEmail());

    user.setImeino(mobileUser.getImeino());

    user.setName(mobileUser.getName());

    user.setPassword(mobileUser.getPassword());

    user.setPhoneno(mobileUser.getPhoneno());

    userrepository.save(user);

    System.out.println("Saved");

    // return "User has been saved Successfully";
    return "SUCCESS";

}

Body:
Put following inside your onClick method:

switch (v.getId()) {
        case R.id.bRegister:

            // add your registration process code here

            break;
}


问:
Removing dynamically an element from a list
My question can looks a bit weird and easy, but I can't find a satisfying answer. I want to iterate on a list, and remove elements from it. The problem happens when there is one element left in the list after a deletion: the loop will not iterate on the last element, just as if the list was empty.

I am using a for .. in .. like in the following example:

```<code>def test_remove(self):
    """Test to remove all values from a list."""
    test = [4, 5]
    [test.remove(i) for i in test]
    print test
</code>```

I am getting the following output:

```<code>[5]
</code>```

Does it mean that iterating like I am doing on a list doesn't dynamically resize the list when an element is deleted (same thing is happening using for i in range()) ? Or it is just because i am simply reaching i = len, and so I can't go further ?

I could always cheat and check when the len is equal to 1 but I would like to understand if there is a more beautiful way to do this.

Thank you very much.

答: It's not just the last element, it is every odd element - test it on a longer list. This is because as you delete elements, all other elements shift positions. The best way around it is probably to copy the elements you don't want to remove to a new list.

Body:
My question can looks a bit weird and easy, but I can't find a satisfying answer. I want to iterate on a list, and remove elements from it. The problem happens when there is one element left in the list after a deletion: the loop will not iterate on the last element, just as if the list was empty.

I am using a for .. in .. like in the following example:

def test_remove(self):
    """Test to remove all values from a list."""
    test = [4, 5]
    [test.remove(i) for i in test]
    print test

I am getting the following output:

[5]

Does it mean that iterating like I am doing on a list doesn't dynamically resize the list when an element is deleted (same thing is happening using for i in range()) ? Or it is just because i am simply reaching i = len, and so I can't go further ?

I could always cheat and check when the len is equal to 1 but I would like to understand if there is a more beautiful way to do this.

Thank you very much.


问:
PHPMailer: Attempt to assign property of non-object
I'm frustrated to fix this.
One time I made it work. The next day, an error annoys me:

```<code>Warning: Attempt to assign property of non-object in C:\XAMPP\htdocs\HAF\includes\sendmail.php on line 356
</code>```

Help me fix this :(

Here's my code:

sendmail.php

```<code>class SendMail {
    function notification($recipient, $name, $subject, $message) {
        global $email;

        $email->Host = "smtp.gmail.com";
        $email->SMTPAuth = true;
        $email->Username = "******@gmail.com";
        $email->Password = "**********";
        $email->SMTPSecure = "tls";
        $email->Port = 465;

        $email->setFrom('admin@gmail.com', 'My WebApp');

        $email->addAddress($recipient);

        $email->isHTML(true);

        $email->Subject = $subject;
        $email->Body = $message;

        if(!$email->send()) {
            return false;
        } else {
            return true;
        }
    }
}
</code>```

index.php

```<code>$email = "jaydenjames@gmail.com";
$name = "Jayden James";
$message = "Welcome {$name}!";
$SendMail->notification($email, $name, 'Welcome guest!', $message);
</code>```

答:
update answer with gmail configuration....   </p>

```<code> $mail = new PHPMailer();
    $mail->IsSMTP();
    $mail->CharSet="UTF-8";
    $mail->SMTPSecure = 'tls';
    $mail->Host = 'smtp.gmail.com';
    $mail->Port = 587;
    $mail->Username = 'MyUsername@gmail.com';
    $mail->Password = 'valid password';
    $mail->SMTPAuth = true;

    $mail->From = 'MyUsername@gmail.com';
    $mail->FromName = 'Mohammad Masoudian';
    $mail->AddAddress('anotherValidGmail@gmail.com');
    $mail->AddReplyTo('phoenixd110@gmail.com', 'Information');

    $mail->IsHTML(true);
    $mail->Subject    = "PHPMailer Test Subject via Sendmail, basic";
    $mail->AltBody    = "To view the message, please use an HTML compatible email viewer!";
    $mail->Body    = "Hello";

    if(!$mail->Send())
    {
      echo "Mailer Error: " . $mail->ErrorInfo;
    }
    else
    {
      echo "Message sent!";
    }
</code>```

Body:
I'm frustrated to fix this.
One time I made it work. The next day, an error annoys me:

Warning: Attempt to assign property of non-object in C:\XAMPP\htdocs\HAF\includes\sendmail.php on line 356

Help me fix this :(

Here's my code:

sendmail.php

class SendMail {
    function notification($recipient, $name, $subject, $message) {
        global $email;

        $email->Host = "smtp.gmail.com";
        $email->SMTPAuth = true;
        $email->Username = "******@gmail.com";
        $email->Password = "**********";
        $email->SMTPSecure = "tls";
        $email->Port = 465;

        $email->setFrom('admin@gmail.com', 'My WebApp');

        $email->addAddress($recipient);

        $email->isHTML(true);

        $email->Subject = $subject;
        $email->Body = $message;

        if(!$email->send()) {
            return false;
        } else {
            return true;
        }
    }
}

index.php

$email = "jaydenjames@gmail.com";
$name = "Jayden James";
$message = "Welcome {$name}!";
$SendMail->notification($email, $name, 'Welcome guest!', $message);

Body:
update answer with gmail configuration....

 $mail = new PHPMailer();
    $mail->IsSMTP();
    $mail->CharSet="UTF-8";
    $mail->SMTPSecure = 'tls';
    $mail->Host = 'smtp.gmail.com';
    $mail->Port = 587;
    $mail->Username = 'MyUsername@gmail.com';
    $mail->Password = 'valid password';
    $mail->SMTPAuth = true;

    $mail->From = 'MyUsername@gmail.com';
    $mail->FromName = 'Mohammad Masoudian';
    $mail->AddAddress('anotherValidGmail@gmail.com');
    $mail->AddReplyTo('phoenixd110@gmail.com', 'Information');

    $mail->IsHTML(true);
    $mail->Subject    = "PHPMailer Test Subject via Sendmail, basic";
    $mail->AltBody    = "To view the message, please use an HTML compatible email viewer!";
    $mail->Body    = "Hello";

    if(!$mail->Send())
    {
      echo "Mailer Error: " . $mail->ErrorInfo;
    }
    else
    {
      echo "Message sent!";
    }


答:
When you will try to add value in set and that does not present in to the set at that time it will get added and add method will return the true,but if the value is already present in to set at that time add method will returns false.
set.add() method dont be supposed to give you an error when you try to add a value already in the Set,it will simply return the false.

https://docs.oracle.com/javase/7/docs/api/java/util/HashSet.html#add%28E%29

Title: Why compiler don't prevent us, when we try to add duplicate object in Hashset?

Body:
As I know HashSet not do not take duplicate object, When I try below code it simply add first one and ignore second one.Why there is no checked Exception for this. How add() is implemented for HashSet?

public static void main (String[] args) throws java.lang.Exception
{
    HashSet Hs = new HashSet();
    Hs.add("A");
    Hs.add("A");
    System.out.println(Hs);
}

OUTPUT- [A]