问:
Ondraw Method doesnt call Using Viewpager & FragmentStateAdapter
I use a Custom Calendar View using
Viewpager - FragmentStateAdapter - Fragment - Viewgroup -view

I can get first fragment and second fragment when I swipe page, but third fragment doesn't show anything.  so I debug and get draw() method doesn't call on View class.

I use Invalidate(), setWillNotDraw(false) but it doesn't work.

I saw in the log that fragment cycle operates fine. I don't know what the problem is.

Here is my code:

FragmentActivity

```<code>public class FindClassFragmentActivity extends FragmentActivity {

private static final int COUNT_PAGE = 12;

ViewPager mViewPager;

CalendarFragmentStatePagerAdapter calendarAdapter;

ImageButton previous;
ImageButton next;
TextView presentMonth;

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

    mViewPager = (ViewPager) findViewById(R.id.viewpager);
    previous = (ImageButton) findViewById(R.id.previous_month);
    next = (ImageButton) findViewById(R.id.next_month);
    presentMonth = (TextView) findViewById(R.id.present_month);

    calendarAdapter = new CalendarFragmentStatePagerAdapter(getSupportFragmentManager());

    mViewPager.setAdapter(calendarAdapter);
  //  mViewPager.setOffscreenPageLimit(24);

}

public void PrevOrNext(View v) {

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

            break;
        case R.id.next_month :

            break;
    }
}

}
</code>```

FragmentStatePagerAdapter

```<code>public class CalendarFragmentStatePagerAdapter extends FragmentStatePagerAdapter {

private HashMap<Integer, MonthFragment> monthMap;
private int numOfMonth;

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

@Override
public int getCount() {
    return 24;
}

@Override
public Object instantiateItem(ViewGroup container, int position) {
    Log.e("solme6", "instantiateItem : " + position  );
    return super.instantiateItem(container, position);
}

@Override
public Fragment getItem(int position) {
    return MonthFragment.newInstance(position);
}

}
</code>```

CalendarMonthView

```<code>public class CalendarMonthView extends ViewGroup {

private final int mScreenWidth;
private final int mWidthDate;

private int mDateOfWeek; // 1일의 요일

private int mDefaultTextSize = 40;

private int mTextColor = Color.BLUE;

public static String[] DAY_OF_WEEK = null;

public CalendarMonthView(Context context, AttributeSet attrs) {
    super(context, attrs);

    mScreenWidth = getResources().getDisplayMetrics().widthPixels;
    mWidthDate = mScreenWidth / 7;
    DAY_OF_WEEK = getResources().getStringArray(R.array.day_of_week);
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

    int count = getChildCount();

    Log.e("solme",Integer.toString(count));
    int maxHeight = 0;
    int childState = 0;
    int childViewFullWidth = 0;
    int childViewFullheight = 0;

    for(int i=0; i < count; i++) {
        final View child = getChildAt(i);
        getChildAt(i).setWillNotDraw(false);

        if (child.getVisibility() == GONE) {
            continue;
        }
        childViewFullWidth = child.getMeasuredWidth();
        childViewFullheight = child.getMeasuredHeight();
        measureChild(child, widthMeasureSpec, heightMeasureSpec); // 자식의 크기 측정.

        childState = combineMeasuredStates(childState, child.getMeasuredState());
    }

    setMeasuredDimension(childViewFullWidth, childViewFullheight);
    LayoutParams params = getLayoutParams();
    params.height = getMeasuredHeight();
    params.height = maxHeight;
}

@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {

    final int count = getChildCount();

    int curLeft = 0; // 왼쪽 스타트 지점 값.
    int curTop = 0;

    int eachCellWidth, eachCellHeight;

    int curDayHeight;

    final int childWidth = this.getMeasuredWidth(); // 1440
    final int childHeight = this.getMeasuredHeight(); //2355

    for (int i = 0; i < count; i++) {
        View child = getChildAt(i);

        if (child.getVisibility() == GONE)
            return;

        child.measure(MeasureSpec.makeMeasureSpec(childWidth, MeasureSpec.AT_MOST), MeasureSpec.makeMeasureSpec(childHeight, MeasureSpec.AT_MOST));
        eachCellWidth = mWidthDate;
        curDayHeight = 100;
        eachCellHeight = (getMeasuredHeight() - curDayHeight) / 6;

        if (i < 7) {

            child.layout(curLeft, curTop, curLeft + eachCellWidth, curTop + curDayHeight);

            curLeft += eachCellWidth;

            if (curLeft + eachCellWidth >= childWidth) {
                curLeft = 0;
                curTop += curDayHeight;
            }

        } else {

            if (i == 7) {
                curLeft = (mDateOfWeek - 1) * eachCellWidth;
            }
            child.layout(curLeft, curTop, curLeft + eachCellWidth, curTop + eachCellHeight);

            curLeft += eachCellWidth;

            if (curLeft + eachCellWidth >= childWidth) {
                curLeft = 0;
                curTop += eachCellHeight;
            }

        }

    }
}

@Override
protected void onDraw(Canvas canvas) {
    Log.e("solme6", "CalendarMonthView : onDraw");
    super.onDraw(canvas);
}

@Override
public void draw(Canvas canvas) {
    Log.e("solme6", "CalendarMonthView : draw");
    super.draw(canvas);
}

@Override
protected void dispatchDraw(Canvas canvas) {
    super.dispatchDraw(canvas);
}

private Paint makePaint(int color) {
    Paint p = new Paint(Paint.ANTI_ALIAS_FLAG);
    p.setColor(color);
    p.setTextSize(mDefaultTextSize);
    return p;
}

public void initCalendar(int dayOfWeek, int maxDateOfMonth) {
    mDateOfWeek = dayOfWeek;
}

}
</code>```

CalendarcellView

```<code>public class CalendarCellView extends View {

Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
Paint mPaintTextWhite = new Paint(Paint.ANTI_ALIAS_FLAG);
Paint mPaintBackground = new Paint(Paint.ANTI_ALIAS_FLAG);
Paint mPaintBackgroundToday = new Paint(Paint.ANTI_ALIAS_FLAG);
Paint mPaintBackgroundEvent = new Paint(Paint.ANTI_ALIAS_FLAG);
private int dayOfWeek = -1;
private boolean isStaticText = false;
private long millis;
private Rect rect;
private boolean isTouchMode;
private int dp11;
private int dp16;
private boolean hasEvent = false;
private int[] mColorEvents;
private final float RADIUS = 100f;

public CalendarCellView(Context context) {
    super(context);
    initialize(context);
    Log.e("solme6", "CalendarCellView : constructor");
}

public CalendarCellView(Context context, AttributeSet attrs) {
    super(context, attrs);
    initialize(context);

}

private void initialize(Context context) {

    dp11 = (int) dp2px(getContext(), 11);
    dp16 = (int) dp2px(getContext(), 16);

    mPaint.setColor(Color.BLACK);
    mPaint.setTextSize(dp11);
    mPaint.setTextAlign(Paint.Align.CENTER);
    mPaintTextWhite.setColor(Color.WHITE);
    mPaintTextWhite.setTextSize(dp11);
    mPaintTextWhite.setTextAlign(Paint.Align.CENTER);
    mPaintBackground.setColor(ContextCompat.getColor(getContext(), R.color.colorPrimaryDark));
    mPaintBackgroundToday.setColor(ContextCompat.getColor(getContext(), R.color.today));
    mPaintBackgroundEvent.setColor(ContextCompat.getColor(getContext(), R.color.colorPrimary));
    setPadding(30, 0, 30, 0);
}

public float dp2px(Context context, float dp) {
    return dp * context.getResources().getDisplayMetrics().density;
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    Log.e("solme6","CalendarCellView : onMeasure");
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}

@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
    Log.e("solme6", "CalendarCellView : onLayout");
    super.onLayout(changed, left, top, right, bottom);
}

@Override
protected void dispatchDraw(Canvas canvas) {
    Log.e("solme6", "CalendarCellView : dispatchDraw");
}

@Override
public void draw(Canvas canvas) {
    Log.e("solme6", "CalendarCellView : draw");
    super.draw(canvas);
}

@Override
protected void onDraw(Canvas canvas) {
    Log.e("solme6", "CalendarCellView : onDraw");
    super.onDraw(canvas);
    int xPos = (canvas.getWidth() / 2);
    int yPos = (int) ((canvas.getHeight() / 2) - ((mPaint.descent() + mPaint.ascent()) / 2));
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(millis);
    set

    CalendarMonthView calendarView = (CalendarMonthView) getParent();
    if (calendarView.getParent() instanceof ViewPager) {
        ViewGroup parent = (ViewPager) calendarView.getParent();
        CalendarCellView tagView = (CalendarCellView) parent.getTag();

        if (!isStaticText && tagView != null && tagView.getTag() != null && tagView.getTag() instanceof Long) {
            long millis = (long) tagView.getTag();
            if (isSameDay(millis, this.millis)) {
                //   RectF rectF = new RectF(xPos - dp16, getHeight() / 2 - dp16, xPos + dp16, getHeight() / 2 + dp16);
                //   canvas.drawRoundRect(rectF, RADIUS, RADIUS, mPaintBackground);
            }
        }
    }

    if (!isStaticText && isToday(millis)) {
        RectF rectF = new RectF(xPos - dp16, getHeight() / 2 - dp16, xPos + dp16, getHeight() / 2 + dp16);
        canvas.drawRoundRect(rectF, RADIUS, RADIUS, mPaintBackgroundToday);
    }

    if (isStaticText) {
        // 요일 표시
        canvas.drawText(CalendarMonthView.DAY_OF_WEEK[dayOfWeek], xPos, yPos, mPaint);
    } else {
        // 날짜 표시
        if (isToday(millis)) {
            canvas.drawText(calendar.get(Calendar.DATE) + "", xPos, yPos, mPaintTextWhite);
        } else {
            canvas.drawText(calendar.get(Calendar.DATE) + "", xPos, yPos, mPaint);
        }
    }

    if (hasEvent) {
        mPaintBackgroundEvent.setColor(getResources().getColor(mColorEvents[0]));
        RectF rectF = new RectF(xPos - 5, getHeight() / 2 + 20, xPos + 5, getHeight() / 2 + 30);
        canvas.drawRoundRect(rectF, RADIUS, RADIUS, mPaintBackgroundToday);
    }
}

private boolean isToday(long millis) {
    Calendar cal1 = Calendar.getInstance();
    return isSameDay(cal1.getTimeInMillis(), millis);

}

public void setDate(long millis) {
    this.millis = millis;
    setTag(millis);
}

public void setDayOfWeek(int dayOfWeek) {
    this.dayOfWeek = dayOfWeek;
    isStaticText = true;
}

public void setEvent(int... resid) {
    hasEvent = true;
    mColorEvents = resid;
}

public boolean isSameDay(long millis1, long millis2) {
    Calendar cal1 = Calendar.getInstance();
    Calendar cal2 = Calendar.getInstance();
    cal1.setTimeInMillis(millis1);
    cal2.setTimeInMillis(millis2);
    Log.d("hatti.calendar", "" + cal1.get(Calendar.YEAR) + "" + cal1.get(Calendar.MONTH) + "" + cal1.get(Calendar.DATE) + " VS " +
            cal2.get(Calendar.YEAR) + "" + cal2.get(Calendar.MONTH) + "" + cal2.get(Calendar.DATE));
    return (cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) && cal1.get(Calendar.MONTH) == cal2.get(Calendar.MONTH) && cal1.get(Calendar.DATE) == cal2.get(Calendar.DATE));
}

public boolean isStaticText() {
    return isStaticText;
}
}
</code>```

