问:
How to make horizontally scroll view pager
I want to make horizontally infinite viewpager, which scroll continue both side left and right.

Anyone have idea then please let me know.

答:
I have implement these all classes below please check it and let me know if any one have any new idea.</p>

```<code>1. Make **HorizontalInfiniteCycleViewPager** class.
package com.test.HorizontalInfiniteCycleViewPager;

import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Interpolator;

/**
 * Created by GIGAMOLE on 7/27/16.
 */
public class HorizontalInfiniteCycleViewPager extends ViewPager implements ViewPageable {

    private InfiniteCycleManager mInfiniteCycleManager;

    public HorizontalInfiniteCycleViewPager(final Context context) {
        super(context);
        init(context, null);
    }

    public HorizontalInfiniteCycleViewPager(final Context context, final AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    private void init(final Context context, final AttributeSet attributeSet) {
        mInfiniteCycleManager = new InfiniteCycleManager(context, this, attributeSet);
    }

    public float getMinPageScaleOffset() {
        return mInfiniteCycleManager == null ? 0.0F : mInfiniteCycleManager.getMinPageScaleOffset();
    }

    public void setMinPageScaleOffset(final float minPageScaleOffset) {
        if (mInfiniteCycleManager != null)
            mInfiniteCycleManager.setMinPageScaleOffset(minPageScaleOffset);
    }

    public float getCenterPageScaleOffset() {
        return mInfiniteCycleManager == null ? 0.0F : mInfiniteCycleManager.getCenterPageScaleOffset();
    }

    public void setCenterPageScaleOffset(final float centerPageScaleOffset) {
        if (mInfiniteCycleManager != null)
            mInfiniteCycleManager.setCenterPageScaleOffset(centerPageScaleOffset);
    }

    public float getMinPageScale() {
        return mInfiniteCycleManager == null ? 0.0F : mInfiniteCycleManager.getMinPageScale();
    }

    public void setMinPageScale(final float minPageScale) {
        if (mInfiniteCycleManager != null) mInfiniteCycleManager.setMinPageScale(minPageScale);
    }

    public float getMaxPageScale() {
        return mInfiniteCycleManager == null ? 0.0F : mInfiniteCycleManager.getMaxPageScale();
    }

    public void setMaxPageScale(final float maxPageScale) {
        if (mInfiniteCycleManager != null) mInfiniteCycleManager.setMaxPageScale(maxPageScale);
    }

    public boolean isMediumScaled() {
        return mInfiniteCycleManager != null && mInfiniteCycleManager.isMediumScaled();
    }

    public void setMediumScaled(final boolean mediumScaled) {
        if (mInfiniteCycleManager != null) mInfiniteCycleManager.setMediumScaled(mediumScaled);
    }

    public int getScrollDuration() {
        return mInfiniteCycleManager == null ? 0 : mInfiniteCycleManager.getScrollDuration();
    }

    public void setScrollDuration(final int scrollDuration) {
        if (mInfiniteCycleManager != null) mInfiniteCycleManager.setScrollDuration(scrollDuration);
    }

    public Interpolator getInterpolator() {
        return mInfiniteCycleManager == null ? null : mInfiniteCycleManager.getInterpolator();
    }

    public void setInterpolator(final Interpolator interpolator) {
        if (mInfiniteCycleManager != null) mInfiniteCycleManager.setInterpolator(interpolator);
    }

    public boolean isVertical() {
        return mInfiniteCycleManager != null && mInfiniteCycleManager.isVertical();
    }

    public OnInfiniteCyclePageTransformListener getOnInfiniteCyclePageTransformListener() {
        return mInfiniteCycleManager == null ?
                null : mInfiniteCycleManager.getOnInfiniteCyclePageTransformListener();
    }

    public void setOnInfiniteCyclePageTransformListener(
            final OnInfiniteCyclePageTransformListener onInfiniteCyclePageTransformListener
    ) {
        if (mInfiniteCycleManager != null)
            mInfiniteCycleManager.setOnInfiniteCyclePageTransformListener(onInfiniteCyclePageTransformListener);
    }

    @Override
    public void setPageTransformer(final boolean reverseDrawingOrder, final PageTransformer transformer) {
        super.setPageTransformer(
                false, mInfiniteCycleManager == null ?
                        transformer : mInfiniteCycleManager.getInfinityCyclePageTransformer()
        );
    }

    @Override
    protected void setChildrenDrawingOrderEnabled(final boolean enabled) {
        super.setChildrenDrawingOrderEnabled(InfiniteCycleManager.DEFAULT_DISABLE_FLAG);
    }

    @Override
    public void setClipChildren(final boolean clipChildren) {
        super.setClipChildren(InfiniteCycleManager.DEFAULT_DISABLE_FLAG);
    }

    @Override
    public void setDrawingCacheEnabled(final boolean enabled) {
        super.setDrawingCacheEnabled(InfiniteCycleManager.DEFAULT_DISABLE_FLAG);
    }

    @Override
    protected void setChildrenDrawingCacheEnabled(final boolean enabled) {
        super.setChildrenDrawingCacheEnabled(InfiniteCycleManager.DEFAULT_DISABLE_FLAG);
    }

    @Override
    public void setWillNotCacheDrawing(final boolean willNotCacheDrawing) {
        super.setWillNotCacheDrawing(InfiniteCycleManager.DEFAULT_ENABLE_FLAG);
    }

    @Override
    public void setPageMargin(final int marginPixels) {
        super.setPageMargin(InfiniteCycleManager.DEFAULT_PAGE_MARGIN);
    }

    @Override
    public void setOffscreenPageLimit(final int limit) {
        super.setOffscreenPageLimit(InfiniteCycleManager.DEFAULT_OFFSCREEN_PAGE_LIMIT);
    }

    @Override
    public void setOverScrollMode(final int overScrollMode) {
        super.setOverScrollMode(OVER_SCROLL_NEVER);
    }

    @Override
    protected boolean addViewInLayout(final View child, final int index, final ViewGroup.LayoutParams params) {
        return super.addViewInLayout(child, 0, params);
    }

    @Override
    public void addView(final View child, final int index, final ViewGroup.LayoutParams params) {
        super.addView(child, 0, params);
    }

    @Override
    public void setAdapter(final PagerAdapter adapter) {
        if (mInfiniteCycleManager == null) super.setAdapter(adapter);
        else {
            super.setAdapter(mInfiniteCycleManager.setAdapter(adapter));
            mInfiniteCycleManager.resetPager();
        }
    }

    @Override
    public PagerAdapter getAdapter() {
        if (mInfiniteCycleManager == null) return super.getAdapter();
        return mInfiniteCycleManager.getInfiniteCyclePagerAdapter() == null ? super.getAdapter() :
                mInfiniteCycleManager.getInfiniteCyclePagerAdapter().getPagerAdapter();
    }

    @Override
    public boolean onTouchEvent(final MotionEvent ev) {
        try {
            return mInfiniteCycleManager == null ? super.onTouchEvent(ev) :
                    mInfiniteCycleManager.onTouchEvent(ev) && super.onTouchEvent(ev);
        } catch (IllegalArgumentException e) {
            return true;
        }
    }

    @Override
    public boolean onInterceptTouchEvent(final MotionEvent ev) {
        try {
            return mInfiniteCycleManager == null ? super.onInterceptTouchEvent(ev) :
                    mInfiniteCycleManager.onInterceptTouchEvent(ev) && super.onInterceptTouchEvent(ev);
        } catch (IllegalArgumentException e) {
            return true;
        }
    }

    @Override
    public void onWindowFocusChanged(final boolean hasWindowFocus) {
        if (mInfiniteCycleManager != null)
            mInfiniteCycleManager.onWindowFocusChanged(hasWindowFocus);
        super.onWindowFocusChanged(hasWindowFocus);
    }

    @Override
    protected void onDetachedFromWindow() {
        if (mInfiniteCycleManager != null) mInfiniteCycleManager.stopAutoScroll();
        super.onDetachedFromWindow();
    }

    @Override
    public void setCurrentItem(final int item) {
        setCurrentItem(item, true);
    }

    @Override
    public void setCurrentItem(final int item, final boolean smoothScroll) {
        if (mInfiniteCycleManager != null)
            super.setCurrentItem(mInfiniteCycleManager.setCurrentItem(item), true);
    }

    public int getRealItem() {
        return mInfiniteCycleManager == null ?
                getCurrentItem() : mInfiniteCycleManager.getRealItem();
    }

    public int getState() {
        return mInfiniteCycleManager == null ?
                ViewPager.SCROLL_STATE_IDLE : mInfiniteCycleManager.getState();
    }

    public void notifyDataSetChanged() {
        if (mInfiniteCycleManager != null) mInfiniteCycleManager.notifyDataSetChanged();
    }

    public void invalidateTransformer() {
        if (mInfiniteCycleManager != null) mInfiniteCycleManager.invalidateTransformer();
    }

    public void postInvalidateTransformer() {
        if (mInfiniteCycleManager != null) mInfiniteCycleManager.postInvalidateTransformer();
    }

    public void startAutoScroll(final boolean isAutoScrollPositive) {
        if (mInfiniteCycleManager != null) mInfiniteCycleManager.startAutoScroll(isAutoScrollPositive);
    }

    public void stopAutoScroll() {
        if (mInfiniteCycleManager != null) mInfiniteCycleManager.stopAutoScroll();
    }
}
</code>```

Body:
I have implement these all classes below please check it and let me know if any one have any new idea.

1. Make **HorizontalInfiniteCycleViewPager** class.
package com.test.HorizontalInfiniteCycleViewPager;

import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Interpolator;

/**
 * Created by GIGAMOLE on 7/27/16.
 */
public class HorizontalInfiniteCycleViewPager extends ViewPager implements ViewPageable {

    private InfiniteCycleManager mInfiniteCycleManager;

    public HorizontalInfiniteCycleViewPager(final Context context) {
        super(context);
        init(context, null);
    }