Is there anything I should do for add Fragment on Adapter?

答:
in your pager adapter, </p>

```<code>    @Override
    public int getItemPosition(Object object) {

            return POSITION_NONE;

    }
</code>```

Body:
I use a Custom Calendar View using
Viewpager - FragmentStateAdapter - Fragment - Viewgroup -view

I can get first fragment and second fragment when I swipe page, but third fragment doesn't show anything.  so I debug and get draw() method doesn't call on View class.

I use Invalidate(), setWillNotDraw(false) but it doesn't work.

I saw in the log that fragment cycle operates fine. I don't know what the problem is.

Here is my code:

FragmentActivity

public class FindClassFragmentActivity extends FragmentActivity {

private static final int COUNT_PAGE = 12;

ViewPager mViewPager;

CalendarFragmentStatePagerAdapter calendarAdapter;

ImageButton previous;
ImageButton next;
TextView presentMonth;

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

    mViewPager = (ViewPager) findViewById(R.id.viewpager);
    previous = (ImageButton) findViewById(R.id.previous_month);
    next = (ImageButton) findViewById(R.id.next_month);
    presentMonth = (TextView) findViewById(R.id.present_month);

    calendarAdapter = new CalendarFragmentStatePagerAdapter(getSupportFragmentManager());

    mViewPager.setAdapter(calendarAdapter);
  //  mViewPager.setOffscreenPageLimit(24);

}

public void PrevOrNext(View v) {

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

            break;
        case R.id.next_month :

            break;
    }
}

}

FragmentStatePagerAdapter

public class CalendarFragmentStatePagerAdapter extends FragmentStatePagerAdapter {

private HashMap<Integer, MonthFragment> monthMap;
private int numOfMonth;

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

@Override
public int getCount() {
    return 24;
}

@Override
public Object instantiateItem(ViewGroup container, int position) {
    Log.e("solme6", "instantiateItem : " + position  );
    return super.instantiateItem(container, position);
}

@Override
public Fragment getItem(int position) {
    return MonthFragment.newInstance(position);
}

}

CalendarMonthView

public class CalendarMonthView extends ViewGroup {

private final int mScreenWidth;
private final int mWidthDate;

private int mDateOfWeek; // 1일의 요일

private int mDefaultTextSize = 40;

private int mTextColor = Color.BLUE;

public static String[] DAY_OF_WEEK = null;

public CalendarMonthView(Context context, AttributeSet attrs) {
    super(context, attrs);

    mScreenWidth = getResources().getDisplayMetrics().widthPixels;
    mWidthDate = mScreenWidth / 7;
    DAY_OF_WEEK = getResources().getStringArray(R.array.day_of_week);
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

    int count = getChildCount();

    Log.e("solme",Integer.toString(count));
    int maxHeight = 0;
    int childState = 0;
    int childViewFullWidth = 0;
    int childViewFullheight = 0;

    for(int i=0; i < count; i++) {
        final View child = getChildAt(i);
        getChildAt(i).setWillNotDraw(false);

        if (child.getVisibility() == GONE) {
            continue;
        }
        childViewFullWidth = child.getMeasuredWidth();
        childViewFullheight = child.getMeasuredHeight();
        measureChild(child, widthMeasureSpec, heightMeasureSpec); // 자식의 크기 측정.

        childState = combineMeasuredStates(childState, child.getMeasuredState());
    }

    setMeasuredDimension(childViewFullWidth, childViewFullheight);
    LayoutParams params = getLayoutParams();
    params.height = getMeasuredHeight();
    params.height = maxHeight;
}

@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {

    final int count = getChildCount();

    int curLeft = 0; // 왼쪽 스타트 지점 값.
    int curTop = 0;

    int eachCellWidth, eachCellHeight;

    int curDayHeight;

    final int childWidth = this.getMeasuredWidth(); // 1440
    final int childHeight = this.getMeasuredHeight(); //2355

    for (int i = 0; i < count; i++) {
        View child = getChildAt(i);

        if (child.getVisibility() == GONE)
            return;

        child.measure(MeasureSpec.makeMeasureSpec(childWidth, MeasureSpec.AT_MOST), MeasureSpec.makeMeasureSpec(childHeight, MeasureSpec.AT_MOST));
        eachCellWidth = mWidthDate;
        curDayHeight = 100;
        eachCellHeight = (getMeasuredHeight() - curDayHeight) / 6;

        if (i < 7) {

            child.layout(curLeft, curTop, curLeft + eachCellWidth, curTop + curDayHeight);

            curLeft += eachCellWidth;

            if (curLeft + eachCellWidth >= childWidth) {
                curLeft = 0;
                curTop += curDayHeight;
            }

        } else {

            if (i == 7) {
                curLeft = (mDateOfWeek - 1) * eachCellWidth;
            }
            child.layout(curLeft, curTop, curLeft + eachCellWidth, curTop + eachCellHeight);

            curLeft += eachCellWidth;

            if (curLeft + eachCellWidth >= childWidth) {
                curLeft = 0;
                curTop += eachCellHeight;
            }

        }

    }
}

@Override
protected void onDraw(Canvas canvas) {
    Log.e("solme6", "CalendarMonthView : onDraw");
    super.onDraw(canvas);
}

@Override
public void draw(Canvas canvas) {
    Log.e("solme6", "CalendarMonthView : draw");
    super.draw(canvas);
}

@Override
protected void dispatchDraw(Canvas canvas) {
    super.dispatchDraw(canvas);
}

private Paint makePaint(int color) {
    Paint p = new Paint(Paint.ANTI_ALIAS_FLAG);
    p.setColor(color);
    p.setTextSize(mDefaultTextSize);
    return p;
}

public void initCalendar(int dayOfWeek, int maxDateOfMonth) {
    mDateOfWeek = dayOfWeek;
}

}

CalendarcellView

public class CalendarCellView extends View {

Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
Paint mPaintTextWhite = new Paint(Paint.ANTI_ALIAS_FLAG);
Paint mPaintBackground = new Paint(Paint.ANTI_ALIAS_FLAG);
Paint mPaintBackgroundToday = new Paint(Paint.ANTI_ALIAS_FLAG);
Paint mPaintBackgroundEvent = new Paint(Paint.ANTI_ALIAS_FLAG);
private int dayOfWeek = -1;
private boolean isStaticText = false;
private long millis;
private Rect rect;
private boolean isTouchMode;
private int dp11;
private int dp16;
private boolean hasEvent = false;
private int[] mColorEvents;
private final float RADIUS = 100f;

public CalendarCellView(Context context) {
    super(context);
    initialize(context);
    Log.e("solme6", "CalendarCellView : constructor");
}

public CalendarCellView(Context context, AttributeSet attrs) {
    super(context, attrs);
    initialize(context);

}

private void initialize(Context context) {

    dp11 = (int) dp2px(getContext(), 11);
    dp16 = (int) dp2px(getContext(), 16);

    mPaint.setColor(Color.BLACK);
    mPaint.setTextSize(dp11);
    mPaint.setTextAlign(Paint.Align.CENTER);
    mPaintTextWhite.setColor(Color.WHITE);
    mPaintTextWhite.setTextSize(dp11);
    mPaintTextWhite.setTextAlign(Paint.Align.CENTER);
    mPaintBackground.setColor(ContextCompat.getColor(getContext(), R.color.colorPrimaryDark));
    mPaintBackgroundToday.setColor(ContextCompat.getColor(getContext(), R.color.today));
    mPaintBackgroundEvent.setColor(ContextCompat.getColor(getContext(), R.color.colorPrimary));
    setPadding(30, 0, 30, 0);
}

public float dp2px(Context context, float dp) {
    return dp * context.getResources().getDisplayMetrics().density;
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    Log.e("solme6","CalendarCellView : onMeasure");
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}

@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
    Log.e("solme6", "CalendarCellView : onLayout");
    super.onLayout(changed, left, top, right, bottom);
}

@Override
protected void dispatchDraw(Canvas canvas) {
    Log.e("solme6", "CalendarCellView : dispatchDraw");
}

@Override
public void draw(Canvas canvas) {
    Log.e("solme6", "CalendarCellView : draw");
    super.draw(canvas);
}

@Override
protected void onDraw(Canvas canvas) {
    Log.e("solme6", "CalendarCellView : onDraw");
    super.onDraw(canvas);
    int xPos = (canvas.getWidth() / 2);
    int yPos = (int) ((canvas.getHeight() / 2) - ((mPaint.descent() + mPaint.ascent()) / 2));
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(millis);
    set

    CalendarMonthView calendarView = (CalendarMonthView) getParent();
    if (calendarView.getParent() instanceof ViewPager) {
        ViewGroup parent = (ViewPager) calendarView.getParent();
        CalendarCellView tagView = (CalendarCellView) parent.getTag();

        if (!isStaticText && tagView != null && tagView.getTag() != null && tagView.getTag() instanceof Long) {
            long millis = (long) tagView.getTag();
            if (isSameDay(millis, this.millis)) {
                //   RectF rectF = new RectF(xPos - dp16, getHeight() / 2 - dp16, xPos + dp16, getHeight() / 2 + dp16);
                //   canvas.drawRoundRect(rectF, RADIUS, RADIUS, mPaintBackground);
            }
        }
    }

    if (!isStaticText && isToday(millis)) {
        RectF rectF = new RectF(xPos - dp16, getHeight() / 2 - dp16, xPos + dp16, getHeight() / 2 + dp16);
        canvas.drawRoundRect(rectF, RADIUS, RADIUS, mPaintBackgroundToday);
    }

    if (isStaticText) {
        // 요일 표시
        canvas.drawText(CalendarMonthView.DAY_OF_WEEK[dayOfWeek], xPos, yPos, mPaint);
    } else {
        // 날짜 표시
        if (isToday(millis)) {
            canvas.drawText(calendar.get(Calendar.DATE) + "", xPos, yPos, mPaintTextWhite);
        } else {
            canvas.drawText(calendar.get(Calendar.DATE) + "", xPos, yPos, mPaint);
        }
    }

    if (hasEvent) {
        mPaintBackgroundEvent.setColor(getResources().getColor(mColorEvents[0]));
        RectF rectF = new RectF(xPos - 5, getHeight() / 2 + 20, xPos + 5, getHeight() / 2 + 30);
        canvas.drawRoundRect(rectF, RADIUS, RADIUS, mPaintBackgroundToday);
    }
}

private boolean isToday(long millis) {
    Calendar cal1 = Calendar.getInstance();
    return isSameDay(cal1.getTimeInMillis(), millis);

}

public void setDate(long millis) {
    this.millis = millis;
    setTag(millis);
}

public void setDayOfWeek(int dayOfWeek) {
    this.dayOfWeek = dayOfWeek;
    isStaticText = true;
}

public void setEvent(int... resid) {
    hasEvent = true;
    mColorEvents = resid;
}

public boolean isSameDay(long millis1, long millis2) {
    Calendar cal1 = Calendar.getInstance();
    Calendar cal2 = Calendar.getInstance();
    cal1.setTimeInMillis(millis1);
    cal2.setTimeInMillis(millis2);
    Log.d("hatti.calendar", "" + cal1.get(Calendar.YEAR) + "" + cal1.get(Calendar.MONTH) + "" + cal1.get(Calendar.DATE) + " VS " +
            cal2.get(Calendar.YEAR) + "" + cal2.get(Calendar.MONTH) + "" + cal2.get(Calendar.DATE));
    return (cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) && cal1.get(Calendar.MONTH) == cal2.get(Calendar.MONTH) && cal1.get(Calendar.DATE) == cal2.get(Calendar.DATE));
}

public boolean isStaticText() {
    return isStaticText;
}
}

Is there anything I should do for add Fragment on Adapter?

Body:
in your pager adapter,

    @Override
    public int getItemPosition(Object object) {

            return POSITION_NONE;

    }


来源: stackexchange

问:
"With respect to an indeterminately-sequenced function call" in operators
There are at least 2 operators with similar texts in their description:

With respect to an indeterminately-sequenced function call, the
  operation of an < operator > is a single evaluation.

Where < operator > might be either "compound assignment" ([expr.ass]) or "postfix ++" ([expr.post.incr]). That rule, if understand correctly, states essentially that the any interleaving (overlapping) between the indeterminately-sequenced function call and one of the aforementioned operator is forbidden. But the Standard already forbids it in [intro.execution]p15:

<...> Evaluations A and B are indeterminately sequenced when either A
  is sequenced before B or B is sequenced before A, but it is
  unspecified which. [ Note: Indeterminately sequenced evaluations cannot overlap, but either could be executed first. — end note ] <...>

So to the question: is the wording in the operator description redundant and might as well be removed completely? And if it is not redundant please describe a situation when the text from the operators apply but the general rule does not.

答:
The execution of the postfix increment occurs in two steps: first, an lvalue-to-rvalue conversion is applied, then, at some point before the end of the full-expression, the value stored in the object is incremented. The latter step is sequenced after the former.

Let's say A is sequenced before B, and both A and B are indeterminately sequenced with C. In that case, no pair of A, B, and C may overlap, however, there are three possible execution orders: ABC, ACB, and CAB.

In the case of the postfix increment, the additional guarantee provided by the language is that the order can only be ABC or CAB. A function call will never occur between the lvalue-to-rvalue conversion and the side effect.

ContentLicense: CC BY-SA 3.0


问:
How to create navigation bar item in the custom Navigation Bar in iPhone?
I have created one custom view and added a web view as subview of that custom view. And i have created one navigation bar in programmatically. Now i want to create one Left or Right navigation bar buttons in that view.

```<code>navigBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];

navigBar.tintColor = [UIColor blackColor];

[self.view addSubview:navigBar];

UIBarButtonItem *homeButton = [[UIBarButtonItem alloc] initWithTitle:@"Home" style:UIBarButtonSystemItemAction target:self action:@selector(homeButtonAction)];

navigBar.rightBarButtonItem = homeButton; // it's not supports
</code>```

How can i create navigation bar item in the custom navigation bar?, i want to remove the custom view. So please Help me out!

Thanks.

答:
rightBarButton is defined for UINavigationItem. See the documentation for the  UINavigationItem and for the UINavigationBar (Specially Adding Content to a Navigation Bar).

The method to use is - (void)pushNavigationItem:(UINavigationItem *)item animated:(BOOL)animated

ContentLicense: CC BY-SA 2.5

Body:
I have created one custom view and added a web view as subview of that custom view. And i have created one navigation bar in programmatically. Now i want to create one Left or Right navigation bar buttons in that view.

navigBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];

navigBar.tintColor = [UIColor blackColor];

[self.view addSubview:navigBar];

UIBarButtonItem *homeButton = [[UIBarButtonItem alloc] initWithTitle:@"Home" style:UIBarButtonSystemItemAction target:self action:@selector(homeButtonAction)];

navigBar.rightBarButtonItem = homeButton; // it's not supports

How can i create navigation bar item in the custom navigation bar?, i want to remove the custom view. So please Help me out!

Thanks.


问:
How do I rotate an image around its center using Pygame?
I had been trying to rotate an image around its center in using pygame.transform.rotate() but it's not working. Specifically the part that hangs is rot_image = rot_image.subsurface(rot_rect).copy(). I get the exception:

ValueError: subsurface rectangle outside surface area

Here is the code used to rotate an image:

```<code>def rot_center(image, angle):
    """rotate an image while keeping its center and size"""
    orig_rect = image.get_rect()
    rot_image = pygame.transform.rotate(image, angle)
    rot_rect = orig_rect.copy()
    rot_rect.center = rot_image.get_rect().center
    rot_image = rot_image.subsurface(rot_rect).copy()
    return rot_image
</code>```

答:
There are some problems with the top answer: The position of the previous rect needs to be available in the function, so that we can assign it to the new rect, e.g.:

```<code>rect = new_image.get_rect(center=rect.center)
</code>```

In the other answer the location is obtained by creating a new rect from the original image, but that means it will be positioned at the default (0, 0) coordinates.

The example below should work correctly. The new rect needs the center position of the old rect,  so we pass it as well to the function. Then rotate the image, call get_rect to get a new rect with the correct size and pass the center attribute of the old rect as the center argument. Finally, return both the rotated image and the new rect as a tuple and unpack it in the main loop.

```<code>import pygame as pg

def rotate(image, rect, angle):
    """Rotate the image while keeping its center."""
    # Rotate the original image without modifying it.
    new_image = pg.transform.rotate(image, angle)
    # Get a new rect with the center of the old rect.
    rect = new_image.get_rect(center=rect.center)
    return new_image, rect

def main():
    clock = pg.time.Clock()
    screen = pg.display.set_mode((640, 480))
    gray = pg.Color('gray15')
    blue = pg.Color('dodgerblue2')

    image = pg.Surface((320, 200), pg.SRCALPHA)
    pg.draw.polygon(image, blue, ((0, 0), (320, 100), (0, 200)))
    # Keep a reference to the original to preserve the image quality.
    orig_image = image
    rect = image.get_rect(center=(320, 240))
    angle = 0

    done = False
    while not done:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                done = True

        angle += 2
        image, rect = rotate(orig_image, rect, angle)

        screen.fill(gray)
        screen.blit(image, rect)
        pg.display.flip()
        clock.tick(30)

if __name__ == '__main__':
    pg.init()
    main()
    pg.quit()
</code>```

Here's another example with a rotating pygame sprite.

```<code>import pygame as pg

class Entity(pg.sprite.Sprite):

    def __init__(self, pos):
        super().__init__()
        self.image = pg.Surface((122, 70), pg.SRCALPHA)
        pg.draw.polygon(self.image, pg.Color('dodgerblue1'),
                        ((1, 0), (120, 35), (1, 70)))
        # A reference to the original image to preserve the quality.
        self.orig_image = self.image
        self.rect = self.image.get_rect(center=pos)
        self.angle = 0

    def update(self):
        self.angle += 2
        self.rotate()

    def rotate(self):
        """Rotate the image of the sprite around its center."""
        # `rotozoom` usually looks nicer than `rotate`. Pygame's rotation
        # functions return new images and don't modify the originals.
        self.image = pg.transform.rotozoom(self.orig_image, self.angle, 1)
        # Create a new rect with the center of the old rect.
        self.rect = self.image.get_rect(center=self.rect.center)

def main():
    screen = pg.display.set_mode((640, 480))
    clock = pg.time.Clock()
    all_sprites = pg.sprite.Group(Entity((320, 240)))

    while True:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                return

        all_sprites.update()
        screen.fill((30, 30, 30))
        all_sprites.draw(screen)
        pg.display.flip()
        clock.tick(30)

if __name__ == '__main__':
    pg.init()
    main()
    pg.quit()
</code>```

Body:
I had been trying to rotate an image around its center in using pygame.transform.rotate() but it's not working. Specifically the part that hangs is rot_image = rot_image.subsurface(rot_rect).copy(). I get the exception:

ValueError: subsurface rectangle outside surface area

Here is the code used to rotate an image:

def rot_center(image, angle):
    """rotate an image while keeping its center and size"""
    orig_rect = image.get_rect()
    rot_image = pygame.transform.rotate(image, angle)
    rot_rect = orig_rect.copy()
    rot_rect.center = rot_image.get_rect().center
    rot_image = rot_image.subsurface(rot_rect).copy()
    return rot_image

Body:
There are some problems with the top answer: The position of the previous rect needs to be available in the function, so that we can assign it to the new rect, e.g.:

rect = new_image.get_rect(center=rect.center)

In the other answer the location is obtained by creating a new rect from the original image, but that means it will be positioned at the default (0, 0) coordinates.

The example below should work correctly. The new rect needs the center position of the old rect,  so we pass it as well to the function. Then rotate the image, call get_rect to get a new rect with the correct size and pass the center attribute of the old rect as the center argument. Finally, return both the rotated image and the new rect as a tuple and unpack it in the main loop.

import pygame as pg

def rotate(image, rect, angle):
    """Rotate the image while keeping its center."""
    # Rotate the original image without modifying it.
    new_image = pg.transform.rotate(image, angle)
    # Get a new rect with the center of the old rect.
    rect = new_image.get_rect(center=rect.center)
    return new_image, rect

def main():
    clock = pg.time.Clock()
    screen = pg.display.set_mode((640, 480))
    gray = pg.Color('gray15')
    blue = pg.Color('dodgerblue2')

    image = pg.Surface((320, 200), pg.SRCALPHA)
    pg.draw.polygon(image, blue, ((0, 0), (320, 100), (0, 200)))
    # Keep a reference to the original to preserve the image quality.
    orig_image = image
    rect = image.get_rect(center=(320, 240))
    angle = 0

    done = False
    while not done:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                done = True

        angle += 2
        image, rect = rotate(orig_image, rect, angle)

        screen.fill(gray)
        screen.blit(image, rect)
        pg.display.flip()
        clock.tick(30)