    public HorizontalInfiniteCycleViewPager(final Context context, final AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    private void init(final Context context, final AttributeSet attributeSet) {
        mInfiniteCycleManager = new InfiniteCycleManager(context, this, attributeSet);
    }

    public float getMinPageScaleOffset() {
        return mInfiniteCycleManager == null ? 0.0F : mInfiniteCycleManager.getMinPageScaleOffset();
    }

    public void setMinPageScaleOffset(final float minPageScaleOffset) {
        if (mInfiniteCycleManager != null)
            mInfiniteCycleManager.setMinPageScaleOffset(minPageScaleOffset);
    }

    public float getCenterPageScaleOffset() {
        return mInfiniteCycleManager == null ? 0.0F : mInfiniteCycleManager.getCenterPageScaleOffset();
    }

    public void setCenterPageScaleOffset(final float centerPageScaleOffset) {
        if (mInfiniteCycleManager != null)
            mInfiniteCycleManager.setCenterPageScaleOffset(centerPageScaleOffset);
    }

    public float getMinPageScale() {
        return mInfiniteCycleManager == null ? 0.0F : mInfiniteCycleManager.getMinPageScale();
    }

    public void setMinPageScale(final float minPageScale) {
        if (mInfiniteCycleManager != null) mInfiniteCycleManager.setMinPageScale(minPageScale);
    }

    public float getMaxPageScale() {
        return mInfiniteCycleManager == null ? 0.0F : mInfiniteCycleManager.getMaxPageScale();
    }

    public void setMaxPageScale(final float maxPageScale) {
        if (mInfiniteCycleManager != null) mInfiniteCycleManager.setMaxPageScale(maxPageScale);
    }

    public boolean isMediumScaled() {
        return mInfiniteCycleManager != null && mInfiniteCycleManager.isMediumScaled();
    }

    public void setMediumScaled(final boolean mediumScaled) {
        if (mInfiniteCycleManager != null) mInfiniteCycleManager.setMediumScaled(mediumScaled);
    }

    public int getScrollDuration() {
        return mInfiniteCycleManager == null ? 0 : mInfiniteCycleManager.getScrollDuration();
    }

    public void setScrollDuration(final int scrollDuration) {
        if (mInfiniteCycleManager != null) mInfiniteCycleManager.setScrollDuration(scrollDuration);
    }

    public Interpolator getInterpolator() {
        return mInfiniteCycleManager == null ? null : mInfiniteCycleManager.getInterpolator();
    }

    public void setInterpolator(final Interpolator interpolator) {
        if (mInfiniteCycleManager != null) mInfiniteCycleManager.setInterpolator(interpolator);
    }

    public boolean isVertical() {
        return mInfiniteCycleManager != null && mInfiniteCycleManager.isVertical();
    }

    public OnInfiniteCyclePageTransformListener getOnInfiniteCyclePageTransformListener() {
        return mInfiniteCycleManager == null ?
                null : mInfiniteCycleManager.getOnInfiniteCyclePageTransformListener();
    }

    public void setOnInfiniteCyclePageTransformListener(
            final OnInfiniteCyclePageTransformListener onInfiniteCyclePageTransformListener
    ) {
        if (mInfiniteCycleManager != null)
            mInfiniteCycleManager.setOnInfiniteCyclePageTransformListener(onInfiniteCyclePageTransformListener);
    }

    @Override
    public void setPageTransformer(final boolean reverseDrawingOrder, final PageTransformer transformer) {
        super.setPageTransformer(
                false, mInfiniteCycleManager == null ?
                        transformer : mInfiniteCycleManager.getInfinityCyclePageTransformer()
        );
    }

    @Override
    protected void setChildrenDrawingOrderEnabled(final boolean enabled) {
        super.setChildrenDrawingOrderEnabled(InfiniteCycleManager.DEFAULT_DISABLE_FLAG);
    }

    @Override
    public void setClipChildren(final boolean clipChildren) {
        super.setClipChildren(InfiniteCycleManager.DEFAULT_DISABLE_FLAG);
    }

    @Override
    public void setDrawingCacheEnabled(final boolean enabled) {
        super.setDrawingCacheEnabled(InfiniteCycleManager.DEFAULT_DISABLE_FLAG);
    }

    @Override
    protected void setChildrenDrawingCacheEnabled(final boolean enabled) {
        super.setChildrenDrawingCacheEnabled(InfiniteCycleManager.DEFAULT_DISABLE_FLAG);
    }

    @Override
    public void setWillNotCacheDrawing(final boolean willNotCacheDrawing) {
        super.setWillNotCacheDrawing(InfiniteCycleManager.DEFAULT_ENABLE_FLAG);
    }

    @Override
    public void setPageMargin(final int marginPixels) {
        super.setPageMargin(InfiniteCycleManager.DEFAULT_PAGE_MARGIN);
    }

    @Override
    public void setOffscreenPageLimit(final int limit) {
        super.setOffscreenPageLimit(InfiniteCycleManager.DEFAULT_OFFSCREEN_PAGE_LIMIT);
    }

    @Override
    public void setOverScrollMode(final int overScrollMode) {
        super.setOverScrollMode(OVER_SCROLL_NEVER);
    }

    @Override
    protected boolean addViewInLayout(final View child, final int index, final ViewGroup.LayoutParams params) {
        return super.addViewInLayout(child, 0, params);
    }

    @Override
    public void addView(final View child, final int index, final ViewGroup.LayoutParams params) {
        super.addView(child, 0, params);
    }

    @Override
    public void setAdapter(final PagerAdapter adapter) {
        if (mInfiniteCycleManager == null) super.setAdapter(adapter);
        else {
            super.setAdapter(mInfiniteCycleManager.setAdapter(adapter));
            mInfiniteCycleManager.resetPager();
        }
    }

    @Override
    public PagerAdapter getAdapter() {
        if (mInfiniteCycleManager == null) return super.getAdapter();
        return mInfiniteCycleManager.getInfiniteCyclePagerAdapter() == null ? super.getAdapter() :
                mInfiniteCycleManager.getInfiniteCyclePagerAdapter().getPagerAdapter();
    }

    @Override
    public boolean onTouchEvent(final MotionEvent ev) {
        try {
            return mInfiniteCycleManager == null ? super.onTouchEvent(ev) :
                    mInfiniteCycleManager.onTouchEvent(ev) && super.onTouchEvent(ev);
        } catch (IllegalArgumentException e) {
            return true;
        }
    }

    @Override
    public boolean onInterceptTouchEvent(final MotionEvent ev) {
        try {
            return mInfiniteCycleManager == null ? super.onInterceptTouchEvent(ev) :
                    mInfiniteCycleManager.onInterceptTouchEvent(ev) && super.onInterceptTouchEvent(ev);
        } catch (IllegalArgumentException e) {
            return true;
        }
    }

    @Override
    public void onWindowFocusChanged(final boolean hasWindowFocus) {
        if (mInfiniteCycleManager != null)
            mInfiniteCycleManager.onWindowFocusChanged(hasWindowFocus);
        super.onWindowFocusChanged(hasWindowFocus);
    }

    @Override
    protected void onDetachedFromWindow() {
        if (mInfiniteCycleManager != null) mInfiniteCycleManager.stopAutoScroll();
        super.onDetachedFromWindow();
    }

    @Override
    public void setCurrentItem(final int item) {
        setCurrentItem(item, true);
    }

    @Override
    public void setCurrentItem(final int item, final boolean smoothScroll) {
        if (mInfiniteCycleManager != null)
            super.setCurrentItem(mInfiniteCycleManager.setCurrentItem(item), true);
    }

    public int getRealItem() {
        return mInfiniteCycleManager == null ?
                getCurrentItem() : mInfiniteCycleManager.getRealItem();
    }

    public int getState() {
        return mInfiniteCycleManager == null ?
                ViewPager.SCROLL_STATE_IDLE : mInfiniteCycleManager.getState();
    }

    public void notifyDataSetChanged() {
        if (mInfiniteCycleManager != null) mInfiniteCycleManager.notifyDataSetChanged();
    }

    public void invalidateTransformer() {
        if (mInfiniteCycleManager != null) mInfiniteCycleManager.invalidateTransformer();
    }

    public void postInvalidateTransformer() {
        if (mInfiniteCycleManager != null) mInfiniteCycleManager.postInvalidateTransformer();
    }

    public void startAutoScroll(final boolean isAutoScrollPositive) {
        if (mInfiniteCycleManager != null) mInfiniteCycleManager.startAutoScroll(isAutoScrollPositive);
    }

    public void stopAutoScroll() {
        if (mInfiniteCycleManager != null) mInfiniteCycleManager.stopAutoScroll();
    }
}


来源: stackexchange

问:
Difference between getMap() and getMapAsync()
I am using getMapAsync() instead of getMap() in mapview.But, I wish to know the difference between getMap() and getMapAsync.

答: getMapAsync let you use a callback when the map is init ;)</p>

ContentLicense: CC BY-SA 3.0


问:
Dynamic values in json parsing with GWT
I have a json response like this

```<code>{
   "columns":[
      "a",
      "b",
      "c"
   ],
   "data":[{
      "a":"some value",
      "b":"some value",
      "c":"some value"
   },
   {
      "a":"some value 2",
      "b":"some value 2",
      "c":"some value 2"
   }
   ]
}
</code>```

Now here whatever values columns have the same values are used as keys in data object. I have to parse this json in GWT client side. As far as I know JSNI requires fixed json objects. Is there any way to parse this?

答:
After fiddling with it here's how I did it.</p>

```<code>public final native JsArray<Columns> getColumns() /*-{ return this.columns; }-*/;
public final native JsArray<Data> getData() /*-{ return this.data; }-*/;

public static class Data extends JavaScriptObject {
    protected Data() {}

    public final native String getValue(String key) /*-{ return this[key]; }-*/;
}
public static class Columns extends JavaScriptObject {
    protected Columns() {}
    public final native String getValue() /*-{ return this; }-*/;
}
</code>```

Title: Dynamic values in json parsing with GWT

Body:
I have a json response like this

{
   "columns":[
      "a",
      "b",
      "c"
   ],
   "data":[{
      "a":"some value",
      "b":"some value",
      "c":"some value"
   },
   {
      "a":"some value 2",
      "b":"some value 2",
      "c":"some value 2"
   }
   ]
}

Now here whatever values columns have the same values are used as keys in data object. I have to parse this json in GWT client side. As far as I know JSNI requires fixed json objects. Is there any way to parse this?

Body:
After fiddling with it here's how I did it.

public final native JsArray<Columns> getColumns() /*-{ return this.columns; }-*/;
public final native JsArray<Data> getData() /*-{ return this.data; }-*/;

public static class Data extends JavaScriptObject {
    protected Data() {}

    public final native String getValue(String key) /*-{ return this[key]; }-*/;
}
public static class Columns extends JavaScriptObject {
    protected Columns() {}
    public final native String getValue() /*-{ return this; }-*/;
}