if __name__ == '__main__':
    pg.init()
    main()
    pg.quit()

Here's another example with a rotating pygame sprite.

import pygame as pg

class Entity(pg.sprite.Sprite):

    def __init__(self, pos):
        super().__init__()
        self.image = pg.Surface((122, 70), pg.SRCALPHA)
        pg.draw.polygon(self.image, pg.Color('dodgerblue1'),
                        ((1, 0), (120, 35), (1, 70)))
        # A reference to the original image to preserve the quality.
        self.orig_image = self.image
        self.rect = self.image.get_rect(center=pos)
        self.angle = 0

    def update(self):
        self.angle += 2
        self.rotate()

    def rotate(self):
        """Rotate the image of the sprite around its center."""
        # `rotozoom` usually looks nicer than `rotate`. Pygame's rotation
        # functions return new images and don't modify the originals.
        self.image = pg.transform.rotozoom(self.orig_image, self.angle, 1)
        # Create a new rect with the center of the old rect.
        self.rect = self.image.get_rect(center=self.rect.center)

def main():
    screen = pg.display.set_mode((640, 480))
    clock = pg.time.Clock()
    all_sprites = pg.sprite.Group(Entity((320, 240)))

    while True:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                return

        all_sprites.update()
        screen.fill((30, 30, 30))
        all_sprites.draw(screen)
        pg.display.flip()
        clock.tick(30)

if __name__ == '__main__':
    pg.init()
    main()
    pg.quit()


问:
Getting array data from PHP to jQuery for outputting
Here is the partial code from the remove PHP file:

```<code>if($action == 'trackings_get') {
    $result = $trackings->get(getCourierSlugByID($GLOBALS['tracking_id']), $GLOBALS['tracking_id']);
    $result_history = $result['data']['tracking']['checkpoints'];

    echo json_encode($result_history);

    // debugging
    //pretty_print($result_history);
}
</code>```

Here is the JS from the remote site i am trying to call the data for:

```<code>$.ajax({
  url: '/login/tracking.php',
  type: 'POST',
  dataType: "json",
  data: {
    action: action,
    tracking_id: tracking_id
  },
  success: function(json){
    //debug
    alert(JSON.stringify(json));
  }
});
</code>```

答:
i try this code in inspect element  in this page https://tracking.ambientlounge.com/

```<code>function test(){
$.ajax({
  url: 'your url',
  type: 'POST',
  dataType: "json",
  data: {
    action: "action",
    tracking_id: "tracking_id"
  },
  success: function(json){
    //debug
    console.log(json);
  }
});

}
</code>```

result is array . dont need JSON.stringify .

Body:
Here is the partial code from the remove PHP file:

if($action == 'trackings_get') {
    $result = $trackings->get(getCourierSlugByID($GLOBALS['tracking_id']), $GLOBALS['tracking_id']);
    $result_history = $result['data']['tracking']['checkpoints'];

    echo json_encode($result_history);

    // debugging
    //pretty_print($result_history);
}

Here is the JS from the remote site i am trying to call the data for:

$.ajax({
  url: '/login/tracking.php',
  type: 'POST',
  dataType: "json",
  data: {
    action: action,
    tracking_id: tracking_id
  },
  success: function(json){
    //debug
    alert(JSON.stringify(json));
  }
});

Body:
i try this code in inspect element  in this page https://tracking.ambientlounge.com/

function test(){
$.ajax({
  url: 'your url',
  type: 'POST',
  dataType: "json",
  data: {
    action: "action",
    tracking_id: "tracking_id"
  },
  success: function(json){
    //debug
    console.log(json);
  }
});

}

result is array . dont need JSON.stringify .


问:
Unable to start activity ComponentInfo?android.view.InflateException: Binary XML file line #8: Error inflating class <unknown>
I am trying to create a page in android app. It is working fine in all the mobiles except in the mobile which is having Android 8.0. Here is the XML file code

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

        <TextView
                android:id="@+id/text1d"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"

                android:layout_marginTop="14dp"
                android:enabled="true"
                android:maxLength="50"
                android:text="Welcome Customer xxxxxx"
                android:textSize="12sp"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/text2d"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"

                android:enabled="true"
                android:maxLength="50"
                android:text="" />

                 <LinearLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal" >

                    <TextView
                           android:id="@+id/textView"
                           android:layout_width="wrap_content"
                           android:layout_height="wrap_content"
                           android:layout_alignParentLeft="true"
                           android:layout_alignTop="@+id/imageButton1"
                           android:gravity="center"
                           android:singleLine="false"
                           android:text=""
                           android:textSize="12dp" />

                    <TextView
                            android:id="@+id/text3"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"

                            android:layout_below="@+id/text2"
                            android:enabled="true"
                            android:maxLength="50"
                            android:text=""
                            android:textSize="12dp"
                             />
                </LinearLayout>

               <LinearLayout
                   android:layout_width="wrap_content"
                   android:layout_height="wrap_content"
                   android:orientation="horizontal" >

                   <ImageButton
                       android:id="@+id/imageButton12"
                       android:layout_width="15dp"
                       android:layout_height="15dp"

                       android:layout_below="@+id/textView3"
                       android:layout_marginRight="14dp"
                       android:background="@drawable/rotate6"
                       android:contentDescription="From Date" />

             </LinearLayout>

             <LinearLayout
                   android:layout_width="wrap_content"
                   android:layout_height="wrap_content"
                   android:orientation="horizontal"
                   android:layout_marginTop="-10dp"
                   android:layout_gravity="right">

                   <ImageButton
                       android:id="@+id/imageButtondl"
                       android:layout_width="50dip"
                       android:layout_height="50dip"
                       android:background="@drawable/logout"
                       android:contentDescription="Logout" />
               </LinearLayout>

            <ListView
            android:id="@+id/mylist"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"/>
            />

            <Button
            android:id="@+id/btn_static"
            android:layout_gravity="center"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="EDIT"/>
            </LinearLayout>
</code>```

I was not able to get the log cat as my emulator was not in a working mode due to restriction of proxy server in our domain. Please help me out guys

Finally able to get the Stack trace by sending it to mail

```<code>                java.lang.RuntimeException: Unable to start activity ComponentInfo{kvbank.kvb_ebook/kvbank.kvb_epassbook.dummy}: android.view.InflateException: Binary XML file line #8: Binary XML file line #8: Error inflating class <unknown>
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2946)
            at android.app.ActivityThread.startActivityNow(ActivityThread.java:2744)
            at android.app.LocalActivityManager.moveToState(LocalActivityManager.java:136)
            at android.app.LocalActivityManager.startActivity(LocalActivityManager.java:348)
            at android.widget.TabHost$IntentContentStrategy.getContentView(TabHost.java:769)
            at android.widget.TabHost.setCurrentTab(TabHost.java:423)
            at android.widget.TabHost.addTab(TabHost.java:233)
            at kvbank.kvb_epassbook.TabDemo.onCreate(TabDemo.java:87)
            at android.app.Activity.performCreate(Activity.java:6998)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1230)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2899)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3046)
            at android.app.ActivityThread.-wrap11(Unknown Source:0)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1688)
            at android.os.Handler.dispatchMessage(Handler.java:105)
            at android.os.Looper.loop(Looper.java:164)
            at android.app.ActivityThread.main(ActivityThread.java:6809)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
            Caused by: android.view.InflateException: Binary XML file line #8: Binary XML file line #8: Error inflating class <unknown>
            Caused by: android.view.InflateException: Binary XML file line #8: Error inflating class <unknown>
            Caused by: java.lang.reflect.InvocationTargetException
            at java.lang.reflect.Constructor.newInstance0(Native Method)
            at java.lang.reflect.Constructor.newInstance(Constructor.java:334)
            at android.view.LayoutInflater.createView(LayoutInflater.java:647)
            at com.android.internal.policy.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:58)
            at android.view.LayoutInflater.onCreateView(LayoutInflater.java:720)
            at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:788)
            at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:730)
            at android.view.LayoutInflater.rInflate(LayoutInflater.java:863)
            at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:824)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
            at com.android.internal.policy.PhoneWindow.setContentView(PhoneWindow.java:432)
            at android.app.Activity.setContentView(Activity.java:2677)
            at kvbank.kvb_epassbook.dummy.onCreate(dummy.java:190)
            at android.app.Activity.performCreate(Activity.java:6998)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1230)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2899)
            at android.app.ActivityThread.startActivityNow(ActivityThread.java:2744)
            at android.app.LocalActivityManager.moveToState(LocalActivityManager.java:136)
            at android.app.LocalActivityManager.startActivity(LocalActivityManager.java:348)
            at android.widget.TabHost$IntentContentStrategy.getContentView(TabHost.java:769)
            at android.widget.TabHost.setCurrentTab(TabHost.java:423)
            at android.widget.TabHost.addTab(TabHost.java:233)
            at kvbank.kvb_epassbook.TabDemo.onCreate(TabDemo.java:87)
            at android.app.Activity.performCreate(Activity.java:6998)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1230)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2899)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3046)
            at android.app.ActivityThread.-wrap11(Unknown Source:0)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1688)
            at android.os.Handler.dispatchMessage(Handler.java:105)
            at android.os.Looper.loop(Looper.java:164)
            at android.app.ActivityThread.main(ActivityThread.java:6809)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
            Caused by: java.lang.UnsupportedOperationException: Failed to resolve attribute at index 6: TypedValue{t=0x2/d=0x101009b a=1}
            at android.content.res.TypedArray.getColorStateList(TypedArray.java:538)
            at android.widget.TextView.<init>(TextView.java:910)
            at android.widget.TextView.<init>(TextView.java:824)
            at android.widget.TextView.<init>(TextView.java:820)
            ... 37 more
</code>```

SOLUTION

```<code>   Issue got solved. I am using "android:theme="@android:style/Theme.Holo""
   for my dummy class in android manifest which is not defined. removing
   this line solved my issue
</code>```

答:
As you said, you are not able to get Log file. I'm not pretty much sure on the reason behind this. You may try this.

1. Unexpected text /> in your xml below the Listview myList. Remove that part

Even you can see warning in your XML with Unexpected text found in file: "/>" Always Check your XML warning for any InflateClassException

Layout Resource file should only content elements and attributes.Any
  XML text content found in file is likely accidental.

(From the warning message that represents the chance of crash.)

2. Remove Numbers form Id as ids are typically assigned in the layout XML file as a string.

Body:
I am trying to create a page in android app. It is working fine in all the mobiles except in the mobile which is having Android 8.0. Here is the XML file code

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

        <TextView
                android:id="@+id/text1d"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"

                android:layout_marginTop="14dp"
                android:enabled="true"
                android:maxLength="50"
                android:text="Welcome Customer xxxxxx"
                android:textSize="12sp"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/text2d"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"

                android:enabled="true"
                android:maxLength="50"
                android:text="" />

                 <LinearLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal" >

                    <TextView
                           android:id="@+id/textView"
                           android:layout_width="wrap_content"
                           android:layout_height="wrap_content"
                           android:layout_alignParentLeft="true"
                           android:layout_alignTop="@+id/imageButton1"
                           android:gravity="center"
                           android:singleLine="false"
                           android:text=""
                           android:textSize="12dp" />

                    <TextView
                            android:id="@+id/text3"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"

                            android:layout_below="@+id/text2"
                            android:enabled="true"
                            android:maxLength="50"
                            android:text=""
                            android:textSize="12dp"
                             />
                </LinearLayout>

               <LinearLayout
                   android:layout_width="wrap_content"
                   android:layout_height="wrap_content"
                   android:orientation="horizontal" >

                   <ImageButton
                       android:id="@+id/imageButton12"
                       android:layout_width="15dp"
                       android:layout_height="15dp"

                       android:layout_below="@+id/textView3"
                       android:layout_marginRight="14dp"
                       android:background="@drawable/rotate6"
                       android:contentDescription="From Date" />

             </LinearLayout>

             <LinearLayout
                   android:layout_width="wrap_content"
                   android:layout_height="wrap_content"
                   android:orientation="horizontal"
                   android:layout_marginTop="-10dp"
                   android:layout_gravity="right">

                   <ImageButton
                       android:id="@+id/imageButtondl"
                       android:layout_width="50dip"
                       android:layout_height="50dip"
                       android:background="@drawable/logout"
                       android:contentDescription="Logout" />
               </LinearLayout>

            <ListView
            android:id="@+id/mylist"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"/>
            />

            <Button
            android:id="@+id/btn_static"
            android:layout_gravity="center"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="EDIT"/>
            </LinearLayout>

I was not able to get the log cat as my emulator was not in a working mode due to restriction of proxy server in our domain. Please help me out guys

Finally able to get the Stack trace by sending it to mail

                java.lang.RuntimeException: Unable to start activity ComponentInfo{kvbank.kvb_ebook/kvbank.kvb_epassbook.dummy}: android.view.InflateException: Binary XML file line #8: Binary XML file line #8: Error inflating class <unknown>
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2946)
            at android.app.ActivityThread.startActivityNow(ActivityThread.java:2744)
            at android.app.LocalActivityManager.moveToState(LocalActivityManager.java:136)
            at android.app.LocalActivityManager.startActivity(LocalActivityManager.java:348)
            at android.widget.TabHost$IntentContentStrategy.getContentView(TabHost.java:769)
            at android.widget.TabHost.setCurrentTab(TabHost.java:423)
            at android.widget.TabHost.addTab(TabHost.java:233)
            at kvbank.kvb_epassbook.TabDemo.onCreate(TabDemo.java:87)
            at android.app.Activity.performCreate(Activity.java:6998)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1230)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2899)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3046)
            at android.app.ActivityThread.-wrap11(Unknown Source:0)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1688)
            at android.os.Handler.dispatchMessage(Handler.java:105)
            at android.os.Looper.loop(Looper.java:164)
            at android.app.ActivityThread.main(ActivityThread.java:6809)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
            Caused by: android.view.InflateException: Binary XML file line #8: Binary XML file line #8: Error inflating class <unknown>
            Caused by: android.view.InflateException: Binary XML file line #8: Error inflating class <unknown>
            Caused by: java.lang.reflect.InvocationTargetException
            at java.lang.reflect.Constructor.newInstance0(Native Method)
            at java.lang.reflect.Constructor.newInstance(Constructor.java:334)
            at android.view.LayoutInflater.createView(LayoutInflater.java:647)
            at com.android.internal.policy.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:58)
            at android.view.LayoutInflater.onCreateView(LayoutInflater.java:720)
            at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:788)
            at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:730)
            at android.view.LayoutInflater.rInflate(LayoutInflater.java:863)
            at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:824)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
            at com.android.internal.policy.PhoneWindow.setContentView(PhoneWindow.java:432)
            at android.app.Activity.setContentView(Activity.java:2677)
            at kvbank.kvb_epassbook.dummy.onCreate(dummy.java:190)
            at android.app.Activity.performCreate(Activity.java:6998)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1230)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2899)
            at android.app.ActivityThread.startActivityNow(ActivityThread.java:2744)
            at android.app.LocalActivityManager.moveToState(LocalActivityManager.java:136)
            at android.app.LocalActivityManager.startActivity(LocalActivityManager.java:348)
            at android.widget.TabHost$IntentContentStrategy.getContentView(TabHost.java:769)
            at android.widget.TabHost.setCurrentTab(TabHost.java:423)
            at android.widget.TabHost.addTab(TabHost.java:233)
            at kvbank.kvb_epassbook.TabDemo.onCreate(TabDemo.java:87)
            at android.app.Activity.performCreate(Activity.java:6998)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1230)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2899)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3046)
            at android.app.ActivityThread.-wrap11(Unknown Source:0)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1688)
            at android.os.Handler.dispatchMessage(Handler.java:105)
            at android.os.Looper.loop(Looper.java:164)
            at android.app.ActivityThread.main(ActivityThread.java:6809)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
            Caused by: java.lang.UnsupportedOperationException: Failed to resolve attribute at index 6: TypedValue{t=0x2/d=0x101009b a=1}
            at android.content.res.TypedArray.getColorStateList(TypedArray.java:538)
            at android.widget.TextView.<init>(TextView.java:910)
            at android.widget.TextView.<init>(TextView.java:824)
            at android.widget.TextView.<init>(TextView.java:820)
            ... 37 more

SOLUTION

   Issue got solved. I am using "android:theme="@android:style/Theme.Holo""
   for my dummy class in android manifest which is not defined. removing
   this line solved my issue


问:
Opaque struct with C linkage & C++ implementation
Say I want a struct foo with C linkage. I'll declare it in a C-style header file (foo.h) opaquely:

```<code>struct foo;
typedef struct foo foo;
</code>```

But I want to use C++ in the implementation of foo. Say I want foo to contain a std::vector<int>. Since C code wouldn't have access to foo's fields, I don't see why the compiler (or language standards) should prohibit this. But how would I do that? Can I just put extern "C" around the implementation of foo in foo.cc like this?

```<code>extern "C" {
    struct foo {
        ....
        std::vector<int> bar;
    }
}
</code>```

答: A struct is compatible between C and C++ as long as the content of the struct is POD (plain old data). If you add non-POD into it e.g. your vector, it no longer is compatible with C and will cause undefined behavior when used with typical C functions like memset or memcpy. The non-POD members cause another memory layout of the struct, it gets a virtual table at the start of it to support inheritance.

Body:
Say I want a struct foo with C linkage. I'll declare it in a C-style header file (foo.h) opaquely:

struct foo;
typedef struct foo foo;

But I want to use C++ in the implementation of foo. Say I want foo to contain a std::vector<int>. Since C code wouldn't have access to foo's fields, I don't see why the compiler (or language standards) should prohibit this. But how would I do that? Can I just put extern "C" around the implementation of foo in foo.cc like this?

extern "C" {
    struct foo {
        ....
        std::vector<int> bar;
    }
}


问:
Why does grepping the same manpage sometimes results in an error?
The exact same command:

```<code>man curl | grep -Pzo 'EXIT CODES(.|\n)*AUTHORS' | grep '  6  '
</code>```

sometimes gives the expected output:

```<code>       6      Couldn't resolve host. The given remote host was not resolved.
</code>```

and sometimes gives the error:

```<code>Binary file (standard input) matches
</code>```

eg:

```<code>$ man curl | grep -Pzo 'EXIT CODES(.|\n)*AUTHORS' | grep '  6  '
       6      Couldn't resolve host. The given remote host was not resolved.

$ man curl | grep -Pzo 'EXIT CODES(.|\n)*AUTHORS' | grep '  6  '
Binary file (standard input) matches

$ man curl | grep -Pzo 'EXIT CODES(.|\n)*AUTHORS' | grep '  6  '
Binary file (standard input) matches

$ man curl | grep -Pzo 'EXIT CODES(.|\n)*AUTHORS' | grep '  6  '
       6      Couldn't resolve host. The given remote host was not resolved.
</code>```

Versions of relevant packages:

```<code>$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 16.04.1 LTS
Release:        16.04
Codename:       xenial

$ grep --version
grep (GNU grep) 2.25
Copyright (C) 2016 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

Written by Mike Haertel and others, see <http://git.sv.gnu.org/cgit/grep.git/tree/AUTHORS>.

$ man --version
man 2.7.5

$ curl --version
curl 7.47.0 (x86_64-pc-linux-gnu) libcurl/7.47.0 GnuTLS/3.4.10 zlib/1.2.8 libidn/1.32 librtmp/2.3
Protocols: dict file ftp ftps gopher http https imap imaps ldap ldaps pop3 pop3s rtmp rtsp smb smbs smtp smtps telnet tftp
Features: AsynchDNS IDN IPv6 Largefile GSS-API Kerberos SPNEGO NTLM NTLM_WB SSL libz TLS-SRP UnixSockets
</code>```

I'm really scratching my head over this one.

I've solved my issue by putting -a flags into my greps as such: man curl | grep -Pzoa 'EXIT CODES(.|\n)*AUTHORS' | grep -a '  6  '

But I'm truly stumped over why it only errors sometimes?...

答:
Because the -z option is used, the first grep appends a NUL character to the end of the output.  What happens next depends on the vagaries of buffering.  If the second grep sees that NUL before analyzing the file, it decides that the file is binary.  If it doesn't, it finds the match that you want.

So, this happened to work for me:

```<code>$ man curl | grep -Pzo 'EXIT CODES(.|\n)*AUTHORS' | grep '  6  '
       6      Couldn't resolve host. The given remote host was not resolved.
</code>```

However, if I put the output of the first grep in a temporary file and asking the second grep to read that, then the second grep would always complain about the input being binary:

```<code>$ man curl | grep -Pzo 'EXIT CODES(.|\n)*AUTHORS' >tmpfile;  grep '  6  ' tmpfile
Binary file tmpfile matches
</code>```

Alternative: use awk

One way of avoiding the NUL character issues, as well as reducing the number of processes required, is to use awk:

```<code>$ man curl | awk '/EXIT CODES/,/AUTHORS/{if (/   6   /) print}'
       6      Couldn't resolve host. The given remote host was not resolved.
</code>```

Alternative: use sed

```<code>$ man curl | sed -n '/EXIT CODES/,/AUTHORS/{/   6   /p}'
       6      Couldn't resolve host. The given remote host was not resolved.