问:
Despite rpath is set, one dll is not found
ldd fail to find a dll, that is present in the rpath definition. Some others libraries are found (check /./../lib/*)

Here the output of ldd (we can see that 2 dll are found in ../lib, but not libexpat.so.0:

root@hyperstream:/DT/local/ADE-trunk4/build-ADE-Desktop-Default/bin#
  ldd ./ade_admin   linux-vdso.so.1 =>  (0x00007ffeb9796000)
    libadeversion.so =>
  /DT/local/ADE-trunk4/build-ADE-Desktop-Default/bin/./../lib/libadeversion.so
  (0x00007f31abaef000)  libuuid.so.1 =>
  /lib/x86_64-linux-gnu/libuuid.so.1 (0x00007f31ab8ca000)
    libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0
  (0x00007f31ab6ac000)  libaprutil-1.so.0 =>
  /DT/local/ADE-trunk4/build-ADE-Desktop-Default/bin/./../lib/libaprutil-1.so.0
  (0x00007f31ab58c000)  libapr-1.so.0 =>
  /DT/local/ADE-trunk4/build-ADE-Desktop-Default/bin/./../lib/libapr-1.so.0
  (0x00007f31ab460000)  libavahi-client.so.3 =>
  /usr/lib/x86_64-linux-gnu/libavahi-client.so.3 (0x00007f31ab24d000)
    libavahi-common.so.3 =>
  /usr/lib/x86_64-linux-gnu/libavahi-common.so.3 (0x00007f31ab041000)
    libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007f31aae3d000)
    libstdc++.so.6 => /usr/lib/x86_64-linux-gnu/libstdc++.so.6
  (0x00007f31aaab5000)  libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6
  (0x00007f31aa7ac000)  libgcc_s.so.1 =>
  /lib/x86_64-linux-gnu/libgcc_s.so.1 (0x00007f31aa595000)  libc.so.6 =>
  /lib/x86_64-linux-gnu/libc.so.6 (0x00007f31aa1cc000)
    /lib64/ld-linux-x86-64.so.2 (0x0000560d30a76000)    libexpat.so.0 =>
  not found   librt.so.1 => /lib/x86_64-linux-gnu/librt.so.1
  (0x00007f31a9fc4000) [...]

root@hyperstream:/DT/local/ADE-trunk4/build-ADE-Desktop-Default/bin#
  file ../lib/libexpat.so.0  ../lib/libexpat.so.0: ELF 64-bit LSB shared
  object, x86-64, version 1 (SYSV), dynamically linked,
  BuildID[sha1]=762de704943d03033d01a9725216d6b05d0740f5, not stripped

Here the rpath:

root@hyperstream:/DT/local/ADE-trunk4/build-ADE-Desktop-Default/bin#
  readelf -d ade_admin | grep 'R.*PATH' 16: 0x000000000000001d (RUNPATH)
  Library runpath: [${ORIGIN}/../lib]

Now the killer fact: It's works with clang 3.8, but fail with gcc 6.3 (ubuntu 16.10)

Obviously adding an LD_LIBRARY_PATH=../lib make it works again, but the goal of rpath was to avoid to set it

root@hyperstream:/DT/local/ADE-trunk4/build-ADE-Desktop-Default/bin#
  export LD_LIBRARY_PATH=../lib
  root@hyperstream:/DT/local/ADE-trunk4/build-ADE-Desktop-Default/bin#
  ldd ./ade_admin   linux-vdso.so.1 =>  (0x00007ffea23b6000)
    libadeversion.so => ../lib/libadeversion.so (0x00007f78c6474000)
    libuuid.so.1 => /lib/x86_64-linux-gnu/libuuid.so.1
  (0x00007f78c624f000)  libpthread.so.0 =>
  /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007f78c6031000)
    libaprutil-1.so.0 => ../lib/libaprutil-1.so.0 (0x00007f78c5f11000)
    libapr-1.so.0 => ../lib/libapr-1.so.0 (0x00007f78c5de5000)
    libavahi-client.so.3 =>
  /usr/lib/x86_64-linux-gnu/libavahi-client.so.3 (0x00007f78c5bd2000)
    libavahi-common.so.3 =>
  /usr/lib/x86_64-linux-gnu/libavahi-common.so.3 (0x00007f78c59c6000)
    libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007f78c57c2000)
    libstdc++.so.6 => /usr/lib/x86_64-linux-gnu/libstdc++.so.6
  (0x00007f78c543a000)  libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6
  (0x00007f78c5131000)  libgcc_s.so.1 =>
  /lib/x86_64-linux-gnu/libgcc_s.so.1 (0x00007f78c4f1a000)  libc.so.6 =>
  /lib/x86_64-linux-gnu/libc.so.6 (0x00007f78c4b51000)
    /lib64/ld-linux-x86-64.so.2 (0x0000559fdceab000)    libexpat.so.0 =>
  ../lib/libexpat.so.0 (0x00007f78c492a000)

Any idea ?

Regards

Laurent

答:
I just find the explanation: clang put in the [NEEDED] section of the elf binary ALL libraries (even libraries not explicitely included by myself, but referenced by the [NEEDED] section of the library that I include

example from gcc:

```<code>readelf -d my_prog

Dynamic section at offset 0x9cb548 contains 46 entries:
  Tag        Type                         Name/Value
 0x0000000000000001 (NEEDED)             Shared library: [libadeversion.so]
 0x0000000000000001 (NEEDED)             Shared library: [libuuid.so.1]
 0x0000000000000001 (NEEDED)             Shared library: [libsqlite3.so]
 0x0000000000000001 (NEEDED)             Shared library: [libpthread.so.0]
 0x0000000000000001 (NEEDED)             Shared library: [libaprutil-1.so.0]
 0x0000000000000001 (NEEDED)             Shared library: [libapr-1.so.0]
 0x0000000000000001 (NEEDED)             Shared library: [libavahi-client.so.3]
 0x0000000000000001 (NEEDED)             Shared library: [libavahi-common.so.3]
 0x0000000000000001 (NEEDED)             Shared library: [libdl.so.2]
 0x0000000000000001 (NEEDED)             Shared library: [libaio.so.1]
 0x0000000000000001 (NEEDED)             Shared library: [librt.so.1]
 0x0000000000000001 (NEEDED)             Shared library: [lib_adm64.so]
 0x0000000000000001 (NEEDED)             Shared library: [lib_dict64.so]
 0x0000000000000001 (NEEDED)             Shared library: [lib_rdm64.so]
 0x0000000000000001 (NEEDED)             Shared library: [lib_dbr64.so]
 0x0000000000000001 (NEEDED)             Shared library: [libstdc++.so.6]
 0x0000000000000001 (NEEDED)             Shared library: [libm.so.6]
 0x0000000000000001 (NEEDED)             Shared library: [libgcc_s.so.1]
 0x0000000000000001 (NEEDED)             Shared library: [libc.so.6]
 0x000000000000001d (RUNPATH)            Library runpath: [${ORIGIN}/../lib/:$ORIGIN/../lib/:../lib/]
</code>```

from clang:

```<code>readelf -d my_prog

Dynamic section at offset 0xa7bae8 contains 54 entries:
  Tag        Type                         Name/Value
 0x0000000000000001 (NEEDED)             Shared library: [libadeversion.so]
 0x0000000000000001 (NEEDED)             Shared library: [libuuid.so.1]
 0x0000000000000001 (NEEDED)             Shared library: [libsqlite3.so]
 0x0000000000000001 (NEEDED)             Shared library: [libpthread.so.0]
 0x0000000000000001 (NEEDED)             Shared library: [libaprutil-1.so.0]
 0x0000000000000001 (NEEDED)             Shared library: [libexpat.so.0]
 0x0000000000000001 (NEEDED)             Shared library: [libapr-1.so.0]
 0x0000000000000001 (NEEDED)             Shared library: [libavahi-client.so.3]
 0x0000000000000001 (NEEDED)             Shared library: [libavahi-common.so.3]
 0x0000000000000001 (NEEDED)             Shared library: [libdl.so.2]
 0x0000000000000001 (NEEDED)             Shared library: [libaio.so.1]
 0x0000000000000001 (NEEDED)             Shared library: [libcrypt.so.1]
 0x0000000000000001 (NEEDED)             Shared library: [librt.so.1]
 0x0000000000000001 (NEEDED)             Shared library: [lib_adm64.so]
 0x0000000000000001 (NEEDED)             Shared library: [lib_dict64.so]
 0x0000000000000001 (NEEDED)             Shared library: [lib_rdm64.so]
 0x0000000000000001 (NEEDED)             Shared library: [lib_rpc64.so]
 0x0000000000000001 (NEEDED)             Shared library: [lib_sql64.so]
 0x0000000000000001 (NEEDED)             Shared library: [lib_rdbc64.so]
 0x0000000000000001 (NEEDED)             Shared library: [lib_rm64.so]
 0x0000000000000001 (NEEDED)             Shared library: [lib_ncp64.so]
 0x0000000000000001 (NEEDED)             Shared library: [lib_cmp64.so]
 0x0000000000000001 (NEEDED)             Shared library: [lib_repfltr64.so]
 0x0000000000000001 (NEEDED)             Shared library: [lib_expat64.so]
 0x0000000000000001 (NEEDED)             Shared library: [lib_cncp64.so]
 0x0000000000000001 (NEEDED)             Shared library: [lib_dbr64.so]
 0x0000000000000001 (NEEDED)             Shared library: [libstdc++.so.6]
 0x0000000000000001 (NEEDED)             Shared library: [libm.so.6]
 0x0000000000000001 (NEEDED)             Shared library: [libgcc_s.so.1]
 0x0000000000000001 (NEEDED)             Shared library: [libc.so.6]
 0x000000000000001d (RUNPATH)            Library runpath: [${ORIGIN}/../lib/:$ORIGIN/../lib/:../lib/]
</code>```

And one dll include the missing one libexpat:

```<code>readelf -d ../lib/libaprutil-1.so.0

Dynamic section at offset 0x1e698 contains 29 entries:
  Tag        Type                         Name/Value
 0x0000000000000001 (NEEDED)             Shared library: **[libexpat.so.0]**
 0x0000000000000001 (NEEDED)             Shared library: [libapr-1.so.0]
 0x0000000000000001 (NEEDED)             Shared library: [libuuid.so.1]
 0x0000000000000001 (NEEDED)             Shared library: [librt.so.1]
 0x0000000000000001 (NEEDED)             Shared library: [libcrypt.so.1]
 0x0000000000000001 (NEEDED)             Shared library: [libpthread.so.0]
 0x0000000000000001 (NEEDED)             Shared library: [libdl.so.2]
 0x0000000000000001 (NEEDED)             Shared library: [libc.so.6]
 0x000000000000000e (SONAME)             Library soname: [libaprutil-1.so.0]
</code>```

but RUNPATH is only used by the binary not by the dll (that can have is own RUNPATH too).

2 solutions:
- add a RUNPATH in libaprutil-1.so.0 to force to include library from "."
- add explicitely all missing dll in my build

Hope it help

Body:
I just find the explanation: clang put in the [NEEDED] section of the elf binary ALL libraries (even libraries not explicitely included by myself, but referenced by the [NEEDED] section of the library that I include

example from gcc:

readelf -d my_prog

Dynamic section at offset 0x9cb548 contains 46 entries:
  Tag        Type                         Name/Value
 0x0000000000000001 (NEEDED)             Shared library: [libadeversion.so]
 0x0000000000000001 (NEEDED)             Shared library: [libuuid.so.1]
 0x0000000000000001 (NEEDED)             Shared library: [libsqlite3.so]
 0x0000000000000001 (NEEDED)             Shared library: [libpthread.so.0]
 0x0000000000000001 (NEEDED)             Shared library: [libaprutil-1.so.0]
 0x0000000000000001 (NEEDED)             Shared library: [libapr-1.so.0]
 0x0000000000000001 (NEEDED)             Shared library: [libavahi-client.so.3]
 0x0000000000000001 (NEEDED)             Shared library: [libavahi-common.so.3]
 0x0000000000000001 (NEEDED)             Shared library: [libdl.so.2]
 0x0000000000000001 (NEEDED)             Shared library: [libaio.so.1]
 0x0000000000000001 (NEEDED)             Shared library: [librt.so.1]
 0x0000000000000001 (NEEDED)             Shared library: [lib_adm64.so]
 0x0000000000000001 (NEEDED)             Shared library: [lib_dict64.so]
 0x0000000000000001 (NEEDED)             Shared library: [lib_rdm64.so]
 0x0000000000000001 (NEEDED)             Shared library: [lib_dbr64.so]
 0x0000000000000001 (NEEDED)             Shared library: [libstdc++.so.6]
 0x0000000000000001 (NEEDED)             Shared library: [libm.so.6]
 0x0000000000000001 (NEEDED)             Shared library: [libgcc_s.so.1]
 0x0000000000000001 (NEEDED)             Shared library: [libc.so.6]
 0x000000000000001d (RUNPATH)            Library runpath: [${ORIGIN}/../lib/:$ORIGIN/../lib/:../lib/]

from clang:

readelf -d my_prog

Dynamic section at offset 0xa7bae8 contains 54 entries:
  Tag        Type                         Name/Value
 0x0000000000000001 (NEEDED)             Shared library: [libadeversion.so]
 0x0000000000000001 (NEEDED)             Shared library: [libuuid.so.1]
 0x0000000000000001 (NEEDED)             Shared library: [libsqlite3.so]
 0x0000000000000001 (NEEDED)             Shared library: [libpthread.so.0]
 0x0000000000000001 (NEEDED)             Shared library: [libaprutil-1.so.0]
 0x0000000000000001 (NEEDED)             Shared library: [libexpat.so.0]
 0x0000000000000001 (NEEDED)             Shared library: [libapr-1.so.0]
 0x0000000000000001 (NEEDED)             Shared library: [libavahi-client.so.3]
 0x0000000000000001 (NEEDED)             Shared library: [libavahi-common.so.3]
 0x0000000000000001 (NEEDED)             Shared library: [libdl.so.2]
 0x0000000000000001 (NEEDED)             Shared library: [libaio.so.1]
 0x0000000000000001 (NEEDED)             Shared library: [libcrypt.so.1]
 0x0000000000000001 (NEEDED)             Shared library: [librt.so.1]
 0x0000000000000001 (NEEDED)             Shared library: [lib_adm64.so]
 0x0000000000000001 (NEEDED)             Shared library: [lib_dict64.so]
 0x0000000000000001 (NEEDED)             Shared library: [lib_rdm64.so]
 0x0000000000000001 (NEEDED)             Shared library: [lib_rpc64.so]
 0x0000000000000001 (NEEDED)             Shared library: [lib_sql64.so]
 0x0000000000000001 (NEEDED)             Shared library: [lib_rdbc64.so]
 0x0000000000000001 (NEEDED)             Shared library: [lib_rm64.so]
 0x0000000000000001 (NEEDED)             Shared library: [lib_ncp64.so]
 0x0000000000000001 (NEEDED)             Shared library: [lib_cmp64.so]
 0x0000000000000001 (NEEDED)             Shared library: [lib_repfltr64.so]
 0x0000000000000001 (NEEDED)             Shared library: [lib_expat64.so]
 0x0000000000000001 (NEEDED)             Shared library: [lib_cncp64.so]
 0x0000000000000001 (NEEDED)             Shared library: [lib_dbr64.so]
 0x0000000000000001 (NEEDED)             Shared library: [libstdc++.so.6]
 0x0000000000000001 (NEEDED)             Shared library: [libm.so.6]
 0x0000000000000001 (NEEDED)             Shared library: [libgcc_s.so.1]
 0x0000000000000001 (NEEDED)             Shared library: [libc.so.6]
 0x000000000000001d (RUNPATH)            Library runpath: [${ORIGIN}/../lib/:$ORIGIN/../lib/:../lib/]

And one dll include the missing one libexpat:

readelf -d ../lib/libaprutil-1.so.0

Dynamic section at offset 0x1e698 contains 29 entries:
  Tag        Type                         Name/Value
 0x0000000000000001 (NEEDED)             Shared library: **[libexpat.so.0]**
 0x0000000000000001 (NEEDED)             Shared library: [libapr-1.so.0]
 0x0000000000000001 (NEEDED)             Shared library: [libuuid.so.1]
 0x0000000000000001 (NEEDED)             Shared library: [librt.so.1]
 0x0000000000000001 (NEEDED)             Shared library: [libcrypt.so.1]
 0x0000000000000001 (NEEDED)             Shared library: [libpthread.so.0]
 0x0000000000000001 (NEEDED)             Shared library: [libdl.so.2]
 0x0000000000000001 (NEEDED)             Shared library: [libc.so.6]
 0x000000000000000e (SONAME)             Library soname: [libaprutil-1.so.0]

but RUNPATH is only used by the binary not by the dll (that can have is own RUNPATH too).

2 solutions:
- add a RUNPATH in libaprutil-1.so.0 to force to include library from "."
- add explicitely all missing dll in my build

Hope it help


答:
getMap() is deprecated

public void getMapAsync (OnMapReadyCallback callback)

Sets a callback object which will be triggered when the GoogleMap instance is ready to be used.

Note that:

This method must be called from the main thread.

The callback will be executed in the main thread.

In the case where Google Play services is not installed on the user's device, the callback will not be triggered until the user installs it.

In the rare case where the GoogleMap is destroyed immediately after creation, the callback is not triggered.

The GoogleMap object provided by the callback is non-null.

Title: Difference between getMap() and getMapAsync()

Body: I am using getMapAsync() instead of getMap() in mapview.But, I wish to know the difference between getMap() and getMapAsync.


问:
Deploy Shiny App with a scheduled script
I have a simple script that in Rstudio works to deploy app:

```<code>rsconnect::setAccountInfo(name='xx', token='xx', secret='xx/xx')
library(rsconnect)
deployApp("xxx",launch.browser = FALSE)
</code>```

After this prompt appears:

Update application currently deployed at https://xxx.shinyapps.io/xx/?

that block my scheduled script.

There's a way to skip this request and update the shiny app without manually type "Y" in the Console?

答:
It works if you just write an unquoted Y in your script after the "deployApp" command and run it in one batch. Like this:

```<code>rsconnect::setAccountInfo(name='xx', token='xx', secret='xx/xx')
library(rsconnect)
deployApp("xxx", launch.browser = FALSE)
Y
</code>```

Just make sure the lines including deployApp(...) and Y are both selected and not seperated by any other commands when executed.

Body:
I have a simple script that in Rstudio works to deploy app:

rsconnect::setAccountInfo(name='xx', token='xx', secret='xx/xx')
library(rsconnect)
deployApp("xxx",launch.browser = FALSE)

After this prompt appears:

Update application currently deployed at https://xxx.shinyapps.io/xx/?

that block my scheduled script.

There's a way to skip this request and update the shiny app without manually type "Y" in the Console?

Body:
It works if you just write an unquoted Y in your script after the "deployApp" command and run it in one batch. Like this:

rsconnect::setAccountInfo(name='xx', token='xx', secret='xx/xx')
library(rsconnect)
deployApp("xxx", launch.browser = FALSE)
Y

Just make sure the lines including deployApp(...) and Y are both selected and not seperated by any other commands when executed.

ContentLicense: CC BY-SA 4.0


问:
i18n - How to use it in application.hbs?
In which route/component should I inject the "i18n" service for it to be used in application.hbs?
I'm trying to use it in other HBS files, and if I inject "i18n" into the route/component - I'm able to use it.

But it's just not working in application.hbs

答:
Generally you dont have to inject the i18n service to use the t helper, which is what you usually do from a template.

But in generally a service needs to be injected to the controller if you want to use it in the routes template. So you need to inject the service to the application controller to use it on your application template.


问:
iPhone: Splash screen in app - Good or Bad?
I'm going to submit a Lifestyle app to the App Store. I'm confused whether to add a Splash Screen to the App or not ?

Please advise me whether it's a good or bad idea as far as usability and App Store's submission guidelines are concerned.

答:
You should definitely at least add a Default.png to your app if I understand your question correctly.

Launching an app and looking at a black screen for a split second is not the best user experience. Some nice-looking image with your company name or app logo will do. Or you could follow Apple's guidelines and present an image of the starting user interface so that your app will seem to load instantly.

Here's a relevant doc.

ContentLicense: CC BY-SA 2.5


问:
Splicing XML sections with Python's `xml.etree.ElementTree.iterparse`
I would like to use xml.etree.ElementTree.iterparse() to grab sections of an XML file. The file is 60GB and 1B lines, so I do not want to load it all into memory. I do not see a method for outputing whole subsections of xml in the xml library. I recognize that iterparse is iterative and probably only looks ahead so far. How can I do this?

```<code>from xml.etree.ElementTree import iterparse

context = iterparse("file.xml", events=("start", "end"))

for event, elem in context:
    if event == 'start':
        if elem.tag == 'page':
            # Splice out this subset of the XML, including tags
            # Or, better, splice it if `<title>` includes "Foo".
    else:
        elem.clear()
</code>```

The XML looks roughly like this:

```<code><siteinfo>
    <page>
        <title>Foo</title>
            <text>Bar</text>
    </page>
    <page>
        <title>NotFoo</title>
        <text>NotBar</text>
    </page>
</siteinfo>
</code>```

答:
i tried something, its not the exact output you expected, just sharing if it can be useful to you

```<code>path='D:\data.xml'
from xml.etree import ElementTree as Et

context = Et.iterparse(path,events=("start", "end"))
root = None
for event, elem in context:
    if event=='end' or event=='start':
        if elem.text=='Foo':
            elem.clear()
root=elem
with open('d:\output.xml', 'wb') as file:
    Et.ElementTree(root).write(file, encoding='utf-8', xml_declaration=True)
</code>```

Output file :

```<code><?xml version='1.0' encoding='utf-8'?>
<siteinfo>
    <page>
        **#some how this <title /> remains**
        ***<title />***
        <text>Bar</text>
    </page>
    <page>
        <title>NotFoo</title>
        <text>NotBar</text>
    </page>
</siteinfo>
</code>```

Body:
I would like to use xml.etree.ElementTree.iterparse() to grab sections of an XML file. The file is 60GB and 1B lines, so I do not want to load it all into memory. I do not see a method for outputing whole subsections of xml in the xml library. I recognize that iterparse is iterative and probably only looks ahead so far. How can I do this?

from xml.etree.ElementTree import iterparse

context = iterparse("file.xml", events=("start", "end"))

for event, elem in context:
    if event == 'start':
        if elem.tag == 'page':
            # Splice out this subset of the XML, including tags
            # Or, better, splice it if `<title>` includes "Foo".
    else:
        elem.clear()

The XML looks roughly like this:

<siteinfo>
    <page>
        <title>Foo</title>
            <text>Bar</text>
    </page>
    <page>
        <title>NotFoo</title>
        <text>NotBar</text>
    </page>
</siteinfo>

Body:
i tried something, its not the exact output you expected, just sharing if it can be useful to you

path='D:\data.xml'
from xml.etree import ElementTree as Et

context = Et.iterparse(path,events=("start", "end"))
root = None
for event, elem in context:
    if event=='end' or event=='start':
        if elem.text=='Foo':
            elem.clear()
root=elem
with open('d:\output.xml', 'wb') as file:
    Et.ElementTree(root).write(file, encoding='utf-8', xml_declaration=True)

Output file :

<?xml version='1.0' encoding='utf-8'?>
<siteinfo>
    <page>
        **#some how this <title /> remains**
        ***<title />***
        <text>Bar</text>
    </page>
    <page>
        <title>NotFoo</title>
        <text>NotBar</text>
    </page>
</siteinfo>


问:
How can I add a value in my list when a condition is true?
I have a dict with alot of items:

```<code>{'id-quantity-60': u'1', 'id-quantity-35': u'3','id-product-35': u'on', 'id-product-60': u'on',}
</code>```

I need to create a list with all three elements inside.
I'm expecting a list like this:

```<code><type 'list'>: [['60', u'1', u'on'], ['35', u'3', u'on'],]
</code>```

I have only 2 values above, but 2 times the same product-id. So it should add the quantity and the 'on off' together to the same product-id.

How can I do that? I tried it with something like this:

```<code>for key, value in request.params.items():
  if key[:12] == 'id-quantity-':
    if key[12:] in list:
      list.insert(key[12:], value)
    else:
      list.append([key[12:], value])

  if key[:11] == 'id-product-':
    if key[11:] in list:
      list.insert(key[11:], value)
    else:
      list.append([key[11:], value])
</code>```

The problem is I get this list all time splitet:

```<code><type 'list'>: [['60', u'1'], ['35', u'3'], ['35', u'on'], ['60', u'on'],]
</code>```

finally I should be able to fill the data in here (60, 1, True for example):

data = request.registry['website']._subscription_exclude_product(cr, uid, [{'product_id': int(60), 'qty': int(1), 'like': bool(True)}], context=context)

Thank you very much.

答:
Suppose your input dictionary is in request.params variable,

```<code>quantity = {k.split("-")[-1]: v for k, v in request.params.items() if "quantity" in k}
product = {k.split("-")[-1]: v for k, v in request.params.items() if "product" in k}

result = [[k, v, product[k]]  for k, v in quantity.items()]

print(result)
</code>```

Output:

```<code>[['60', '1', 'on'], ['35', '3', 'on']]
</code>```

Updated: replace result=... with the following

```<code>result = [[k, v, True if product.get(k) else False]  for k, v in quantity.items()]
</code>```

to get

```<code>[['35', '3', True], ['42', '0', False]]
</code>```

if "id-product-42" is not in input dict.

Body:
I have a dict with alot of items:

{'id-quantity-60': u'1', 'id-quantity-35': u'3','id-product-35': u'on', 'id-product-60': u'on',}

I need to create a list with all three elements inside.
I'm expecting a list like this:

<type 'list'>: [['60', u'1', u'on'], ['35', u'3', u'on'],]

I have only 2 values above, but 2 times the same product-id. So it should add the quantity and the 'on off' together to the same product-id.

How can I do that? I tried it with something like this:

for key, value in request.params.items():
  if key[:12] == 'id-quantity-':
    if key[12:] in list:
      list.insert(key[12:], value)
    else:
      list.append([key[12:], value])

  if key[:11] == 'id-product-':
    if key[11:] in list:
      list.insert(key[11:], value)
    else:
      list.append([key[11:], value])

The problem is I get this list all time splitet:

<type 'list'>: [['60', u'1'], ['35', u'3'], ['35', u'on'], ['60', u'on'],]

finally I should be able to fill the data in here (60, 1, True for example):

data = request.registry['website']._subscription_exclude_product(cr, uid, [{'product_id': int(60), 'qty': int(1), 'like': bool(True)}], context=context)

Thank you very much.

Body:
Suppose your input dictionary is in request.params variable,

quantity = {k.split("-")[-1]: v for k, v in request.params.items() if "quantity" in k}
product = {k.split("-")[-1]: v for k, v in request.params.items() if "product" in k}

result = [[k, v, product[k]]  for k, v in quantity.items()]

print(result)

Output:

[['60', '1', 'on'], ['35', '3', 'on']]

Updated: replace result=... with the following

result = [[k, v, True if product.get(k) else False]  for k, v in quantity.items()]

to get

[['35', '3', True], ['42', '0', False]]

if "id-product-42" is not in input dict.


问:
Resetting a setTimeout using addEventListener Javascript
i am trying to make a function that when clicking your mouse, can see that you are active or AFK. When the time runs out, this person must be offline. If the person clicks again after the time runs out, the person must come back online. Furthermore, the time must always be reset if he clicks again within the time so you can see that he is active on the page. Does anyone know what I need to adjust here to make it work?</p>

```<code>var time;

window.addEventListener('click', function() {
  time = setTimeout(function() {
    SaveUrl('Save/SetIsOnlineUser', { isOnline: false });
  }, 20000);
})

window.addEventListener("click", myFunction);

function myFunction() {
  clearTimeout(time)
  SaveUrl('Save/SetIsOnlineUser', { isOnline: true });
}
</code>```

答:
Your logic is flawed as you run opposing logic under two handlers which run under the same event.

To fix this you instead need to use a single event handler. You can set the user online immediately within the click handler, then set the timeout for N seconds later to mark them as offline, something like this:

var time;

window.addEventListener('click', function() {
  clearTimeout(time)
  SaveUrl('Save/SetIsOnlineUser', {
    isOnline: true
  });

  time = setTimeout(function() {
    SaveUrl('Save/SetIsOnlineUser', {
      isOnline: false
    });
  }, 5000);
})

function SaveUrl(u, o) {
  console.log('Online:', o.isOnline);
}```

Note that I made the timer only 5 seconds to make the effect more obvious.

Body:
i am trying to make a function that when clicking your mouse, can see that you are active or AFK. When the time runs out, this person must be offline. If the person clicks again after the time runs out, the person must come back online. Furthermore, the time must always be reset if he clicks again within the time so you can see that he is active on the page. Does anyone know what I need to adjust here to make it work?

var time;

window.addEventListener('click', function() {
  time = setTimeout(function() {
    SaveUrl('Save/SetIsOnlineUser', { isOnline: false });
  }, 20000);
})

window.addEventListener("click", myFunction);

function myFunction() {
  clearTimeout(time)
  SaveUrl('Save/SetIsOnlineUser', { isOnline: true });
}

Body:
Your logic is flawed as you run opposing logic under two handlers which run under the same event.

To fix this you instead need to use a single event handler. You can set the user online immediately within the click handler, then set the timeout for N seconds later to mark them as offline, something like this:

var time;

window.addEventListener('click', function() {
  clearTimeout(time)
  SaveUrl('Save/SetIsOnlineUser', {
    isOnline: true
  });

  time = setTimeout(function() {
    SaveUrl('Save/SetIsOnlineUser', {
      isOnline: false
    });
  }, 5000);
})

function SaveUrl(u, o) {
  console.log('Online:', o.isOnline);
}

Note that I made the timer only 5 seconds to make the effect more obvious.


问:
How to fix an error related to Zend parameters?
I have a fatal error:

Class Zend\Stdlib\Parameters contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (ArrayAccess::offsetUnset) in

E:\xampp\htdocs\mage221\vendor\zendframework\zend-stdlib\src\Parameters.php on line 14

How to fix this error? Thanks

答:
I take some step and it solved.

reset your server like xampp, wamp.
give command to magento.

php bin/Magento setup:upgrade

php bin/Magento setup:static-content:deploy

php bin/Magento cache:clean

php bin/Magento cache:flush

thanks.


问:
Combine two different array in javascript
I have two array data that I want to combine into one array, the first array contain only data of date and id, the second array contain name and id.

```<code>    temp_data:[
      0:{
        id:"1"
        date:"2017-11-07"
      }
      1:{
        id:"1"
        date:"2017-11-08"
      }
      2:{
        id:"2"
        date:"2017-11-07"
      }
      3:{
        id:"2"
        date:"2017-11-08"
      }
]

name:[
      0:{
       id:"1"
       name:"Pervies, Peter"
      }
      1:{
       id:"2"
       name:"Ming, Edmund"
      }
]
</code>```

I want the data to be look like this:

```<code>    data:[
    0:{
     id:"1"
     name:"Pervies, Peter"
     details:[
        {date:"2017-11-07"},
        {date:"2017-11-08"}
     ]
    }
    1:{
     id:"2"
     name:"Ming, Edmund"
     details:[
        {date:"2017-11-07"},
        {date:"2017-11-08"}
     ]
    }
]
</code>```

I have try the code below to combine the two array,it works but not in the way I expect.

```<code>  let len = temp_data.length;
    let leng = name.length;
        for (let i = 0; i < leng; ++i) {
            for (let x = 0; x < len; ++x) {
                if (name[i].id == temp_data[x].id) {
                    let id = name[i].id;
                    let details = temp_data[x];
                    data.push({id,details})
                }
            }
        }

    // ------------------------------------------------------------------------

       let dat = temp_data,
       hash = Object.create(null),
       result = [];

   dat.forEach(function (o) {
        if (!hash[o.id]) {
         hash[o.id] = [];
         result.push(hash[o.id]);
        }
          hash[o.id].push(o);
    });

        data = result;
</code>```

can you help me with this?

答:
You could take a Map and iterate both array only once.

var data = [{ id: "1", date: "2017-11-07" }, { id: "1", date: "2017-11-08" }, { id: "2", date: "2017-11-07" }, { id: "2", date: "2017-11-08" }],
    names = [{ id: "1", name: "Pervies, Peter" }, { id: "2", name: "Ming, Edmund" }],
    map = new Map,
    result = names.map(({ id, name }) => ({ id, name, details: map.set(id, []).get(id) }));

data.forEach(({ id, date }) => map.get(id).push({ date }));

console.log(result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
I have two array data that I want to combine into one array, the first array contain only data of date and id, the second array contain name and id.

    temp_data:[
      0:{
        id:"1"
        date:"2017-11-07"
      }
      1:{
        id:"1"
        date:"2017-11-08"
      }
      2:{
        id:"2"
        date:"2017-11-07"
      }
      3:{
        id:"2"
        date:"2017-11-08"
      }
]

name:[
      0:{
       id:"1"
       name:"Pervies, Peter"
      }
      1:{
       id:"2"
       name:"Ming, Edmund"
      }
]

I want the data to be look like this:

    data:[
    0:{
     id:"1"
     name:"Pervies, Peter"
     details:[
        {date:"2017-11-07"},
        {date:"2017-11-08"}
     ]
    }
    1:{
     id:"2"
     name:"Ming, Edmund"
     details:[
        {date:"2017-11-07"},
        {date:"2017-11-08"}
     ]
    }
]

I have try the code below to combine the two array,it works but not in the way I expect.

  let len = temp_data.length;
    let leng = name.length;
        for (let i = 0; i < leng; ++i) {
            for (let x = 0; x < len; ++x) {
                if (name[i].id == temp_data[x].id) {
                    let id = name[i].id;
                    let details = temp_data[x];
                    data.push({id,details})
                }
            }
        }

    // ------------------------------------------------------------------------

       let dat = temp_data,
       hash = Object.create(null),
       result = [];

   dat.forEach(function (o) {
        if (!hash[o.id]) {
         hash[o.id] = [];
         result.push(hash[o.id]);
        }
          hash[o.id].push(o);
    });

        data = result;

can you help me with this?

Body:
You could take a Map and iterate both array only once.

var data = [{ id: "1", date: "2017-11-07" }, { id: "1", date: "2017-11-08" }, { id: "2", date: "2017-11-07" }, { id: "2", date: "2017-11-08" }],
    names = [{ id: "1", name: "Pervies, Peter" }, { id: "2", name: "Ming, Edmund" }],
    map = new Map,
    result = names.map(({ id, name }) => ({ id, name, details: map.set(id, []).get(id) }));

data.forEach(({ id, date }) => map.get(id).push({ date }));

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Select text in devextreme input element
I use Devexpress with TypeScript an angular 4.
How can I select/highlight text in dx-text-box?

I try to use (document.getElementById('id') as HTMLInputElement).select(); but I cannnot get near input fields becaouse it use devextreme wrapper.

Wraper look like this.

```<code><dx-text-box _ngcontent-c1="" id="test" ng-reflect-disabled="false" ng-reflect-value="11:26" class="dx-texteditor dx-widget dx-textbox">
<div class="dx-texteditor-container"><input autocomplete="off" class="dx-texteditor-input" type="text" spellcheck="false" tabindex="0" role="textbox">
<div data-dx_placeholder="" class="dx-placeholder dx-state-invisible">
</div><div class="dx-texteditor-buttons-container"></div></div></dx-text-box>
</code>```

答:
Lets say you have defined your input with following div

```<code><div id="myText"></div>
</code>```

You would than instantiate the dxTextBox like this

```<code>var myTextBox = $("#myText").dxTextBox({value: "Select this text"}).dxTextBox("instance");
</code>```

Now that you have the instance you would acces its input element as such

```<code>var myInput = myTextBox.element().find('input');
</code>```

You can now call the select on your input.

```<code>myInput.select();
</code>```

Title: Select text in devextreme input element

Body:
I use Devexpress with TypeScript an angular 4.
How can I select/highlight text in dx-text-box?

I try to use (document.getElementById('id') as HTMLInputElement).select(); but I cannnot get near input fields becaouse it use devextreme wrapper.

Wraper look like this.

<dx-text-box _ngcontent-c1="" id="test" ng-reflect-disabled="false" ng-reflect-value="11:26" class="dx-texteditor dx-widget dx-textbox">

<input autocomplete="off" class="dx-texteditor-input" type="text" spellcheck="false" tabindex="0" role="textbox">

</dx-text-box>

Body:
Lets say you have defined your input with following div

<div id="myText"></div>

You would than instantiate the dxTextBox like this

var myTextBox = $("#myText").dxTextBox({value: "Select this text"}).dxTextBox("instance");

Now that you have the instance you would acces its input element as such

var myInput = myTextBox.element().find('input');

You can now call the select on your input.

myInput.select();


问:
'Uncaught Error: Can't resolve all parameters for' runtime error when upgrading from Angular 4 to 5.0.1
This is fine in Angular 4.x, just not Angular 5.0.1.  This project was generated with Angular CLI.

```<code>compiler.js:466 Uncaught Error: Can't resolve all parameters for RegistrationService: (?).
    at syntaxError (compiler.js:466)
    at CompileMetadataResolver._getDependenciesMetadata (compiler.js:15546)
    at CompileMetadataResolver._getTypeMetadata (compiler.js:15381)
    at CompileMetadataResolver._getInjectableMetadata (compiler.js:15361)
    at CompileMetadataResolver.getProviderMetadata (compiler.js:15721)
    at eval (compiler.js:15632)
    at Array.forEach (<anonymous>)
    at CompileMetadataResolver._getProvidersMetadata (compiler.js:15592)
    at CompileMetadataResolver.getNgModuleMetadata (compiler.js:15160)
    at CompileMetadataResolver.getNgModuleSummary (compiler.js:14998)
syntaxError @ compiler.js:466
CompileMetadataResolver._getDependenciesMetadata @ compiler.js:15546
CompileMetadataResolver._getTypeMetadata @ compiler.js:15381
CompileMetadataResolver._getInjectableMetadata @ compiler.js:15361
CompileMetadataResolver.getProviderMetadata @ compiler.js:15721
(anonymous) @ compiler.js:15632
CompileMetadataResolver._getProvidersMetadata @ compiler.js:15592
CompileMetadataResolver.getNgModuleMetadata @ compiler.js:15160
CompileMetadataResolver.getNgModuleSummary @ compiler.js:14998
(anonymous) @ compiler.js:15086
CompileMetadataResolver.getNgModuleMetadata @ compiler.js:15071
JitCompiler._loadModules @ compiler.js:33486
JitCompiler._compileModuleAndComponents @ compiler.js:33447
JitCompiler.compileModuleAsync @ compiler.js:33363
CompilerImpl.compileModuleAsync @ platform-browser-dynamic.js:230
PlatformRef.bootstrapModule @ core.js:5446
(anonymous) @ main.ts:12
../../../../../src/main.ts @ main.bundle.js:640
__webpack_require__ @ inline.bundle.js:55
1 @ main.bundle.js:670
__webpack_require__ @ inline.bundle.js:55
webpackJsonpCallback @ inline.bundle.js:26
(anonymous) @ main.bundle.js:1
</code>```

This is what the constructor looks like:

```<code>     constructor(
    private apiHelperService: ApiHelperService
  ) {
  }
</code>```

The class has @Injectable()

```<code>    @Injectable()
export class ApiHelperService {
</code>```

It has also properly imported into the module providers.

```<code>providers: [
    AuthGuard,
    ApiHelperService,
</code>```

If I change it to this, then the error goes away and it works, but then it wants you to change every constructor in the entire solution to this syntax, which I don't believe to be correct.

```<code>@Inject(ApiHelperService) private apiHelperService: ApiHelperService
</code>```

Here is my tsconfig.json, which does have emitDecoratorMetadata properly set to true

```<code>{
  "compileOnSave": false,
  "compilerOptions": {
    "outDir": "./dist/out-tsc",
    "baseUrl": "src",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2017",
      "dom"
    ]
  }
}
</code>```

答: The error mentions that you're using a wron constructor for RegistrationService.</p>

Body:
This is fine in Angular 4.x, just not Angular 5.0.1.  This project was generated with Angular CLI.

compiler.js:466 Uncaught Error: Can't resolve all parameters for RegistrationService: (?).
    at syntaxError (compiler.js:466)
    at CompileMetadataResolver._getDependenciesMetadata (compiler.js:15546)
    at CompileMetadataResolver._getTypeMetadata (compiler.js:15381)
    at CompileMetadataResolver._getInjectableMetadata (compiler.js:15361)
    at CompileMetadataResolver.getProviderMetadata (compiler.js:15721)
    at eval (compiler.js:15632)
    at Array.forEach (<anonymous>)
    at CompileMetadataResolver._getProvidersMetadata (compiler.js:15592)
    at CompileMetadataResolver.getNgModuleMetadata (compiler.js:15160)
    at CompileMetadataResolver.getNgModuleSummary (compiler.js:14998)
syntaxError @ compiler.js:466
CompileMetadataResolver._getDependenciesMetadata @ compiler.js:15546
CompileMetadataResolver._getTypeMetadata @ compiler.js:15381
CompileMetadataResolver._getInjectableMetadata @ compiler.js:15361
CompileMetadataResolver.getProviderMetadata @ compiler.js:15721
(anonymous) @ compiler.js:15632
CompileMetadataResolver._getProvidersMetadata @ compiler.js:15592
CompileMetadataResolver.getNgModuleMetadata @ compiler.js:15160
CompileMetadataResolver.getNgModuleSummary @ compiler.js:14998
(anonymous) @ compiler.js:15086
CompileMetadataResolver.getNgModuleMetadata @ compiler.js:15071
JitCompiler._loadModules @ compiler.js:33486
JitCompiler._compileModuleAndComponents @ compiler.js:33447
JitCompiler.compileModuleAsync @ compiler.js:33363
CompilerImpl.compileModuleAsync @ platform-browser-dynamic.js:230
PlatformRef.bootstrapModule @ core.js:5446
(anonymous) @ main.ts:12
../../../../../src/main.ts @ main.bundle.js:640
__webpack_require__ @ inline.bundle.js:55
1 @ main.bundle.js:670
__webpack_require__ @ inline.bundle.js:55
webpackJsonpCallback @ inline.bundle.js:26
(anonymous) @ main.bundle.js:1

This is what the constructor looks like:

     constructor(
    private apiHelperService: ApiHelperService
  ) {
  }

The class has @Injectable()

    @Injectable()
export class ApiHelperService {

It has also properly imported into the module providers.

providers: [
    AuthGuard,
    ApiHelperService,

If I change it to this, then the error goes away and it works, but then it wants you to change every constructor in the entire solution to this syntax, which I don't believe to be correct.

@Inject(ApiHelperService) private apiHelperService: ApiHelperService

Here is my tsconfig.json, which does have emitDecoratorMetadata properly set to true

{
  "compileOnSave": false,
  "compilerOptions": {
    "outDir": "./dist/out-tsc",
    "baseUrl": "src",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2017",
      "dom"
    ]
  }
}


问:
Should I test (duplicate) data, or only the behavior?
From the design perspective, I am wondering should I test the data, especially if it's a generally known data (not something very configurable) - this can apply to things like popular file extensions, special IP addresses etc.

Suppose we have a emergency phone number classifier:

```<code>public class ContactClassifier {

    public final static String EMERGENCY_PHONE_NUMBER = "911";

    public boolean isEmergencyNumber(String number) {
        return number.equals(EMERGENCY_PHONE_NUMBER);
    }
}
</code>```

Should I test it this way ("911" duplication):

```<code>@Test
public testClassifier() {
    assertTrue(contactClassifier.isEmergencyNumber("911"));
    assertFalse(contactClassifier.isEmergencyNumber("111-other-222"));
}
</code>```

or (test if properly recognized "configured" number):

```<code>@Test
public testClassifier() {
    assertTrue(contactClassifier.isEmergencyNumber(ContactClassifier.EMERGENCY_PHONE_NUMBER));
    assertFalse(contactClassifier.isEmergencyNumber("111-other-222"));
}
</code>```

or inject "911" in the constructor,which looks the most reasonable for me, but even if I do so - should I wrote a test for the "application glue" if the component was instantiated with proper value? If someone can do a typo in data (code), then I see no reasons someone can do a typo in tests case (I bet such data would be copy-paste)

答:
In my opinion the test should check behaviour and not the internal implementation.
The fact that isEmergencyNumber verifies the number over constant declared in the class you're trying to test is verification over internal implementation. You shouldn't rely on it in the test because it is not safe.

Let me give you some examples:

Example #1: Someone changed EMERGENCY_PHONE_NUMBER by mistake and didn't notice. The second test will never catch it.

Example #2: Suppose ContactClassifier is changed by not very smart developer to the following code. Of course it is completely edge case and most likely it will never happen in practice, but it also helps to understand what I mean.

```<code>public final static String EMERGENCY_PHONE_NUMBER = new String("911");

public boolean isEmergencyNumber(String number) {
    return number == EMERGENCY_PHONE_NUMBER;
}
</code>```

In this case your second test will not fail because it relies on internal implementation, but your first test which checks real word behaviour will catch the problem.

Body:
From the design perspective, I am wondering should I test the data, especially if it's a generally known data (not something very configurable) - this can apply to things like popular file extensions, special IP addresses etc.

Suppose we have a emergency phone number classifier:

public class ContactClassifier {

    public final static String EMERGENCY_PHONE_NUMBER = "911";

    public boolean isEmergencyNumber(String number) {
        return number.equals(EMERGENCY_PHONE_NUMBER);
    }
}

Should I test it this way ("911" duplication):

@Test
public testClassifier() {
    assertTrue(contactClassifier.isEmergencyNumber("911"));
    assertFalse(contactClassifier.isEmergencyNumber("111-other-222"));
}

or (test if properly recognized "configured" number):

@Test
public testClassifier() {
    assertTrue(contactClassifier.isEmergencyNumber(ContactClassifier.EMERGENCY_PHONE_NUMBER));
    assertFalse(contactClassifier.isEmergencyNumber("111-other-222"));
}

or inject "911" in the constructor,which looks the most reasonable for me, but even if I do so - should I wrote a test for the "application glue" if the component was instantiated with proper value? If someone can do a typo in data (code), then I see no reasons someone can do a typo in tests case (I bet such data would be copy-paste)

Body:
In my opinion the test should check behaviour and not the internal implementation.
The fact that isEmergencyNumber verifies the number over constant declared in the class you're trying to test is verification over internal implementation. You shouldn't rely on it in the test because it is not safe.

Let me give you some examples:

Example #1: Someone changed EMERGENCY_PHONE_NUMBER by mistake and didn't notice. The second test will never catch it.

Example #2: Suppose ContactClassifier is changed by not very smart developer to the following code. Of course it is completely edge case and most likely it will never happen in practice, but it also helps to understand what I mean.

public final static String EMERGENCY_PHONE_NUMBER = new String("911");

public boolean isEmergencyNumber(String number) {
    return number == EMERGENCY_PHONE_NUMBER;
}

In this case your second test will not fail because it relies on internal implementation, but your first test which checks real word behaviour will catch the problem.


答:
First of all you had errors in your array, arrays do not store key:value pairs like I said in the comments, inside objects you need , to separate array entries and you need , to separate properties inside the actual objects.

When you assign an array to a variable you do not use : but = otherwise you'll get syntax errors.

You can use a simple two way for loop like below;

```<code>var newArray = [];

for(var i = 0; i < name.length; i++){
    var newObj = name[i];
  newObj.details = [];
    var id = name[i].id;

  for(var j = 0; j < temp_data.length; j++){
    if(id == temp_data[j].id){
        newObj.details.push({date : temp_data[j].date});
    }
  }

  newArray.push(newObj);
}
</code>```

Which will generate your desired output in a simple, old fashion way. See JSFiddle for example.

Title: Combine two different array in javascript

Body:
First of all you had errors in your array, arrays do not store key:value pairs like I said in the comments, inside objects you need , to separate array entries and you need , to separate properties inside the actual objects.

When you assign an array to a variable you do not use : but = otherwise you'll get syntax errors.

You can use a simple two way for loop like below;

var newArray = [];

for(var i = 0; i < name.length; i++){
    var newObj = name[i];
  newObj.details = [];
    var id = name[i].id;

  for(var j = 0; j < temp_data.length; j++){
    if(id == temp_data[j].id){
        newObj.details.push({date : temp_data[j].date});
    }
  }

  newArray.push(newObj);
}

Which will generate your desired output in a simple, old fashion way. See JSFiddle for example.


问:
Timestamp to human readable format
Well I have a strange problem while convert from unix timestamp to human representation using javascript

Here is timestamp

```<code>1301090400
</code>```

This is my javascript

```<code>var date = new Date(timestamp * 1000);
var year    = date.getFullYear();
var month   = date.getMonth();
var day     = date.getDay();
var hour    = date.getHours();
var minute  = date.getMinutes();
var seconds = date.getSeconds();
</code>```

I expected results to be 2011 2, 25 22 00 00. But it is 2011, 2, 6, 0, 0, 0
What I miss ?

答:
use Date.prototype.toLocaleTimeString() as documented here

please note the locale example en-US in the url.

Title: Timestamp to human readable format

Body:
Well I have a strange problem while convert from unix timestamp to human representation using javascript

Here is timestamp

1301090400

This is my javascript

var date = new Date(timestamp * 1000);
var year    = date.getFullYear();
var month   = date.getMonth();
var day     = date.getDay();
var hour    = date.getHours();
var minute  = date.getMinutes();
var seconds = date.getSeconds();

I expected results to be 2011 2, 25 22 00 00. But it is 2011, 2, 6, 0, 0, 0
What I miss ?


问:
Display content from DIV
I have the two text button Main Folder & Second Folder using the  tag inside the div element.

```<code><div class="zf-folder">
   <!-- another div elements -->
      <a href="#mainTab" aria-controls="mainTab" role="tab" data-toggle="tab">Main Folder</a>
   <!-- another div elements -->
</div>
</code>```

Unfortunately, I have to click the text to move tabs, can't use the button (div) column to display the content.

How can I display tab content not only from text, but can from clicking on div element.

Please help me, I give a lot of code on JSFiddle.

Thanks in advance

$(document).ready(function() {
  $('table.table').DataTable();
  $('a[data-toggle="tab"]').on('shown.bs.tab', function(e) {
    $($.fn.dataTable.tables(true)).DataTable().columns.adjust();
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>._tabFolder {
  cursor: pointer;
  position: relative;
}

._tabFolder:hover {
  background-color: rgba(255, 255, 255, 0.2)
}

._tabFolder:active {
  background-color: rgba(29, 33, 41, 1)
}

._itemPosition {
  align-items: center;
  display: flex
}

._sideFolder {
  background-color: none;
  height: 90%;
  left: 0;
  position: absolute;
  top: 2px;
  width: 5px
}

._iconText:hover ._1i5y,
.uiPopover.selected ._1i5y {
  display: block
}

._iconText {
  align-items: center;
  display: flex;
  justify-content: space-between;
  width: 100%;
  margin-left: 13px;
}

._iconFolder,
._1i5x,
._1i5w {
  display: inline-block;
  margin-right: 5px;
  vertical-align: middle
}

._iconFolder {
  background-image: url(/rsrc.php/v3/yE/r/miCSJRxMvJi.png);
  background-repeat: no-repeat;
  background-size: auto;
  background-position: -437px -21px;
  height: 24px;
  position: relative;
  width: 24px
}

._5bme ._iconFolder {
  background-image: url(/rsrc.php/v3/yE/r/miCSJRxMvJi.png);
  background-repeat: no-repeat;
  background-size: auto;
  background-position: -412px -21px
}

._icon-col {
  height: 16px;
  left: 4px;
  position: absolute;
  top: 4px;
  width: 16px
}</code>```

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet"/>

              Main Folder

              Second Folder

Main Folder

            Name
            Start Date
            End Date
            Leave Type
            Remarks
            Status
            Operation

            ...
            ...
            ...
            ...
            ...
            ...

              <input hidden="hidden" name="offId" th:value="${off.id}" />
              <button th:id="${off.id}" class="btn btn-success btn-xs approve-off" type="submit" value="approve">
                 Approve
              </button>
              <button th:id="${off.id}" class="btn btn-danger btn-xs reject-off" type="submit" value="reject">
                 Reject
              </button>

Second Folder

            Name
            Start Date
            End Date
            Leave Type
            Remarks
            Status
            Operation

            ...
            ...
            ...
            ...
            ...
            ...

              <input hidden="hidden" name="offId" th:value="${off.id}" />
              <button th:id="${off.id}" class="btn btn-danger btn-xs delete-ocoff" type="submit" value="delete">
                 Delete
              </button>

```

答:
This should work for you. Just add these lines to your JS:

```<code>$(".mainFolder").click(function (e) {
    $(this).find("a")[0].click();
});

$(".secondFolder").click(function (e) {
    $(this).find("a")[0].click();
});
</code>```

Working JSFiddle https://jsfiddle.net/Karadjordje1389/h14uv4ww/

Title: Display content from DIV

Body:
I have the two text button Main Folder & Second Folder using the  tag inside the div element.

      Main Folder

Unfortunately, I have to click the text to move tabs, can't use the button (div) column to display the content.

How can I display tab content not only from text, but can from clicking on div element.

Please help me, I give a lot of code on JSFiddle.

Thanks in advance

$(document).ready(function() {
  $('table.table').DataTable();
  $('a[data-toggle="tab"]').on('shown.bs.tab', function(e) {
    $($.fn.dataTable.tables(true)).DataTable().columns.adjust();
  });
});

._tabFolder {
  cursor: pointer;
  position: relative;
}

._tabFolder:hover {
  background-color: rgba(255, 255, 255, 0.2)
}

._tabFolder:active {
  background-color: rgba(29, 33, 41, 1)
}

._itemPosition {
  align-items: center;
  display: flex
}

._sideFolder {
  background-color: none;
  height: 90%;
  left: 0;
  position: absolute;
  top: 2px;
  width: 5px
}

._iconText:hover ._1i5y,
.uiPopover.selected ._1i5y {
  display: block
}

._iconText {
  align-items: center;
  display: flex;
  justify-content: space-between;
  width: 100%;
  margin-left: 13px;
}

._iconFolder,
._1i5x,
._1i5w {
  display: inline-block;
  margin-right: 5px;
  vertical-align: middle
}

._iconFolder {
  background-image: url(/rsrc.php/v3/yE/r/miCSJRxMvJi.png);
  background-repeat: no-repeat;
  background-size: auto;
  background-position: -437px -21px;
  height: 24px;
  position: relative;
  width: 24px
}

._5bme ._iconFolder {
  background-image: url(/rsrc.php/v3/yE/r/miCSJRxMvJi.png);
  background-repeat: no-repeat;
  background-size: auto;
  background-position: -412px -21px
}

._icon-col {
  height: 16px;
  left: 4px;
  position: absolute;
  top: 4px;
  width: 16px
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet"/>

              Main Folder

              Second Folder

Main Folder

            Name
            Start Date
            End Date
            Leave Type
            Remarks
            Status
            Operation

            ...
            ...
            ...
            ...
            ...
            ...

              <input hidden="hidden" name="offId" th:value="${off.id}" />
              <button th:id="${off.id}" class="btn btn-success btn-xs approve-off" type="submit" value="approve">
                 Approve
              </button>
              <button th:id="${off.id}" class="btn btn-danger btn-xs reject-off" type="submit" value="reject">
                 Reject
              </button>

Second Folder

            Name
            Start Date
            End Date
            Leave Type
            Remarks
            Status
            Operation

            ...
            ...
            ...
            ...
            ...
            ...

              <input hidden="hidden" name="offId" th:value="${off.id}" />
              <button th:id="${off.id}" class="btn btn-danger btn-xs delete-ocoff" type="submit" value="delete">
                 Delete
              </button>

Body:
This should work for you. Just add these lines to your JS:

$(".mainFolder").click(function (e) {
    $(this).find("a")[0].click();
});

$(".secondFolder").click(function (e) {
    $(this).find("a")[0].click();
});

Working JSFiddle https://jsfiddle.net/Karadjordje1389/h14uv4ww/


问:
image as link with javascript
I have two images and two radio buttons.

and if you click on a image the readio button will be selected.

But now I want to have the image as a link. So that you can see the hand - by normal link.

this is the html:

```<code> @if (Html.GebruikerContext().Klant.LogoIDSpecified)
                {
                    <div class="property wide extra-margin">
                        <br />
                        <label>
                            Kies header logo
                        </label>
                        <div class="email-logo">
                            <label>
                                <span class="email-logo-image">
                                     <img src='/Beheer/Images/mainlogo_274x122.png' />
                                </span>
                                <span class="email-logo-button">
                                    @Html.RadioButton("logo-selectie", "standaard", !Model.GebruikKlantLogo, new { @name = "logoKeuze" })
                                    <span>standaard logo</span>
                                </span>
                            </label>
                        </div>                        <div class="email-logo">
                            <label>
                                <span class="email-logo-image">
                                    <img src='/Beheer/Document/Download?documentID=@(Html.GebruikerContext().Klant.LogoID)' />
                                </span>
                                <span class="email-logo-button">
                                    @Html.RadioButton("logo-selectie", "klant", Model.GebruikKlantLogo, new { @name = "logoKeuze" })
                                    <span>eigen logo</span>
                                </span>
                            </label>
                        </div>
                    </div>
                }
</code>```

and this is the javascript:

```<code>$('#logo-selectie[value=standaard]').change(function () {
    $('#GebruikKlantLogo').val(false);
});

$('#logo-selectie[value=klant]').change(function () {
    $('#GebruikKlantLogo').val(true);
});
</code>```

答:
Unless I'm misunderstanding, I think you're overthinking the problem. To display a pointer when hovering over the image, all you need to do is add a small amount of CSS to style the image.

.showPointer {
  cursor: pointer;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img class="showPointer" src="http://via.placeholder.com/300x300"></code>```

Title: image as link with javascript

Body:
I have two images and two radio buttons.

and if you click on a image the readio button will be selected.

But now I want to have the image as a link. So that you can see the hand - by normal link.

this is the html:

 @if (Html.GebruikerContext().Klant.LogoIDSpecified)
                {

                            Kies header logo

                                    @Html.RadioButton("logo-selectie", "standaard", !Model.GebruikKlantLogo, new { @name = "logoKeuze" })
                                    standaard logo

                                    @Html.RadioButton("logo-selectie", "klant", Model.GebruikKlantLogo, new { @name = "logoKeuze" })
                                    eigen logo

                }

and this is the javascript:

$('#logo-selectie[value=standaard]').change(function () {
    $('#GebruikKlantLogo').val(false);
});

$('#logo-selectie[value=klant]').change(function () {
    $('#GebruikKlantLogo').val(true);
});

Body:
Unless I'm misunderstanding, I think you're overthinking the problem. To display a pointer when hovering over the image, all you need to do is add a small amount of CSS to style the image.

.showPointer {
  cursor: pointer;
}

<img class="showPointer" src="http://via.placeholder.com/300x300">


问:
Get file's absolute path SharepointOnline
I need to get the absolute path of a file within a document library.
Doing some research i figured out that i cannot do that directly by code without querying Sharepoint using CSOM.

Which is the recommended/correct way?

1)

```<code>context.Load(file, f => f.ListItemAllFields["FileRef"]);
</code>```

2)

Using File.LinkingUrl?

UPDATE

Something like this?

```<code>            List docLib = context.Web.Lists.GetByTitle(doclibrary);

            CamlQuery query = new CamlQuery();
            query.ViewXml = @"<View>
                                <Query>
                                    <Where>
                                        <Eq>
                                            <FieldRef Name='Name'/>
                                            <Value Type='Text'>" +versionId+ @"</Value>
                                        </Eq>
                                    </Where>
                                    <RowLimit>1</RowLimit>
                                </Query>
                            </View>";

            ListItemCollection collListItems = docLib.GetItems(query);

            context.Load(docLib);
            context.Load(collListItems, items => items.Include(
                item => item["FileRef"],
                item => item["FileLeafRef"],
                item => item["EncodedAbsUrl"]
            ));

            context.ExecuteQuery();

            ListItem listItem = collListItems[0];

            fileAbsPath = (string)listItem["EncodedAbsUrl"];
</code>```

答:
Have a try this.</p>

```<code>var linkUrl=(stirng)file.item["EncodedAbsUrl"];
</code>```

Body:
I need to get the absolute path of a file within a document library.
Doing some research i figured out that i cannot do that directly by code without querying Sharepoint using CSOM.

Which is the recommended/correct way?

1)

context.Load(file, f => f.ListItemAllFields["FileRef"]);

2)

Using File.LinkingUrl?

UPDATE

Something like this?

            List docLib = context.Web.Lists.GetByTitle(doclibrary);

            CamlQuery query = new CamlQuery();
            query.ViewXml = @"<View>
                                <Query>
                                    <Where>
                                        <Eq>
                                            <FieldRef Name='Name'/>
                                            <Value Type='Text'>" +versionId+ @"</Value>
                                        </Eq>
                                    </Where>
                                    <RowLimit>1</RowLimit>
                                </Query>
                            </View>";

            ListItemCollection collListItems = docLib.GetItems(query);

            context.Load(docLib);
            context.Load(collListItems, items => items.Include(
                item => item["FileRef"],
                item => item["FileLeafRef"],
                item => item["EncodedAbsUrl"]
            ));

            context.ExecuteQuery();

            ListItem listItem = collListItems[0];

            fileAbsPath = (string)listItem["EncodedAbsUrl"];

Body:
Have a try this.

var linkUrl=(stirng)file.item["EncodedAbsUrl"];


问:
Problem with UITableView clear color
I have a tableview in grouped style. When I set the tableview background color to clear color then I see dark black corners around the tableview. Is there a way to solve this problem and remove those dark corners?

Any help would be appreciated.

答:
Along with using clearColor, use the following:

```<code>[tableView setBackgroundView:nil];
[tableView setBackgroundColor:[UIColor clearColor]];
[tableView setOpaque:NO];
</code>```

Title: Problem with UITableView clear color

Body:
Along with using clearColor, use the following:

[tableView setBackgroundView:nil];
[tableView setBackgroundColor:[UIColor clearColor]];
[tableView setOpaque:NO];


问:
How to set env variable in Jupyter notebook
I've a problem that Jupyter can't see env variable in bashrc file. Is there a way to load these variables in jupyter or add custom variables to it?</p>

答:
If you need the variable set before you're starting the notebook, the only solution which worked for me was env VARIABLE=$VARIABLE jupyter notebook with export VARIABLE=value in .bashrc.

In my case tensorflow needs the exported variable for successful importing it in a notebook.


问:
When I create a zip file of a directory with a large zip file in PHP, I am facing a memory limit
I am facing a memory limit error in my WordPress plugin code.

My Code:

```<code>function zipData($source, $destination) {
    if (extension_loaded('zip')) {
        if (file_exists($source)) {
            $zip = new ZipArchive();
            if ($zip -> open($destination, ZipArchive::CREATE) === TRUE)     {
                $source = realpath($source);
                if (is_dir($source)) {
                    $iterator = new RecursiveDirectoryIterator($source);

                    $iterator->setFlags(RecursiveDirectoryIterator::SKIP_DOTS);
                    $files = new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::SELF_FIRST);
                    foreach ($files as $file) {
                        $file = realpath($file);
                        if (is_dir($file)) {
                            $zip->addEmptyDir(str_replace($source . '/', '', $file . '/'));
                        } else if (is_file($file)) {
                            $zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
                        }
                    }
                } else if (is_file($source)) {
                    $zip->addFromString(basename($source), file_get_contents($source));
                }
            }
            return $zip->close();
        }
    }
    return false;
}

ini_set('max_execution_time', 600);
ini_set('memory_limit','1024M');
zipData($upload_dir['basedir'], $upload_dir['basedir'].'/Jincowboy/JinBackupMedia'. time() .'.zip');
</code>```

I encountered a memory limit so I checked Google.

I found that stream zip file generation is needed for avoiding the memory limit, but I couldn't confirm about this.

I want my code to bypass this memory limit and allow creation of a zip file based on a directory with large files.

How can I fix this?

答:
You can try https://github.com/Grandt/PHPZip which supports creating ZIP files with streaming data (lowering memory usage by a lot).

And there are plenty of stackoverflow posts about zipping with streams with a pletora of answers.

Body:
I am facing a memory limit error in my WordPress plugin code.

My Code:

function zipData($source, $destination) {
    if (extension_loaded('zip')) {
        if (file_exists($source)) {
            $zip = new ZipArchive();
            if ($zip -> open($destination, ZipArchive::CREATE) === TRUE)     {
                $source = realpath($source);
                if (is_dir($source)) {
                    $iterator = new RecursiveDirectoryIterator($source);

                    $iterator->setFlags(RecursiveDirectoryIterator::SKIP_DOTS);
                    $files = new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::SELF_FIRST);
                    foreach ($files as $file) {
                        $file = realpath($file);
                        if (is_dir($file)) {
                            $zip->addEmptyDir(str_replace($source . '/', '', $file . '/'));
                        } else if (is_file($file)) {
                            $zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
                        }
                    }
                } else if (is_file($source)) {
                    $zip->addFromString(basename($source), file_get_contents($source));
                }
            }
            return $zip->close();
        }
    }
    return false;
}

ini_set('max_execution_time', 600);
ini_set('memory_limit','1024M');
zipData($upload_dir['basedir'], $upload_dir['basedir'].'/Jincowboy/JinBackupMedia'. time() .'.zip');

I encountered a memory limit so I checked Google.

I found that stream zip file generation is needed for avoiding the memory limit, but I couldn't confirm about this.

I want my code to bypass this memory limit and allow creation of a zip file based on a directory with large files.

How can I fix this?


问:
Singleton class vs static methods and fields?
Why are Singleton Classes used in Android/Java, when the same functionality looks to be provided by using a class with static fields and methods?

e.g.

```<code>public class StaticClass {
    private static int foo = 0;

    public static void setFoo(int f) {
        foo = f;
    }

    public static int getFoo() {
        return foo;
    }
}
</code>```

vs

```<code>public class SingletonClass implements Serializable {

    private static volatile SingletonClass sSoleInstance;
    private int foo;

    //private constructor.
    private SingletonClass(){

        //Prevent form the reflection api.
        if (sSoleInstance != null){
            throw new RuntimeException("Use getInstance() method to get the single instance of this class.");
        }

        foo = 0;
    }

    public static SingletonClass getInstance() {
        if (sSoleInstance == null) { //if there is no instance available... create new one
            synchronized (SingletonClass.class) {
                if (sSoleInstance == null) sSoleInstance = new SingletonClass();
            }
        }

        return sSoleInstance;
    }

    //Make singleton from serialize and deserialize operation.
    protected SingletonClass readResolve() {
        return getInstance();
    }

    public void setFoo(int foo) {
        this.foo = foo;
    }

    public int getFoo() {
        return foo;
    }
}
</code>```

答:
This is mainly due to the limitations of static types versus singletons. Which are:

Static types cannot implement interfaces and derive from base classes.

From the above we can see that static types cause high coupling - you cannot use other classes in tests and different environments.

Static classes cannot be injected using dependency injection.

Singletons are much easier to mock and shim.

Singletons can be easily converted to transients.

These a few reasons from the top of my head. This is probably not all.

Body:
Why are Singleton Classes used in Android/Java, when the same functionality looks to be provided by using a class with static fields and methods?

e.g.

public class StaticClass {
    private static int foo = 0;

    public static void setFoo(int f) {
        foo = f;
    }

    public static int getFoo() {
        return foo;
    }
}

vs

public class SingletonClass implements Serializable {

    private static volatile SingletonClass sSoleInstance;
    private int foo;

    //private constructor.
    private SingletonClass(){

        //Prevent form the reflection api.
        if (sSoleInstance != null){
            throw new RuntimeException("Use getInstance() method to get the single instance of this class.");
        }

        foo = 0;
    }

    public static SingletonClass getInstance() {
        if (sSoleInstance == null) { //if there is no instance available... create new one
            synchronized (SingletonClass.class) {
                if (sSoleInstance == null) sSoleInstance = new SingletonClass();
            }
        }

        return sSoleInstance;
    }

    //Make singleton from serialize and deserialize operation.
    protected SingletonClass readResolve() {
        return getInstance();
    }

    public void setFoo(int foo) {
        this.foo = foo;
    }

    public int getFoo() {
        return foo;
    }
}


问:
Ionic 2 - Google Maps Native: marker click event not firing
I am using Ionic 2 and the google maps cordova plugin.

"cordova-plugin-googlemaps": "^2.0.11"

I cannot get this listener to fire.

The marker is added to the map but the click event does not fire the alert.

Thanks for the help!

```<code>    let latlng = new LatLng(spot.lat, spot.long);
    let markerOptions: MarkerOptions = {
        'position': latlng,
        'animation': 'drop'
      };

      this.map.addMarker(markerOptions).then((marker: Marker) => {
        marker.addEventListener(GoogleMapsEvent.MARKER_CLICK).subscribe(e => {
          alert('foo');
        });
      });
</code>```

Additional Information

@ionic-native/core: 'version': 3.7.0

@ionic-native/google-maps: 'version': '4.3.0'

import {
 GoogleMaps,
 GoogleMap,
 GoogleMapsEvent,
 GoogleMapOptions,
 CameraPosition,
 MarkerOptions,
 LatLng,
 Marker
} from '@ionic-native/google-maps';

I am looping through multiple lat long coordinates and adding them to the map. The event never gets fired for any of them.

When I try to attach the even to just one of the markers it does not work either.

Lastly if I put another alert it does not fire. Is it possible the add marker promise is not resolving?

```<code>this.map.addMarker(markerOptions).then((marker: Marker) => {
   alert('in here');
 marker.addEventListener(GoogleMapsEvent.MARKER_CLICK).subscribe(e => {
   alert('foo');
 });
});
</code>```

答:
You should try this. It worked fine for me</p>

```<code>marker.on(GoogleMapsEvent.MARKER_CLICK).subscribe((latLng: LatLng) => {
    // do something
});
</code>```

Body:
I am using Ionic 2 and the google maps cordova plugin.

"cordova-plugin-googlemaps": "^2.0.11"

I cannot get this listener to fire.

The marker is added to the map but the click event does not fire the alert.

Thanks for the help!

    let latlng = new LatLng(spot.lat, spot.long);
    let markerOptions: MarkerOptions = {
        'position': latlng,
        'animation': 'drop'
      };

      this.map.addMarker(markerOptions).then((marker: Marker) => {
        marker.addEventListener(GoogleMapsEvent.MARKER_CLICK).subscribe(e => {
          alert('foo');
        });
      });

Additional Information

@ionic-native/core: 'version': 3.7.0

@ionic-native/google-maps: 'version': '4.3.0'

import {
 GoogleMaps,
 GoogleMap,
 GoogleMapsEvent,
 GoogleMapOptions,
 CameraPosition,
 MarkerOptions,
 LatLng,
 Marker
} from '@ionic-native/google-maps';

I am looping through multiple lat long coordinates and adding them to the map. The event never gets fired for any of them.

When I try to attach the even to just one of the markers it does not work either.

Lastly if I put another alert it does not fire. Is it possible the add marker promise is not resolving?

this.map.addMarker(markerOptions).then((marker: Marker) => {
   alert('in here');
 marker.addEventListener(GoogleMapsEvent.MARKER_CLICK).subscribe(e => {
   alert('foo');
 });
});

Body:
You should try this. It worked fine for me

marker.on(GoogleMapsEvent.MARKER_CLICK).subscribe((latLng: LatLng) => {
    // do something
});


问:
CASE .. WHEN expression in Oracle SQL
I have the table with 1 column and has following data

```<code>Status
a1
i
t
a2
a3
</code>```

I want to display the following result in my select query

```<code>Status| STATUSTEXT
a1    | Active
i     | Inactive
t     | Terminated
a2    | Active
a3    | Active
</code>```

One way I could think was using a Switch When expression in select query

```<code>SELECT
status,
CASE status
WHEN 'a1' THEN 'Active'
WHEN 'a2' THEN 'Active'
WHEN 'a3' THEN 'Active'
WHEN 'i' THEN 'Inactive'
WHEN 't' THEN 'Terminated'
END AS StatusText
FROM stage.tst
</code>```

Is there any other way of doing this where I don't need to write When expression 3 times for Active Status  and the entire active status can be checked in one single expression?

答:
```<code>SELECT
  STATUS,
  CASE
    WHEN STATUS IN('a1','a2','a3')
     THEN 'Active'
    WHEN STATUS = 'i'
     THEN 'Inactive'
    WHEN STATUS = 't'
     THEN 'Terminated'  ELSE null
  END AS STATUSTEXT
FROM
  stage.tst;
</code>```

Title: CASE .. WHEN expression in Oracle SQL

Body:
I have the table with 1 column and has following data

Status
a1
i
t
a2
a3

I want to display the following result in my select query

Status| STATUSTEXT
a1    | Active
i     | Inactive
t     | Terminated
a2    | Active
a3    | Active

One way I could think was using a Switch When expression in select query

SELECT
status,
CASE status
WHEN 'a1' THEN 'Active'
WHEN 'a2' THEN 'Active'
WHEN 'a3' THEN 'Active'
WHEN 'i' THEN 'Inactive'
WHEN 't' THEN 'Terminated'
END AS StatusText
FROM stage.tst

Is there any other way of doing this where I don't need to write When expression 3 times for Active Status  and the entire active status can be checked in one single expression?