</code>```

Alternative: use greps and tr

As tripleee suggests, another option is to use tr to replace the NUL with a newline:

```<code>$ man curl | grep -Pzo 'EXIT CODES(.|\n)*AUTHORS' | tr '\000' '\n' | grep '  6  '
       6      Couldn't resolve host. The given remote host was not resolved.
</code>```

Body:
The exact same command:

man curl | grep -Pzo 'EXIT CODES(.|\n)*AUTHORS' | grep '  6  '

sometimes gives the expected output:

       6      Couldn't resolve host. The given remote host was not resolved.

and sometimes gives the error:

Binary file (standard input) matches

eg:

$ man curl | grep -Pzo 'EXIT CODES(.|\n)*AUTHORS' | grep '  6  '
       6      Couldn't resolve host. The given remote host was not resolved.

$ man curl | grep -Pzo 'EXIT CODES(.|\n)*AUTHORS' | grep '  6  '
Binary file (standard input) matches

$ man curl | grep -Pzo 'EXIT CODES(.|\n)*AUTHORS' | grep '  6  '
Binary file (standard input) matches

$ man curl | grep -Pzo 'EXIT CODES(.|\n)*AUTHORS' | grep '  6  '
       6      Couldn't resolve host. The given remote host was not resolved.

Versions of relevant packages:

$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 16.04.1 LTS
Release:        16.04
Codename:       xenial

$ grep --version
grep (GNU grep) 2.25
Copyright (C) 2016 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

Written by Mike Haertel and others, see <http://git.sv.gnu.org/cgit/grep.git/tree/AUTHORS>.

$ man --version
man 2.7.5

$ curl --version
curl 7.47.0 (x86_64-pc-linux-gnu) libcurl/7.47.0 GnuTLS/3.4.10 zlib/1.2.8 libidn/1.32 librtmp/2.3
Protocols: dict file ftp ftps gopher http https imap imaps ldap ldaps pop3 pop3s rtmp rtsp smb smbs smtp smtps telnet tftp
Features: AsynchDNS IDN IPv6 Largefile GSS-API Kerberos SPNEGO NTLM NTLM_WB SSL libz TLS-SRP UnixSockets

I'm really scratching my head over this one.

I've solved my issue by putting -a flags into my greps as such: man curl | grep -Pzoa 'EXIT CODES(.|\n)*AUTHORS' | grep -a '  6  '

But I'm truly stumped over why it only errors sometimes?...

Body:
Because the -z option is used, the first grep appends a NUL character to the end of the output.  What happens next depends on the vagaries of buffering.  If the second grep sees that NUL before analyzing the file, it decides that the file is binary.  If it doesn't, it finds the match that you want.

So, this happened to work for me:

$ man curl | grep -Pzo 'EXIT CODES(.|\n)*AUTHORS' | grep '  6  '
       6      Couldn't resolve host. The given remote host was not resolved.

However, if I put the output of the first grep in a temporary file and asking the second grep to read that, then the second grep would always complain about the input being binary:

$ man curl | grep -Pzo 'EXIT CODES(.|\n)*AUTHORS' >tmpfile;  grep '  6  ' tmpfile
Binary file tmpfile matches

Alternative: use awk

One way of avoiding the NUL character issues, as well as reducing the number of processes required, is to use awk:

$ man curl | awk '/EXIT CODES/,/AUTHORS/{if (/   6   /) print}'
       6      Couldn't resolve host. The given remote host was not resolved.

Alternative: use sed

$ man curl | sed -n '/EXIT CODES/,/AUTHORS/{/   6   /p}'
       6      Couldn't resolve host. The given remote host was not resolved.

Alternative: use greps and tr

As tripleee suggests, another option is to use tr to replace the NUL with a newline:

$ man curl | grep -Pzo 'EXIT CODES(.|\n)*AUTHORS' | tr '\000' '\n' | grep '  6  '
       6      Couldn't resolve host. The given remote host was not resolved.


问:
WCF Optimal performance settings
Hi i am creating an API using WCF. My question can be broken down into two seperate ones

1) I have quite a few calls, for instance i have calls relating to the customer, products, orders, employees.

My question is should all this go into one public interface class e.g

```<code>public interface IRestService
public class RestService : IRestService
</code>```

Or should I have one for each call e.g

```<code>public interface ICustomer
public class Customer : ICustomer

public interface IProducts
public class Products: IProducts
</code>```

2) If you have an API which will be accessed by tens of thousands of users and thousands of users concurrently, how would you set up, what will your web config settings be for instance in terms of throttling. Also what setting would you give your InstanceContextMode, or ConcurrencyMode. Finally what type of binding would it be, bearing in mind websites and mobile phones can access the api.

答:
If you really have few operations, single service can be used. Generally services are logical collection of related operations but the number of operations should be limited. Usually if your service have more than 20 operations you should think about refactoring.

Do you plan to use REST service? I guess you do because of your first interface example. In such case you need WebHttpBinding (or similar custom binding) with default InstanceContextMode (PerCall) and ConcurrencyMode (Single) values. Only other meaningful combination for REST service is InstanceContextMode.Single and ConcurrencyMode.Multiple but it will create your service as singleton which can have impact on your service implementation. My rule of thumb: Don't use singleton service unless you really need it.

Throttling configuration is dependend on your service implementation and on performance of your servers. What does thousands concurrent users really mean for you? Processing thousands of requests concurrently requires good server cluster with load balancer or hosting in Azure (cloud). All is also dependend on the speed of processing (operation implementation) and size of messages. The correct setting for MaxConcurrentInstances and MaxConcurrentCalls (should be same for PerCall instancing) should be revealed by performance testing. Default values for service throttling have changed in WCF 4.

Title: WCF Optimal performance settings

Body:
Hi i am creating an API using WCF. My question can be broken down into two seperate ones

1) I have quite a few calls, for instance i have calls relating to the customer, products, orders, employees.

My question is should all this go into one public interface class e.g

public interface IRestService
public class RestService : IRestService

Or should I have one for each call e.g

public interface ICustomer
public class Customer : ICustomer

public interface IProducts
public class Products: IProducts

2) If you have an API which will be accessed by tens of thousands of users and thousands of users concurrently, how would you set up, what will your web config settings be for instance in terms of throttling. Also what setting would you give your InstanceContextMode, or ConcurrencyMode. Finally what type of binding would it be, bearing in mind websites and mobile phones can access the api.


问:
Google Maps API Search Along Route
Is there a way I can use Google Maps/Google Places API to search for places along a route like the app allows?</p>

答:
hello using placeApi u can not draw route for drawing route between two place u need to use  direction Api for that u can use this link </p>

<p>https://developers.google.com/maps/documentation/directions/intro </p>

Title: Google Maps API Search Along Route

Body:
hello using placeApi u can not draw route for drawing route between two place u need to use  direction Api for that u can use this link

https://developers.google.com/maps/documentation/directions/intro


问:
MySQL connection made but query failing
Im trying to create a login page.
Connection is successful but query is not fetching the required result.
login page sends data through post method to action_page.php.

Action_page.php

```<code><?php
$servername = "localhost:3306";
$username = "root";
$password = "";
$dbname = "MyDB";

$con = mysqli_connect($servername, $username, $password, $dbname);

// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$uname = $_POST['uname'];
$pass = $_POST['psw'];
$sql = "SELECT * FROM Users WHERE uname=".$uname." AND pass=".$pass;
echo "<br/>$sql<br/>";

//$result = $con->query($sql);

echo var_dump($con->query($sql));

$con->close();
</code>```

?>

could someone please help.!

答:
update from </p>

```<code>$sql = "SELECT * FROM Users WHERE uname=".$uname." AND pass=".$pass;
</code>```

<p>to </p>

```<code>$sql = "SELECT * FROM Users WHERE uname='".$uname."' AND pass='".$pass."'";
</code>```

Title: MySQL connection made but query failing

Body:
Im trying to create a login page.
Connection is successful but query is not fetching the required result.
login page sends data through post method to action_page.php.

Action_page.php

<?php
$servername = "localhost:3306";
$username = "root";
$password = "";
$dbname = "MyDB";

$con = mysqli_connect($servername, $username, $password, $dbname);

// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$uname = $_POST['uname'];
$pass = $_POST['psw'];
$sql = "SELECT * FROM Users WHERE uname=".$uname." AND pass=".$pass;
echo "
$sql
";

//$result = $con->query($sql);

echo var_dump($con->query($sql));

$con->close();

?>

could someone please help.!

Body:
update from

$sql = "SELECT * FROM Users WHERE uname=".$uname." AND pass=".$pass;

to

$sql = "SELECT * FROM Users WHERE uname='".$uname."' AND pass='".$pass."'";


问:
Create device nodes from initramfs on embedded Linux
Linux v2.6.26.5 embedded on device, Squashfs on NAND flash chip. I need mount the root filesystem from busybox shell (initramfs). The old Linux kernel missing fs driver for automatic setup of /dev, not using devtmpfs, so I need to create the basic device nodes manually use mknod (/dev/null, /dev/zero, dev/mtdblock4, ttys). What is correct steps to setup and mount root from a busybox shell based on given details?

Kernel has been loaded, file system have the following structure:

```<code>BusyBox v1.10.2 (2017-08-02 14:07:25 CST) built-in shell (ash)
Enter 'help' for a list of built-in commands.

/bin/sh: can't access tty; job control turned off
# mount -t proc proc /proc
# mount -t sysfs sysfs /sys
# ls -l
drwxrwxr-x    2 1005     1005          432 Aug  2  2017 bin
-rwxr-xr-x    1 1005     1005       715844 Aug  2  2017 cordless_nodect.coma
drwxr-xr-x    2 0        0              32 Aug  2  2017 dev
drwxr-xr-x    2 1005     1005            3 Aug  2  2017 eeprom
drwxr-xr-x    4 1005     1005          386 Aug  2  2017 etc
drwxr-xr-x    2 1005     1005            3 Aug  2  2017 fpar
drwxr-xr-x    4 0        0              48 Aug  2  2017 home
drwxr-xr-x    2 1005     1005            3 Aug  2  2017 hsfw
drwxr-xr-x    3 1005     1005          287 Aug  2  2017 lib
drwxrwxr-x    2 1005     1005            3 Aug  2  2017 mnt
drwxr-xr-x    2 1005     1005            3 Aug  2  2017 nvram
dr-xr-xr-x   27 0        0               0 Jan  1 00:00 proc
lrwxrwxrwx    1 1005     1005            8 Aug  2  2017 root -> tmp/root
drwxr-xr-x    2 1005     1005          642 Aug  2  2017 sbin
drwxr-xr-x   10 0        0               0 Jan  1 00:00 sys
drwxr-xr-x    2 1005     1005            3 Aug  2  2017 tmp
drwxr-xr-x    7 1005     1005           73 Aug  2  2017 usr
lrwxrwxrwx    1 1005     1005            7 Aug  2  2017 var -> tmp/var
drwxr-xr-x    6 1005     1005         4051 Aug  2  2017 www

# mount -t devtmpfs devtmpfs /dev
mount: mounting devtmpfs on /dev failed: No such device
# mount /dev/mtd4 /mnt/root
mount: mounting /dev/mtd4 on /mnt/root failed: No such file or directory
# cat /proc/partitions
major minor  #blocks  name

  31     0        384 mtdblock0
  31     1        128 mtdblock1
  31     2      20352 mtdblock2
  31     3       7168 mtdblock3
  31     4      18816 mtdblock4
  31     5       2048 mtdblock5
  31     6       1024 mtdblock6
  31     7        512 mtdblock7
  31     8        128 mtdblock8
  31     9        512 mtdblock9
  31    10        512 mtdblock10
# cat /proc/filesystems
nodev   sysfs
nodev   rootfs
nodev   bdev
nodev   proc
nodev   debugfs
nodev   sockfs
nodev   pipefs
nodev   anon_inodefs
nodev   tmpfs
nodev   inotifyfs
nodev   configfs
nodev   devpts
    squashfs
nodev   ramfs
nodev   nfs
nodev   jffs2
nodev   mqueue
nodev   rpc_pipefs
# cat /proc/devices
Character devices:
  1 mem
  2 pty
  3 ttyp
  4 /dev/vc/0
  4 tty
  4 ttyS
  5 /dev/tty
  5 /dev/console
  5 /dev/ptmx
  7 vcs
 10 misc
 13 input
 89 i2c
 90 mtd
108 ppp
128 ptm
136 pts
153 spi
204 ttyJ
254 cordless

Block devices:
  1 ramdisk
 31 mtdblock
 93 nftl
</code>```

答: You need to modify fstab file. An step by step example of how to create fstab file from scratch and fill entries to mount is here.</p>

Body:
Linux v2.6.26.5 embedded on device, Squashfs on NAND flash chip. I need mount the root filesystem from busybox shell (initramfs). The old Linux kernel missing fs driver for automatic setup of /dev, not using devtmpfs, so I need to create the basic device nodes manually use mknod (/dev/null, /dev/zero, dev/mtdblock4, ttys). What is correct steps to setup and mount root from a busybox shell based on given details?

Kernel has been loaded, file system have the following structure:

BusyBox v1.10.2 (2017-08-02 14:07:25 CST) built-in shell (ash)
Enter 'help' for a list of built-in commands.

/bin/sh: can't access tty; job control turned off
# mount -t proc proc /proc
# mount -t sysfs sysfs /sys
# ls -l
drwxrwxr-x    2 1005     1005          432 Aug  2  2017 bin
-rwxr-xr-x    1 1005     1005       715844 Aug  2  2017 cordless_nodect.coma
drwxr-xr-x    2 0        0              32 Aug  2  2017 dev
drwxr-xr-x    2 1005     1005            3 Aug  2  2017 eeprom
drwxr-xr-x    4 1005     1005          386 Aug  2  2017 etc
drwxr-xr-x    2 1005     1005            3 Aug  2  2017 fpar
drwxr-xr-x    4 0        0              48 Aug  2  2017 home
drwxr-xr-x    2 1005     1005            3 Aug  2  2017 hsfw
drwxr-xr-x    3 1005     1005          287 Aug  2  2017 lib
drwxrwxr-x    2 1005     1005            3 Aug  2  2017 mnt
drwxr-xr-x    2 1005     1005            3 Aug  2  2017 nvram
dr-xr-xr-x   27 0        0               0 Jan  1 00:00 proc
lrwxrwxrwx    1 1005     1005            8 Aug  2  2017 root -> tmp/root
drwxr-xr-x    2 1005     1005          642 Aug  2  2017 sbin
drwxr-xr-x   10 0        0               0 Jan  1 00:00 sys
drwxr-xr-x    2 1005     1005            3 Aug  2  2017 tmp
drwxr-xr-x    7 1005     1005           73 Aug  2  2017 usr
lrwxrwxrwx    1 1005     1005            7 Aug  2  2017 var -> tmp/var
drwxr-xr-x    6 1005     1005         4051 Aug  2  2017 www

# mount -t devtmpfs devtmpfs /dev
mount: mounting devtmpfs on /dev failed: No such device
# mount /dev/mtd4 /mnt/root
mount: mounting /dev/mtd4 on /mnt/root failed: No such file or directory
# cat /proc/partitions
major minor  #blocks  name

  31     0        384 mtdblock0
  31     1        128 mtdblock1
  31     2      20352 mtdblock2
  31     3       7168 mtdblock3
  31     4      18816 mtdblock4
  31     5       2048 mtdblock5
  31     6       1024 mtdblock6
  31     7        512 mtdblock7
  31     8        128 mtdblock8
  31     9        512 mtdblock9
  31    10        512 mtdblock10
# cat /proc/filesystems
nodev   sysfs
nodev   rootfs
nodev   bdev
nodev   proc
nodev   debugfs
nodev   sockfs
nodev   pipefs
nodev   anon_inodefs
nodev   tmpfs
nodev   inotifyfs
nodev   configfs
nodev   devpts
    squashfs
nodev   ramfs
nodev   nfs
nodev   jffs2
nodev   mqueue
nodev   rpc_pipefs
# cat /proc/devices
Character devices:
  1 mem
  2 pty
  3 ttyp
  4 /dev/vc/0
  4 tty
  4 ttyS
  5 /dev/tty
  5 /dev/console
  5 /dev/ptmx
  7 vcs
 10 misc
 13 input
 89 i2c
 90 mtd
108 ppp
128 ptm
136 pts
153 spi
204 ttyJ
254 cordless

Block devices:
  1 ramdisk
 31 mtdblock
 93 nftl


问:
ImageMagick server requirements
I'm in the process of building a simple website, or to be more precise a simple component for a website that adds a watermark to an image, creates a few different size images, and overlays it onto a few products. These edits will be made every time someone queries an image in a certain directory on the server.

I know this can all be done with imagemagick, my only concern is that the whole website will grind to a halt every time someone views their image for the first time (after the edit's been made once, the database is updated to get the edited version every time a user accesses it).

The website isn't hosted yet, for the time being I'm testing on XAMPP, but I figured for this I'm going to need a virtual or dedicated server, I just need some advice on what sort of hardware specs I ought to be looking at. I doubt more than 2 or 3 people will be viewing photos at any one time, but at a guess I need to be sure that the server can handle up to 10 or so and still be functional.

Hope someone can advise on this, cheers!

答: For Imageprocessing you need some CPU Power. If the Images are large they will also consume memory. But I think you should in any case work with caching. I don't know your application but certainly there are possibilities to cache images which are rendered once into the filesystem. </p>

Title: ImageMagick server requirements


问:
DatePicker not working on bootstrap 4
I want to used datepicker on my project.This is my first time using bootstrap.The problem is that datepicker not displayed when i click the date form.I already try replace CDN url position inside  and inside  tag and still not worked.I dont know what mistake that i make,hope you guys can help me with this problem thank you.</p>

```<code><!DOCTYPE html>
<html lang="en">

<head>
  <!-- Required meta tags -->
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

  <!-- Bootstrap CSS -->
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

  <!-- datepicker -->
  <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  <script>
    $(function() {
      $("#datepicker").datepicker();
    });
  </script>
</head>

<body>
  <nav class="navbar navbar-toggleable-md navbar-inverse bg-inverse">
    <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarsExampleDefault" aria-controls="navbarsExampleDefault" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>
    <a class="navbar-brand" href="#">Menu</a>
    <div class="collapse navbar-collapse" id="navbarsExampleDefault">
      <ul class="navbar-nav mr-auto">
        <li class="nav-item dropdown">
          <a class="nav-link dropdown-toggle" href="http://example.com" id="dropdown01" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Management</a>
          <div class="dropdown-menu" aria-labelledby="dropdown01">
            <a class="dropdown-item" href="dashboard.php?act=create_program">Create Program</a>
            <a class="dropdown-item" href="dashboard.php?act=view_program">View Program</a>
          </div>
        </li>
      </ul>
    </div>
  </nav>
  <div class="container-fluid">
    <div class="row">
      <div class="col-md-4"></div>
      <div class="col-md-4">
        <!-- Datepicker -->
        Date: <input type="text" id="datepicker">
      </div>
      <div class="col-md-4"></div>
    </div>
  </div>
  <!-- jQuery first, then Tether, then Bootstrap JS. -->
  <script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
</body>

</html>
</code>```

答: You are importing jQuery twice (1.12.4 and 3.1.1). Remove v1.12.4 and move the jquery-ui.js to the bottom (after jQuery 3.1.1).</p>

Title: DatePicker not working on bootstrap 4

Body:
I want to used datepicker on my project.This is my first time using bootstrap.The problem is that datepicker not displayed when i click the date form.I already try replace CDN url position inside  and inside  tag and still not worked.I dont know what mistake that i make,hope you guys can help me with this problem thank you.

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

  <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">

    <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarsExampleDefault" aria-controls="navbarsExampleDefault" aria-expanded="false" aria-label="Toggle navigation">

      </button>
    Menu

          Management

            Create Program
            View Program

        Date: <input type="text" id="datepicker">


问:
Calculate the Last day and Hour of the day from Year_Month_Snap String in SQL Server 2014
I am learning SQL Server and am stuck at this conversion issue. Any help is greatly appreciated.

I have a table in SQL Server 2014 with a column Year_Month_Snap which has data in the nvarchar datatype.

I need to obtain the last day and hour of the monthend for 35 consecutive months from 2016 jan.

I see there are many suggestions to snap the fixed day to the YYYY-MM part to make it as YYYY-MM-DD part and convert it to date & datetime, but since the last date of every month varies every month (it may be 30 days month or 31 days or 28/29 days February month) so I need to calculate the last date and hour of the given month from the YYYY-MM nvarchar datatype in the Year_Month_Snap column.

When I try to convert it to the date/datetime, it throws the following error:

Msg 241, Level 16, State 1, Line 25

  Conversion failed when converting date and/or time from character string.

Year_Month_Snap column

Any help is greatly appreciated!!

答:
You can convert your year and month values to DateTime by adding 01 to it. And add 1 month and  subtract 1 hour.

For example for 2017-10 you can obtain 2017-10-31 23:00:00.000 with this.

```<code>SELECT DATEADD(HOUR,-1,DATEADD(MONTH,1, CONVERT(DATETIME, ('2017-10' + '-01') )))
</code>```

your final query.

```<code>SELECT DATEADD(HOUR,-1,DATEADD(MONTH,1, CONVERT(DATETIME, (Year_Month_Snap + '-01') ))) as LastDayAndHourOfMonth
FROM MyTable
</code>```

Body:
You can convert your year and month values to DateTime by adding 01 to it. And add 1 month and  subtract 1 hour.

For example for 2017-10 you can obtain 2017-10-31 23:00:00.000 with this.

SELECT DATEADD(HOUR,-1,DATEADD(MONTH,1, CONVERT(DATETIME, ('2017-10' + '-01') )))

your final query.

SELECT DATEADD(HOUR,-1,DATEADD(MONTH,1, CONVERT(DATETIME, (Year_Month_Snap + '-01') ))) as LastDayAndHourOfMonth
FROM MyTable


问:
Dragging formulas across - Increment columns by more than 1
I can't seem to find anything similar that's already been asked (they all relate to incrementing row numbers rather than columns)

I'm looking to drag a formula across horizontally and have the columns increment by 2

E.g. B1-A1, D1-C1, F1-E1...

Thanks!

答:
You'll need to have a value in cell A1 and B1 for the following to work.

For my testing I put the number 1 in A1 and B1.

Try this in Cell C1:

=IF(MOD(COUNT($A$1:B1),2)=0,COLUMN(B1),IF(B1<>A1,B1,A1))

Here's what you should see when you drag that formula across:

```<code>A B C D E F G H I J K  L  M  N
1 1 2 2 4 4 6 6 8 8 10 10 12 12
</code>```

And this is what the formula does:

The MOD(COUNT() part of the formula counts the cells to the left of it, and if they are a multiple of 2, the value changes.

I've left the value to change to (the 'new' value) as the COLUMN() number for the cell before, just for example's sake. but you can change this part.

The last IF statement at the end checks if the cell before is equal to the cell before that, (eg. Is CELL C1 equal to CELL B1) and if they are not equal, it will give the cell before as a value (the 'copy' value).

Body:
You'll need to have a value in cell A1 and B1 for the following to work.

For my testing I put the number 1 in A1 and B1.

Try this in Cell C1:

=IF(MOD(COUNT($A$1:B1),2)=0,COLUMN(B1),IF(B1<>A1,B1,A1))

Here's what you should see when you drag that formula across:

A B C D E F G H I J K  L  M  N
1 1 2 2 4 4 6 6 8 8 10 10 12 12

And this is what the formula does:

The MOD(COUNT() part of the formula counts the cells to the left of it, and if they are a multiple of 2, the value changes.

I've left the value to change to (the 'new' value) as the COLUMN() number for the cell before, just for example's sake. but you can change this part.

The last IF statement at the end checks if the cell before is equal to the cell before that, (eg. Is CELL C1 equal to CELL B1) and if they are not equal, it will give the cell before as a value (the 'copy' value).


问:
SELECT MAX OF COUNT IN PHPMyadmin
I have a problem with SQLcode

I have a table

id | content | id_user | id_store

```<code>1 |  abc    |  1      | 10
2 |  xzy    |  1      | 10
3 |  abc    |  1      | 10
4 |  abc    |  1      | 11
5 |  abc    |  1      | 12
</code>```

My problem is how i got the result is the count of max (id_store) which is 2* value >= max(id_store)

This is a example, result will be

id_store | count(...)

```<code>10      |   3
because (3*2) > max of count = 3
</code>```

Tks everyone

答:
It's very difficult to understand your question. Try to use the next query

```<code>SELECT id_store,COUNT(*) CountOfStore
FROM `Your Table`
GROUP BY id_store
HAVING 2*COUNT(*) >= (
                        SELECT MAX(CountOfStore) -- max of all CountOfStore
                        FROM
                          (
                            SELECT COUNT(*) CountOfStore -- count of store for each id_store
                            FROM `Your Table`
                            GROUP BY id_store
                          )
                      )
</code>```

Hope I understood you rightly.

Title: SELECT MAX OF COUNT IN PHPMyadmin

Body:
I have a problem with SQLcode

I have a table

id | content | id_user | id_store

1 |  abc    |  1      | 10
2 |  xzy    |  1      | 10
3 |  abc    |  1      | 10
4 |  abc    |  1      | 11
5 |  abc    |  1      | 12

My problem is how i got the result is the count of max (id_store) which is 2* value >= max(id_store)

This is a example, result will be

id_store | count(...)

10      |   3
because (3*2) > max of count = 3

Tks everyone

Body:
It's very difficult to understand your question. Try to use the next query

SELECT id_store,COUNT(*) CountOfStore
FROM `Your Table`
GROUP BY id_store
HAVING 2*COUNT(*) >= (
                        SELECT MAX(CountOfStore) -- max of all CountOfStore
                        FROM
                          (
                            SELECT COUNT(*) CountOfStore -- count of store for each id_store
                            FROM `Your Table`
                            GROUP BY id_store
                          )
                      )

Hope I understood you rightly.


问:
How to functionally convert a nested hash to a list of records?
Let's say I have a nested hash describing money quantities:

```<code>my %money = (coins => {'50c' => 4}, notes => {'10' => 1, '20' => 5});
</code>```

My desired format is a record list:

```<code>my @money = [
  (:type('coins'), :subtype('50c'), value => 4),
  (:type('notes'), :subtype('10'), value => 1),
  (:type('notes'), :subtype('20'), value => 5),
];
</code>```

The most obvious answer is loops:

```<code>my @money;
for %money.kv -> $type, %sub-records {
  for %sub-records.kv -> $subtype, $value {
    @money.push: (:$type, :$subtype, :$value);
  }
}
</code>```

But I'm allergic to separating a variable from the code that populates it. Next, I tried to create the variable with functional transformations on the input hash:

```<code>%money.kv.map: -> $k1, %hsh2 { :type($k1) X, %hsh2.kv.map(->$k2, $v2 {:subtype($k2), :$v2, :value($v2)}) }
</code>```

But I didn't get the nesting right. I want a list of flat lists. Plus, the above is a mess to read.

The compromise is the gather/take construct which lets me construct a list by iteration without any temporary/uninitialized junk in the main scope:

```<code>my @money = gather for %money.kv -> $type, %sub-records {
  for %sub-records.kv -> $subtype, $value {
    take (:$type, :$subtype, :$value);
  }
};
</code>```

But I'm curious, what is the right way to get this right with just list transformations like map, X or Z, and flat? ("key1", "key2", and "value" are fine field names, since an algorithm shouldn't be domain specific.)

Edit: I should mention that in Perl 6, gather/take is the most readable solution (best for code that's not write-only). I'm still curious about the pure functional solution.

答:
my @money = %money.map:
-> ( :key($type), :value(%records) ) {
  slip

      :$type xx *
    Z
      ( 'subtype' X=> %records.keys   )
    Z
      (   'value' X=> %records.values )
}
```

<p>You could do <code>.kv.map: -> $type, %records {…}</code></p>

<hr>

<ul>
<li><code>-> ( :key($type), :value(%records) ) {…}</code> destructures a Pair object</li>
<li><code>:$type</code> creates a <code>type => $type</code> Pair</li>
<li><code>:$type xx *</code> repeats <code>:$type</code> infinitely (<code>Z</code> stops when any of it's inputs stops)</li>
<li><code>('subtype' X=> %records.keys)</code> creates a list of Pairs<br>
(Note that <code>.keys</code> and <code>.values</code> are in the same order if you don't modify the Hash between the calls)</li>
<li><code>Z</code> zips two lists</li>
<li><code>slip</code> causes the elements of the sequence to slip into the outer sequence<br>
(<code>flat</code> would flatten too much)</li>
</ul>

<hr>

<p>If you wanted them to be sorted</p>

<pre class="lang-perl6 prettyprint-override"><code>my @money = %money.sort.map: # 'coins' sorts before 'notes'
-> ( :key($type), :value(%records) ) {

  # sort by the numeric part of the key
  my @sorted = %records.sort( +*.key.match(/^\d+/) );

  slip

      :$type xx *
    Z
      ( 'subtype' X=> @sorted».key   )
    Z
      (   'value' X=> @sorted».value )
}
</code>```

You could do .sort».kv.map: -> ($type, %records) {…}

Body:
Let's say I have a nested hash describing money quantities:

my %money = (coins => {'50c' => 4}, notes => {'10' => 1, '20' => 5});

My desired format is a record list:

my @money = [
  (:type('coins'), :subtype('50c'), value => 4),
  (:type('notes'), :subtype('10'), value => 1),
  (:type('notes'), :subtype('20'), value => 5),
];

The most obvious answer is loops:

my @money;
for %money.kv -> $type, %sub-records {
  for %sub-records.kv -> $subtype, $value {
    @money.push: (:$type, :$subtype, :$value);
  }
}

But I'm allergic to separating a variable from the code that populates it. Next, I tried to create the variable with functional transformations on the input hash:

%money.kv.map: -> $k1, %hsh2 { :type($k1) X, %hsh2.kv.map(->$k2, $v2 {:subtype($k2), :$v2, :value($v2)}) }

But I didn't get the nesting right. I want a list of flat lists. Plus, the above is a mess to read.

The compromise is the gather/take construct which lets me construct a list by iteration without any temporary/uninitialized junk in the main scope:

my @money = gather for %money.kv -> $type, %sub-records {
  for %sub-records.kv -> $subtype, $value {
    take (:$type, :$subtype, :$value);
  }
};

But I'm curious, what is the right way to get this right with just list transformations like map, X or Z, and flat? ("key1", "key2", and "value" are fine field names, since an algorithm shouldn't be domain specific.)

Edit: I should mention that in Perl 6, gather/take is the most readable solution (best for code that's not write-only). I'm still curious about the pure functional solution.

Body:
my @money = %money.map:
-> ( :key($type), :value(%records) ) {
  slip

      :$type xx *
    Z
      ( 'subtype' X=> %records.keys   )
    Z
      (   'value' X=> %records.values )
}

You could do .kv.map: -> $type, %records {…}

-> ( :key($type), :value(%records) ) {…} destructures a Pair object

:$type creates a type => $type Pair

:$type xx * repeats :$type infinitely (Z stops when any of it's inputs stops)

('subtype' X=> %records.keys) creates a list of Pairs

(Note that .keys and .values are in the same order if you don't modify the Hash between the calls)

Z zips two lists

slip causes the elements of the sequence to slip into the outer sequence

(flat would flatten too much)

If you wanted them to be sorted

my @money = %money.sort.map: # 'coins' sorts before 'notes'
-> ( :key($type), :value(%records) ) {

  # sort by the numeric part of the key
  my @sorted = %records.sort( +*.key.match(/^\d+/) );

  slip

      :$type xx *
    Z
      ( 'subtype' X=> @sorted».key   )
    Z
      (   'value' X=> @sorted».value )
}

You could do .sort».kv.map: -> ($type, %records) {…}