问:
jQuery - good solution for "easy parsing" of html string
I have the following html string (var jsonHtmlString) returned as json in a jquery get request and need to parse the html to return an array of objects with using the info below. There's probably an easy way to do this but I haven't been able to find it. I'm hoping someone might be able to recommend an "easy parsing" solution (and if you use an online tool (e.g. plnkr.co) to easily seeing the parsing as you test your js code)?

I've included what the jQuery selector value should return on each line of the mapped object. Thanks!

```<code>var jsonHtmlString = '<div class="search-result-srch box"> <span class="number">1.</span>
    <a href="/Practice/Detail.aspx?docid=18600&mode=search&p=Tools-@-Technology">The Continuous Learning Technology Stack: Thinking outside the LMS</a>
    <br />
    <div title="Research Report" class="description rr">This report introduces the Continuous Learning Technology Stack, or the sum of technologies that can be leveraged for enabling continuous learning within organizations. </div>
    <div class="pracsub"> <span class="col1-a">Practice:</span> <span class="col1-b"><strong>Tools & Technology</strong></span> <span class="col2-a">Subject:</span> <span class="col2-b"><strong>Learning Tech</strong></span> </div>
    <div class="pracsub top-blue-brdr"> <span class="col1-a">Access:</span> <span class="col1-b">Member</span> <span class="col2-a">Published:</span> <span class="col2-b">09/02/2015</span>
        <div class="clearfix"></div> <span class="col1-a">Type:</span> <span class="col1-b">Research Report</span> </div>
    <div class="clearfix"></div>
</div>
<div class="search-result-srch box"> <span class="number">2.</span>
    <a href="/Practice/Detail.aspx?docid=18817&mode=search&p=Learning-@-Development">Business Case for Investing Beyond the LMS (editable PPT)</a>
    <br />
    <div title="Performance Support" class="description ps">This editable PowerPoint template guides you through the process of building and presenting a business case for investing in continuous learning—beyond the LMS.</div>
    <div class="pracsub"> <span class="col1-a">Practice:</span> <span class="col1-b"><strong>Learning & Development</strong></span> <span class="col2-a">Subject:</span> <span class="col2-b"><strong>Informal Learning</strong></span> </div>
    <div class="pracsub top-blue-brdr"> <span class="col1-a">Access:</span> <span class="col1-b">Complimentary</span> <span class="col2-a">Published:</span> <span class="col2-b">08/26/2015</span>
        <div class="clearfix"></div> <span class="col1-a">Type:</span> <span class="col1-b">Performance Support</span> </div>
    <div class="clearfix"></div>
</div>';

var items = parseHtml(jsonHtmlString);

function parseHtml(html) {
    var items = $(div.search-result-srch); // array of object for each div class="search-result-srchbox"
    items.map((item) => {
            return {
                title: $(item)('a'), // The Continuous Learning..., Business Case for...
                description: $(item)('.description'), // This report introduces..., This editable PowerPoint...
                practice: $(item)('.col1-b').innerText, // Tools & Technology, Learning & Development
                subject: $(item)('.col2-b').innerText, // Learning Tech, Informal Learning
                access: $(item)('.pracsub .col2-b').innerText, // Member, Complimentary
                publishDate: $(item)('.pracsub .col2-b').innerText, // 09/02/2015, 08/26/2015
                type: $(item)('.pracsub .col1-b:last-of-type').innerText, // Research Report, Performance Support
            }
    });
}
</code>```

答:
jQuery has a parseHTML method already. You just need to run that and then map through the results correctly. Sample below:

```<code>var jsonHtmlString = `<div class="search-result-srch box"> <span class="number">1.</span>
<a href="/Practice/Detail.aspx?docid=18600&mode=search&p=Tools-@-Technology">The Continuous Learning Technology Stack: Thinking outside the LMS</a>
<br />
<div title="Research Report" class="description rr">This report introduces the Continuous Learning Technology Stack, or the sum of technologies that can be leveraged for enabling continuous learning within organizations. </div>
<div class="pracsub"> <span class="col1-a">Practice:</span> <span class="col1-b"><strong>Tools & Technology</strong></span> <span class="col2-a">Subject:</span> <span class="col2-b"><strong>Learning Tech</strong></span> </div>
<div class="pracsub top-blue-brdr"> <span class="col1-a">Access:</span> <span class="col1-b">Member</span> <span class="col2-a">Published:</span> <span class="col2-b">09/02/2015</span>
    <div class="clearfix"></div> <span class="col1-a">Type:</span> <span class="col1-b">Research Report</span> </div>
<div class="clearfix"></div>
</div>
<div class="search-result-srch box"> <span class="number">2.</span>
<a href="/Practice/Detail.aspx?docid=18817&mode=search&p=Learning-@-Development">Business Case for Investing Beyond the LMS (editable PPT)</a>
<br />
<div title="Performance Support" class="description ps">This editable PowerPoint template guides you through the process of building and presenting a business case for investing in continuous learning—beyond the LMS.</div>
<div class="pracsub"> <span class="col1-a">Practice:</span> <span class="col1-b"><strong>Learning & Development</strong></span> <span class="col2-a">Subject:</span> <span class="col2-b"><strong>Informal Learning</strong></span> </div>
<div class="pracsub top-blue-brdr"> <span class="col1-a">Access:</span> <span class="col1-b">Complimentary</span> <span class="col2-a">Published:</span> <span class="col2-b">08/26/2015</span>
    <div class="clearfix"></div> <span class="col1-a">Type:</span> <span class="col1-b">Performance Support</span> </div>
<div class="clearfix"></div>
</div>`;

var htmled = $.parseHTML(jsonHtmlString);

var listOfObjects = htmled.map(item => {
  if ($(item).hasClass('search-result-srch')) {
    return {
      title: $(item).find('a').text(), // The Continuous Learning..., Business Case for...
      description: $(item).find('.description').text(), // This report introduces..., This editable PowerPoint...
      practice: $(item).find('.col1-b').text(), // Tools & Technology, Learning & Development
      subject: $(item).find('.col2-b').text(), // Learning Tech, Informal Learning
      access: $(item).find('.pracsub .col2-b').text(), // Member, Complimentary
    publishDate: $(item).find('.pracsub .col2-b').text(), // 09/02/2015, 08/26/2015
      type: $(item).find('.pracsub .col1-b:last-of-type').text(), // Research Report, Performance Support
    };
  }
});
</code>```

Body:
I have the following html string (var jsonHtmlString) returned as json in a jquery get request and need to parse the html to return an array of objects with using the info below. There's probably an easy way to do this but I haven't been able to find it. I'm hoping someone might be able to recommend an "easy parsing" solution (and if you use an online tool (e.g. plnkr.co) to easily seeing the parsing as you test your js code)?

I've included what the jQuery selector value should return on each line of the mapped object. Thanks!

var jsonHtmlString = '
 1.
    The Continuous Learning Technology Stack: Thinking outside the LMS

This report introduces the Continuous Learning Technology Stack, or the sum of technologies that can be leveraged for enabling continuous learning within organizations.

 Practice: Tools & Technology Subject: Learning Tech

 Access: Member Published: 09/02/2015

 Type: Research Report

 2.
    Business Case for Investing Beyond the LMS (editable PPT)

This editable PowerPoint template guides you through the process of building and presenting a business case for investing in continuous learning—beyond the LMS.

 Practice: Learning & Development Subject: Informal Learning

 Access: Complimentary Published: 08/26/2015

 Type: Performance Support

';

var items = parseHtml(jsonHtmlString);

function parseHtml(html) {
    var items = $(div.search-result-srch); // array of object for each div class="search-result-srchbox"
    items.map((item) => {
            return {
                title: $(item)('a'), // The Continuous Learning..., Business Case for...
                description: $(item)('.description'), // This report introduces..., This editable PowerPoint...
                practice: $(item)('.col1-b').innerText, // Tools & Technology, Learning & Development
                subject: $(item)('.col2-b').innerText, // Learning Tech, Informal Learning
                access: $(item)('.pracsub .col2-b').innerText, // Member, Complimentary
                publishDate: $(item)('.pracsub .col2-b').innerText, // 09/02/2015, 08/26/2015
                type: $(item)('.pracsub .col1-b:last-of-type').innerText, // Research Report, Performance Support
            }
    });
}

Body:
jQuery has a parseHTML method already. You just need to run that and then map through the results correctly. Sample below:

var jsonHtmlString = `<div class="search-result-srch box"> <span class="number">1.</span>
<a href="/Practice/Detail.aspx?docid=18600&mode=search&p=Tools-@-Technology">The Continuous Learning Technology Stack: Thinking outside the LMS</a>
<br />
<div title="Research Report" class="description rr">This report introduces the Continuous Learning Technology Stack, or the sum of technologies that can be leveraged for enabling continuous learning within organizations. </div>
<div class="pracsub"> <span class="col1-a">Practice:</span> <span class="col1-b"><strong>Tools & Technology</strong></span> <span class="col2-a">Subject:</span> <span class="col2-b"><strong>Learning Tech</strong></span> </div>
<div class="pracsub top-blue-brdr"> <span class="col1-a">Access:</span> <span class="col1-b">Member</span> <span class="col2-a">Published:</span> <span class="col2-b">09/02/2015</span>
    <div class="clearfix"></div> <span class="col1-a">Type:</span> <span class="col1-b">Research Report</span> </div>
<div class="clearfix"></div>
</div>
<div class="search-result-srch box"> <span class="number">2.</span>
<a href="/Practice/Detail.aspx?docid=18817&mode=search&p=Learning-@-Development">Business Case for Investing Beyond the LMS (editable PPT)</a>
<br />
<div title="Performance Support" class="description ps">This editable PowerPoint template guides you through the process of building and presenting a business case for investing in continuous learning—beyond the LMS.</div>
<div class="pracsub"> <span class="col1-a">Practice:</span> <span class="col1-b"><strong>Learning & Development</strong></span> <span class="col2-a">Subject:</span> <span class="col2-b"><strong>Informal Learning</strong></span> </div>
<div class="pracsub top-blue-brdr"> <span class="col1-a">Access:</span> <span class="col1-b">Complimentary</span> <span class="col2-a">Published:</span> <span class="col2-b">08/26/2015</span>
    <div class="clearfix"></div> <span class="col1-a">Type:</span> <span class="col1-b">Performance Support</span> </div>
<div class="clearfix"></div>
</div>`;

var htmled = $.parseHTML(jsonHtmlString);

var listOfObjects = htmled.map(item => {
  if ($(item).hasClass('search-result-srch')) {
    return {
      title: $(item).find('a').text(), // The Continuous Learning..., Business Case for...
      description: $(item).find('.description').text(), // This report introduces..., This editable PowerPoint...
      practice: $(item).find('.col1-b').text(), // Tools & Technology, Learning & Development
      subject: $(item).find('.col2-b').text(), // Learning Tech, Informal Learning
      access: $(item).find('.pracsub .col2-b').text(), // Member, Complimentary
    publishDate: $(item).find('.pracsub .col2-b').text(), // 09/02/2015, 08/26/2015
      type: $(item).find('.pracsub .col1-b:last-of-type').text(), // Research Report, Performance Support
    };
  }
});


来源: stackexchange

问:
How to get bottom of user stack under multi threads on Linux
I would like to get user stack information on 64bit Linux.
I know mm->start_stack that indicates a location of an initial stack pointer of user stack.

However, under multi thread applications like a pthread, mm->start_stack is the same values all threads because of using same struct task_struct.

And, I know the way of memory layout by using mm->mmap->vm_start and mm->mmap->vm_end but, I do not know that whether these mmap area are stack or not.

I confirmed memory layout under these with pmap process id and strace.

Could you tell me how to get user stack location all threads like a mm->start_stack?.

```<code>sudo pmap 24074
24074:   ./a.out
0000000000400000      4K r-x-- a.out
0000000000600000      4K r---- a.out
0000000000601000      4K rw--- a.out
0000000000602000    132K rw---   [ anon ]
00007ffff5fee000      4K -----   [ anon ]
00007ffff5fef000   8192K rw---   [ anon ]   <==== Thread Stack
00007ffff67ef000      4K -----   [ anon ]
00007ffff67f0000   8192K rw---   [ anon ]   <==== Thread Stack
00007ffff6ff0000      4K -----   [ anon ]
00007ffff6ff1000   8192K rw---   [ anon ]   <==== Thread Stack
00007ffff77f1000   1792K r-x-- libc-2.23.so
00007ffff79b1000   2044K ----- libc-2.23.so
00007ffff7bb0000     16K r---- libc-2.23.so
00007ffff7bb4000      8K rw--- libc-2.23.so
00007ffff7bb6000     16K rw---   [ anon ]
00007ffff7bba000     96K r-x-- libpthread-2.23.so
00007ffff7bd2000   2044K ----- libpthread-2.23.so
00007ffff7dd1000      4K r---- libpthread-2.23.so
00007ffff7dd2000      4K rw--- libpthread-2.23.so
00007ffff7dd3000     16K rw---   [ anon ]
00007ffff7dd7000    152K r-x-- ld-2.23.so
00007ffff7fda000     12K rw---   [ anon ]
00007ffff7ff6000      8K rw---   [ anon ]
00007ffff7ff8000      8K r----   [ anon ]
00007ffff7ffa000      8K r-x--   [ anon ]
00007ffff7ffc000      4K r---- ld-2.23.so
00007ffff7ffd000      4K rw--- ld-2.23.so
00007ffff7ffe000      4K rw---   [ anon ]
00007ffffffde000    132K rw---   [ stack ]
ffffffffff600000      4K r-x--   [ anon ]
 total            31108K
</code>```

strace results

```<code>clone(child_stack=0x7ffff77efff0,flags=CLONE_VM|CLONE_FS|CLONE_FILES|CLONE_SIGHAND|CLONE_THREAD|CLONE_SYSVSEM|CLONE_SETTLS|CLONE_PARENT_SETTID|CLONE_CHILD_CLEARTID, parent_tidptr=0x7ffff77f09d0, tls=0x7ffff77f0700, child_tidptr=0x7ffff77f09d0) = 24075

clone(pid: 24074 child_stack=0x7ffff6feeff0, flags=CLONE_VM|CLONE_FS|CLONE_FILES|CLONE_SIGHAND|CLONE_THREAD|CLONE_SYSVSEM|CLONE_SETTLS|CLONE_PARENT_SETTID|CLONE_CHILD_CLEARTID, parent_tidptr=0x7ffff6fef9d0, tls=0x7ffff6fef700, child_tidptr=0x7ffff6fef9d0) = 24076

clone(child_stack=0x7ffff67edff0, flags=CLONE_VM|CLONE_FS|CLONE_FILES|CLONE_SIGHAND|CLONE_THREAD|CLONE_SYSVSEM|CLONE_SETTLS|CLONE_PARENT_SETTID|CLONE_CHILD_CLEARTID, parent_tidptr=0x7ffff67ee9d0, tls=0x7ffff67ee700, child_tidptr=0x7ffff67ee9d0) = 24077
</code>```

答:
Most systems provide pthread_getattr_np (Linux) or pthread_attr_get_np (NetBSD) or similar means to initialize a pthread_attr_t structure from a running thread.

Once you have done that, you can use e.g. pthread_attr_getstackaddr and pthread_attr_getstacksize to get the lowest address and the size. The "bottom" of the stack is either the former or the sum of both, depending on the direction of stack growth.

Small note of warning: while many systems provide this functionality, it may or may not work for the initial/main thread of a program. You have found one Linux specific way of dealing with this already.

ContentLicense: CC BY-SA 3.0

Body:
I would like to get user stack information on 64bit Linux.
I know mm->start_stack that indicates a location of an initial stack pointer of user stack.

However, under multi thread applications like a pthread, mm->start_stack is the same values all threads because of using same struct task_struct.

And, I know the way of memory layout by using mm->mmap->vm_start and mm->mmap->vm_end but, I do not know that whether these mmap area are stack or not.

I confirmed memory layout under these with pmap process id and strace.

Could you tell me how to get user stack location all threads like a mm->start_stack?.

sudo pmap 24074
24074:   ./a.out
0000000000400000      4K r-x-- a.out
0000000000600000      4K r---- a.out
0000000000601000      4K rw--- a.out
0000000000602000    132K rw---   [ anon ]
00007ffff5fee000      4K -----   [ anon ]
00007ffff5fef000   8192K rw---   [ anon ]   <==== Thread Stack
00007ffff67ef000      4K -----   [ anon ]
00007ffff67f0000   8192K rw---   [ anon ]   <==== Thread Stack
00007ffff6ff0000      4K -----   [ anon ]
00007ffff6ff1000   8192K rw---   [ anon ]   <==== Thread Stack
00007ffff77f1000   1792K r-x-- libc-2.23.so
00007ffff79b1000   2044K ----- libc-2.23.so
00007ffff7bb0000     16K r---- libc-2.23.so
00007ffff7bb4000      8K rw--- libc-2.23.so
00007ffff7bb6000     16K rw---   [ anon ]
00007ffff7bba000     96K r-x-- libpthread-2.23.so
00007ffff7bd2000   2044K ----- libpthread-2.23.so
00007ffff7dd1000      4K r---- libpthread-2.23.so
00007ffff7dd2000      4K rw--- libpthread-2.23.so
00007ffff7dd3000     16K rw---   [ anon ]
00007ffff7dd7000    152K r-x-- ld-2.23.so
00007ffff7fda000     12K rw---   [ anon ]
00007ffff7ff6000      8K rw---   [ anon ]
00007ffff7ff8000      8K r----   [ anon ]
00007ffff7ffa000      8K r-x--   [ anon ]
00007ffff7ffc000      4K r---- ld-2.23.so
00007ffff7ffd000      4K rw--- ld-2.23.so
00007ffff7ffe000      4K rw---   [ anon ]
00007ffffffde000    132K rw---   [ stack ]
ffffffffff600000      4K r-x--   [ anon ]
 total            31108K

strace results

clone(child_stack=0x7ffff77efff0,flags=CLONE_VM|CLONE_FS|CLONE_FILES|CLONE_SIGHAND|CLONE_THREAD|CLONE_SYSVSEM|CLONE_SETTLS|CLONE_PARENT_SETTID|CLONE_CHILD_CLEARTID, parent_tidptr=0x7ffff77f09d0, tls=0x7ffff77f0700, child_tidptr=0x7ffff77f09d0) = 24075

clone(pid: 24074 child_stack=0x7ffff6feeff0, flags=CLONE_VM|CLONE_FS|CLONE_FILES|CLONE_SIGHAND|CLONE_THREAD|CLONE_SYSVSEM|CLONE_SETTLS|CLONE_PARENT_SETTID|CLONE_CHILD_CLEARTID, parent_tidptr=0x7ffff6fef9d0, tls=0x7ffff6fef700, child_tidptr=0x7ffff6fef9d0) = 24076

clone(child_stack=0x7ffff67edff0, flags=CLONE_VM|CLONE_FS|CLONE_FILES|CLONE_SIGHAND|CLONE_THREAD|CLONE_SYSVSEM|CLONE_SETTLS|CLONE_PARENT_SETTID|CLONE_CHILD_CLEARTID, parent_tidptr=0x7ffff67ee9d0, tls=0x7ffff67ee700, child_tidptr=0x7ffff67ee9d0) = 24077


问:
how to display by clicking an imageview into fullscreen and zoom?
i have seen many answers about this question. but none of those worked perfectly for me. I just want to know how to display and immageview thumbnail by clicking/touching it into full screen view and also it enables to zoomin zoomout.

thank you

答:
Instead of ImageView Use TouchImageView class and open it in full
  Screen

```<code>public class TouchImageView extends ImageView {

    Matrix matrix;

    // We can be in one of these 3 states
    static final int NONE = 0;
    static final int DRAG = 1;
    static final int ZOOM = 2;
    int mode = NONE;

    // Remember some things for zooming
    PointF last = new PointF();
    PointF start = new PointF();
    float minScale = 1f;
    float maxScale = 3f;
    float[] m;

    int viewWidth, viewHeight;
    static final int CLICK = 3;
    float saveScale = 1f;
    protected float origWidth, origHeight;
    int oldMeasuredWidth, oldMeasuredHeight;

    ScaleGestureDetector mScaleDetector;

    Context context;

    public TouchImageView(Context context) {
        super(context);
        sharedConstructing(context);
    }

    public TouchImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        sharedConstructing(context);
    }

    private void sharedConstructing(Context context) {
        super.setClickable(true);
        this.context = context;
        mScaleDetector = new ScaleGestureDetector(context, new ScaleListener());
        matrix = new Matrix();
        m = new float[9];
        setImageMatrix(matrix);
        setScaleType(ScaleType.MATRIX);

        setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                mScaleDetector.onTouchEvent(event);
                PointF curr = new PointF(event.getX(), event.getY());

                switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    last.set(curr);
                    start.set(last);
                    mode = DRAG;
                    break;

                case MotionEvent.ACTION_MOVE:
                    if (mode == DRAG) {
                        float deltaX = curr.x - last.x;
                        float deltaY = curr.y - last.y;
                        float fixTransX = getFixDragTrans(deltaX, viewWidth, origWidth * saveScale);
                        float fixTransY = getFixDragTrans(deltaY, viewHeight, origHeight * saveScale);
                        matrix.postTranslate(fixTransX, fixTransY);
                        fixTrans();
                        last.set(curr.x, curr.y);
                    }
                    break;

                case MotionEvent.ACTION_UP:
                    mode = NONE;
                    int xDiff = (int) Math.abs(curr.x - start.x);
                    int yDiff = (int) Math.abs(curr.y - start.y);
                    if (xDiff < CLICK && yDiff < CLICK)
                        performClick();
                    break;

                case MotionEvent.ACTION_POINTER_UP:
                    mode = NONE;
                    break;
                }

                setImageMatrix(matrix);
                invalidate();
                return true; // indicate event was handled
            }

        });
    }

    public void setMaxZoom(float x) {
        maxScale = x;
    }

    private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
        @Override
        public boolean onScaleBegin(ScaleGestureDetector detector) {
            mode = ZOOM;
            return true;
        }

        @Override
        public boolean onScale(ScaleGestureDetector detector) {
            float mScaleFactor = detector.getScaleFactor();
            float origScale = saveScale;
            saveScale *= mScaleFactor;
            if (saveScale > maxScale) {
                saveScale = maxScale;
                mScaleFactor = maxScale / origScale;
            } else if (saveScale < minScale) {
                saveScale = minScale;
                mScaleFactor = minScale / origScale;
            }

            if (origWidth * saveScale <= viewWidth || origHeight * saveScale <= viewHeight)
                matrix.postScale(mScaleFactor, mScaleFactor, viewWidth / 2, viewHeight / 2);
            else
                matrix.postScale(mScaleFactor, mScaleFactor, detector.getFocusX(), detector.getFocusY());

            fixTrans();
            return true;
        }
    }

    void fixTrans() {
        matrix.getValues(m);
        float transX = m[Matrix.MTRANS_X];
        float transY = m[Matrix.MTRANS_Y];

        float fixTransX = getFixTrans(transX, viewWidth, origWidth * saveScale);
        float fixTransY = getFixTrans(transY, viewHeight, origHeight * saveScale);

        if (fixTransX != 0 || fixTransY != 0)
            matrix.postTranslate(fixTransX, fixTransY);
    }

    float getFixTrans(float trans, float viewSize, float contentSize) {
        float minTrans, maxTrans;

        if (contentSize <= viewSize) {
            minTrans = 0;
            maxTrans = viewSize - contentSize;
        } else {
            minTrans = viewSize - contentSize;
            maxTrans = 0;
        }

        if (trans < minTrans)
            return -trans + minTrans;
        if (trans > maxTrans)
            return -trans + maxTrans;
        return 0;
    }

    float getFixDragTrans(float delta, float viewSize, float contentSize) {
        if (contentSize <= viewSize) {
            return 0;
        }
        return delta;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        viewWidth = MeasureSpec.getSize(widthMeasureSpec);
        viewHeight = MeasureSpec.getSize(heightMeasureSpec);

        //
        // Rescales image on rotation
        //
        if (oldMeasuredHeight == viewWidth && oldMeasuredHeight == viewHeight || viewWidth == 0 || viewHeight == 0)
            return;
        oldMeasuredHeight = viewHeight;
        oldMeasuredWidth = viewWidth;

        if (saveScale == 1) {
            // Fit to screen.
            float scale;

            Drawable drawable = getDrawable();
            if (drawable == null || drawable.getIntrinsicWidth() == 0 || drawable.getIntrinsicHeight() == 0)
                return;
            int bmWidth = drawable.getIntrinsicWidth();
            int bmHeight = drawable.getIntrinsicHeight();

            Log.d("bmSize", "bmWidth: " + bmWidth + " bmHeight : " + bmHeight);

            float scaleX = (float) viewWidth / (float) bmWidth;
            float scaleY = (float) viewHeight / (float) bmHeight;
            scale = Math.min(scaleX, scaleY);
            matrix.setScale(scale, scale);

            // Center the image
            float redundantYSpace = (float) viewHeight - (scale * (float) bmHeight);
            float redundantXSpace = (float) viewWidth - (scale * (float) bmWidth);
            redundantYSpace /= (float) 2;
            redundantXSpace /= (float) 2;

            matrix.postTranslate(redundantXSpace, redundantYSpace);

            origWidth = viewWidth - 2 * redundantXSpace;
            origHeight = viewHeight - 2 * redundantYSpace;
            setImageMatrix(matrix);
        }
        fixTrans();
    }
}
</code>```

Body:
Instead of ImageView Use TouchImageView class and open it in full
  Screen

public class TouchImageView extends ImageView {

    Matrix matrix;

    // We can be in one of these 3 states
    static final int NONE = 0;
    static final int DRAG = 1;
    static final int ZOOM = 2;
    int mode = NONE;

    // Remember some things for zooming
    PointF last = new PointF();
    PointF start = new PointF();
    float minScale = 1f;
    float maxScale = 3f;
    float[] m;

    int viewWidth, viewHeight;
    static final int CLICK = 3;
    float saveScale = 1f;
    protected float origWidth, origHeight;
    int oldMeasuredWidth, oldMeasuredHeight;

    ScaleGestureDetector mScaleDetector;

    Context context;

    public TouchImageView(Context context) {
        super(context);
        sharedConstructing(context);
    }

    public TouchImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        sharedConstructing(context);
    }

    private void sharedConstructing(Context context) {
        super.setClickable(true);
        this.context = context;
        mScaleDetector = new ScaleGestureDetector(context, new ScaleListener());
        matrix = new Matrix();
        m = new float[9];
        setImageMatrix(matrix);
        setScaleType(ScaleType.MATRIX);

        setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                mScaleDetector.onTouchEvent(event);
                PointF curr = new PointF(event.getX(), event.getY());

                switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    last.set(curr);
                    start.set(last);
                    mode = DRAG;
                    break;

                case MotionEvent.ACTION_MOVE:
                    if (mode == DRAG) {
                        float deltaX = curr.x - last.x;
                        float deltaY = curr.y - last.y;
                        float fixTransX = getFixDragTrans(deltaX, viewWidth, origWidth * saveScale);
                        float fixTransY = getFixDragTrans(deltaY, viewHeight, origHeight * saveScale);
                        matrix.postTranslate(fixTransX, fixTransY);
                        fixTrans();
                        last.set(curr.x, curr.y);
                    }
                    break;

                case MotionEvent.ACTION_UP:
                    mode = NONE;
                    int xDiff = (int) Math.abs(curr.x - start.x);
                    int yDiff = (int) Math.abs(curr.y - start.y);
                    if (xDiff < CLICK && yDiff < CLICK)
                        performClick();
                    break;

                case MotionEvent.ACTION_POINTER_UP:
                    mode = NONE;
                    break;
                }

                setImageMatrix(matrix);
                invalidate();
                return true; // indicate event was handled
            }

        });
    }

    public void setMaxZoom(float x) {
        maxScale = x;
    }

    private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
        @Override
        public boolean onScaleBegin(ScaleGestureDetector detector) {
            mode = ZOOM;
            return true;
        }

        @Override
        public boolean onScale(ScaleGestureDetector detector) {
            float mScaleFactor = detector.getScaleFactor();
            float origScale = saveScale;
            saveScale *= mScaleFactor;
            if (saveScale > maxScale) {
                saveScale = maxScale;
                mScaleFactor = maxScale / origScale;
            } else if (saveScale < minScale) {
                saveScale = minScale;
                mScaleFactor = minScale / origScale;
            }

            if (origWidth * saveScale <= viewWidth || origHeight * saveScale <= viewHeight)
                matrix.postScale(mScaleFactor, mScaleFactor, viewWidth / 2, viewHeight / 2);
            else
                matrix.postScale(mScaleFactor, mScaleFactor, detector.getFocusX(), detector.getFocusY());

            fixTrans();
            return true;
        }
    }

    void fixTrans() {
        matrix.getValues(m);
        float transX = m[Matrix.MTRANS_X];
        float transY = m[Matrix.MTRANS_Y];

        float fixTransX = getFixTrans(transX, viewWidth, origWidth * saveScale);
        float fixTransY = getFixTrans(transY, viewHeight, origHeight * saveScale);

        if (fixTransX != 0 || fixTransY != 0)
            matrix.postTranslate(fixTransX, fixTransY);
    }

    float getFixTrans(float trans, float viewSize, float contentSize) {
        float minTrans, maxTrans;

        if (contentSize <= viewSize) {
            minTrans = 0;
            maxTrans = viewSize - contentSize;
        } else {
            minTrans = viewSize - contentSize;
            maxTrans = 0;
        }

        if (trans < minTrans)
            return -trans + minTrans;
        if (trans > maxTrans)
            return -trans + maxTrans;
        return 0;
    }

    float getFixDragTrans(float delta, float viewSize, float contentSize) {
        if (contentSize <= viewSize) {
            return 0;
        }
        return delta;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        viewWidth = MeasureSpec.getSize(widthMeasureSpec);
        viewHeight = MeasureSpec.getSize(heightMeasureSpec);

        //
        // Rescales image on rotation
        //
        if (oldMeasuredHeight == viewWidth && oldMeasuredHeight == viewHeight || viewWidth == 0 || viewHeight == 0)
            return;
        oldMeasuredHeight = viewHeight;
        oldMeasuredWidth = viewWidth;

        if (saveScale == 1) {
            // Fit to screen.
            float scale;

            Drawable drawable = getDrawable();
            if (drawable == null || drawable.getIntrinsicWidth() == 0 || drawable.getIntrinsicHeight() == 0)
                return;
            int bmWidth = drawable.getIntrinsicWidth();
            int bmHeight = drawable.getIntrinsicHeight();

            Log.d("bmSize", "bmWidth: " + bmWidth + " bmHeight : " + bmHeight);

            float scaleX = (float) viewWidth / (float) bmWidth;
            float scaleY = (float) viewHeight / (float) bmHeight;
            scale = Math.min(scaleX, scaleY);
            matrix.setScale(scale, scale);

            // Center the image
            float redundantYSpace = (float) viewHeight - (scale * (float) bmHeight);
            float redundantXSpace = (float) viewWidth - (scale * (float) bmWidth);
            redundantYSpace /= (float) 2;
            redundantXSpace /= (float) 2;

            matrix.postTranslate(redundantXSpace, redundantYSpace);

            origWidth = viewWidth - 2 * redundantXSpace;
            origHeight = viewHeight - 2 * redundantYSpace;
            setImageMatrix(matrix);
        }
        fixTrans();
    }
}


问:
Connection to the server was unsuccessful. (file ///android_asset/www/index.html)
I have an error when I run my app on ionic cordova run android.
My error is : Connection to the server was unsuccessful. (file ///android_asset/www/index.html)
I try to resolve it with forums that exists with this solution :

1)Rename your index.html to “main.html”

2)Create a new “index.html” and put the following content into it:

```<code><!doctype html>
<html>
  <head>
   <title>title</title>
   <script>
     window.location='./main.html';
   </script>
  <body>
  </body>
</html>
</code>```

Or modify in the config.xml this line :

```<code><preference name="SplashScreenDelay" value="3000" />
</code>```

to this line :

```<code><preference name="SplashScreenDelay" value="70000" />
</code>```

But when I run my app after saving my new code, the error still appear and when I return into my code, I see that the code is still the same and not has been modified (even if I modified it like I sayed previously !)

Someone know how to resolve my problem ?

Thanks in advance,
Caroline

答:
Add and Remove android platform
ionic platform rm android
ionic platform add android

Body:
I have an error when I run my app on ionic cordova run android.
My error is : Connection to the server was unsuccessful. (file ///android_asset/www/index.html)
I try to resolve it with forums that exists with this solution :

1)Rename your index.html to “main.html”

2)Create a new “index.html” and put the following content into it:

<!doctype html>

   <title>title</title>

Or modify in the config.xml this line :

<preference name="SplashScreenDelay" value="3000" />

to this line :

<preference name="SplashScreenDelay" value="70000" />

But when I run my app after saving my new code, the error still appear and when I return into my code, I see that the code is still the same and not has been modified (even if I modified it like I sayed previously !)

Someone know how to resolve my problem ?

Thanks in advance,
Caroline


问:
Unable to make my app location aware
I am following the android tutorial on making your app location aware here

but when I run it in the emulator the below method

```<code>@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
    Log.i("state", "Connection failed: ConnectionResult.getErrorCode() = " + connectionResult.getErrorCode());
}
</code>```

shows in the Logcat:

Connection failed: ConnectionResult.getErrorCode() = 9

Does anyone know what ErrorCode 9 means?

答:
public static final int SERVICE_INVALID

The version of the Google Play services installed on this device is
  not authentic.

Constant Value: 9

Source: ConnectionResult

Are you running the emulator that uses the Google APIs?

Title: Unable to make my app location aware

Body:
I am following the android tutorial on making your app location aware here

but when I run it in the emulator the below method

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
    Log.i("state", "Connection failed: ConnectionResult.getErrorCode() = " + connectionResult.getErrorCode());
}

shows in the Logcat:

Connection failed: ConnectionResult.getErrorCode() = 9

Does anyone know what ErrorCode 9 means?


问:
Is it possible to retrieve Samsung Gear S3 watch pedometer and heart rate logs without using the Samsung S Health app on the phone/tablet
Say for some reason, maybe some kind of security constraints, you can "not" run the Samsung "S Health" app which talks to Samsung cloud servers etc. But you do want to access the History/Logs off of the Samsung "Gear S3 watch", so is that possible or does Samsung lock that data so only "their" S Health app can get it?

So is there a way to download the pedometer+heart-rate "statistics"/data that you can see on the Gear S3 watch without using Internet/cloud or the official "S Health App" from Samsung on your phone?

Problem is if you don't use Samsung's S Health app it seems the log statistics get lost after a while, that it doesn't store too much on the watch itself only the last couple weeks. I don't want to use S-Health on Phone but would like to keep periodically saving the pedometer+heart rate data from gear-s3 watch so that the older data doesn't get lost.

Or is the "only" way to save the stats from days and weeks for pedometer daily walking stats and heart-rate, is from doing a completely separate app yourself that counts steps using the sensor etc?

Or maybe there is some "hacky" way to do this and get existing data/logs that are on the gear s3 watch without using the Samsung S Health app on the phone?

答: If you want to access historical data you are going to make a phone application. Samsung keeps the historical health data locked down and only accessible through an SDK  for Android Application. If you wanted to make an application that the user only interacts with through the watch you would still need a phone side companion application to interface to the Samsung Health service. The phone side application could run as a service  so that it is otherwise invisible to the user. From the user's perspective, it would be a watch application. A user would also need to grant your application access to the type of data that it needs to access (an application doesn't automatically have access simply from being on someone's phone). You can download and read more about the Samsung Health SDK from  this site http://developer.samsung.com/health</p>


问:
Microsoft Graph how to request emails for a different user?
I understand how this call works (to get my own emails):

```<code>graphClient.Me.MailFolders.Inbox.Messages.Request().GetAsync();
</code>```

How would I use a similar call do get another user's emails? Would it be something like this?:

```<code>graphClient.Users["userid"].MailFolders.Inbox.Messages.Request().Top(25).GetAsync();
</code>```

When I execute this, I get this error: "Error in /Home/GetEmails: Caller needs to authenticate."

答:
You can only do this if you request for an App Only Token using App Only permissions for access to the Microsoft Graph.

Read here to learn about the different Graph Permissions for the Mail Endpoint.

I think this only works for AAD accounts, and you must be a Tenant Administrator to consent to these kinds of permissions.

Body:
I understand how this call works (to get my own emails):

graphClient.Me.MailFolders.Inbox.Messages.Request().GetAsync();

How would I use a similar call do get another user's emails? Would it be something like this?:

graphClient.Users["userid"].MailFolders.Inbox.Messages.Request().Top(25).GetAsync();

When I execute this, I get this error: "Error in /Home/GetEmails: Caller needs to authenticate."


问:
Why is the image not displaying in php and random symbols appearing instead
I have the webserver and the sql server working fin but when i run the file no image is displayed and characters like �})>�}(���>��j|��0�Ry>�s appear instead. What am i missing? the cobe below is part of the page.</p>

```<code>    <body>
         <?php
    $servername = "localhost";
    $user = "root";
    $passw = "Ajax3617";
    $dbname="sailingdb";
    // Create connection
    $conn = new mysqli($servername, $user, $passw, $dbname);

    $sql = "SELECT picturefile FROM pictures";
    $result = mysqli_query($conn,$sql);
    while ($row = mysqli_fetch_assoc($result))  {

echo '<img src="'.$row['picturefile'].'" width="175" height="200" />';

    } ?>
</body>
</html>
</code>```

答:
If the data in $row['picturefile'] is base64 encoded you could display it with the following:

```<code>echo '<img src="'.'data:image/png;base64,'.$row['picturefile'].'" width="175" height="200" />';
</code>```

Body:
I have the webserver and the sql server working fin but when i run the file no image is displayed and characters like �})>�}(���>��j|��0�Ry>�s appear instead. What am i missing? the cobe below is part of the page.

         <?php
    $servername = "localhost";
    $user = "root";
    $passw = "Ajax3617";
    $dbname="sailingdb";
    // Create connection
    $conn = new mysqli($servername, $user, $passw, $dbname);

    $sql = "SELECT picturefile FROM pictures";
    $result = mysqli_query($conn,$sql);
    while ($row = mysqli_fetch_assoc($result))  {

echo '';

    } ?>

Body:
If the data in $row['picturefile'] is base64 encoded you could display it with the following:

echo '<img src="'.'data:image/png;base64,'.$row['picturefile'].'" width="175" height="200" />';


问:
Java Reflect/AOP override supertype private Method
Is it at all possible to "override" a private method of a super class in Java?

The class whose method I wish to override is a third party class so I cannot modify the source. It would be ideal if there were some way to reflectively set a method on a class.

Alternatively, if it is possible to intercept a private method of a third party class then this would be suitable.

答:
Is it at all possible to "override" a private method of a super class in Java?

No

I don't think using Reflection there would be a tweak , it will break OOP there

ContentLicense: CC BY-SA 2.5


问:
Error installing generator-jhipster with npm on ubuntu 16
I am trying to install jhipster to run a repository I have already cloned in /home/thomas/Documents/softeng/project/CS673-Project.  I cant parse what is missing.  the command I've run is sudo npm install -g generator-jhipster.
Below I have included the complete relevant section of the log.

```<code>11518 silly install generator-jhipster@4.5.2
11519 info lifecycle generator-jhipster@4.5.2~install: generator-jhipster@4.5.2
11520 verbose lifecycle generator-jhipster@4.5.2~install: unsafe-perm in lifecycle false
11521 verbose lifecycle generator-jhipster@4.5.2~install: PATH: /usr/local/lib/node_modules/npm/bin/node-gyp-bin:/usr/local/lib/node_modules/generator-jhipster/node_modules/.bin:/usr/local/lib/node_modules/.bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/snap/bin
11522 verbose lifecycle generator-jhipster@4.5.2~install: CWD: /usr/local/lib/node_modules/generator-jhipster
11523 silly lifecycle generator-jhipster@4.5.2~install: Args: [ '-c', 'tabtab install --name jhipster --auto' ]
11524 silly lifecycle generator-jhipster@4.5.2~install: Returned: code: 1  signal: null
11525 info lifecycle generator-jhipster@4.5.2~install: Failed to exec install script
11526 verbose unlock done using /home/thomas/.npm/_locks/staging-3a08f0df5026584d.lock for /usr/local/lib/node_modules/.staging
11527 verbose stack Error: generator-jhipster@4.5.2 install: `tabtab install --name jhipster --auto`
11527 verbose stack Exit status 1
11527 verbose stack     at EventEmitter.<anonymous> (/usr/local/lib/node_modules/npm/lib/utils/lifecycle.js:283:16)
11527 verbose stack     at emitTwo (events.js:87:13)
11527 verbose stack     at EventEmitter.emit (events.js:172:7)
11527 verbose stack     at ChildProcess.<anonymous> (/usr/local/lib/node_modules/npm/lib/utils/spawn.js:40:14)
11527 verbose stack     at emitTwo (events.js:87:13)
11527 verbose stack     at ChildProcess.emit (events.js:172:7)
11527 verbose stack     at maybeClose (internal/child_process.js:821:16)
11527 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:211:5)
11528 verbose pkgid generator-jhipster@4.5.2
11529 verbose cwd /home/thomas/Documents/softeng/project/CS673-Project
11530 verbose Linux 4.4.0-53-generic
11531 verbose argv "/usr/bin/nodejs" "/usr/local/bin/npm" "install" "-g" "generator-jhipster"
11532 verbose node v4.2.6
11533 verbose npm  v5.0.3
11534 error code ELIFECYCLE
11535 error errno 1
11536 error generator-jhipster@4.5.2 install: `tabtab install --name jhipster --auto`
11536 error Exit status 1
11537 error Failed at the generator-jhipster@4.5.2 install script.
11537 error This is probably not a problem with npm. There is likely additional logging output above.
11538 verbose exit [ 1, true ]
</code>```

Thank you so much

答: I can see in your log, node 4.2.6. It's too old. Try the version 6.10.3 LTS</p>

Body:
I am trying to install jhipster to run a repository I have already cloned in /home/thomas/Documents/softeng/project/CS673-Project.  I cant parse what is missing.  the command I've run is sudo npm install -g generator-jhipster.
Below I have included the complete relevant section of the log.

11518 silly install generator-jhipster@4.5.2
11519 info lifecycle generator-jhipster@4.5.2~install: generator-jhipster@4.5.2
11520 verbose lifecycle generator-jhipster@4.5.2~install: unsafe-perm in lifecycle false
11521 verbose lifecycle generator-jhipster@4.5.2~install: PATH: /usr/local/lib/node_modules/npm/bin/node-gyp-bin:/usr/local/lib/node_modules/generator-jhipster/node_modules/.bin:/usr/local/lib/node_modules/.bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/snap/bin
11522 verbose lifecycle generator-jhipster@4.5.2~install: CWD: /usr/local/lib/node_modules/generator-jhipster
11523 silly lifecycle generator-jhipster@4.5.2~install: Args: [ '-c', 'tabtab install --name jhipster --auto' ]
11524 silly lifecycle generator-jhipster@4.5.2~install: Returned: code: 1  signal: null
11525 info lifecycle generator-jhipster@4.5.2~install: Failed to exec install script
11526 verbose unlock done using /home/thomas/.npm/_locks/staging-3a08f0df5026584d.lock for /usr/local/lib/node_modules/.staging
11527 verbose stack Error: generator-jhipster@4.5.2 install: `tabtab install --name jhipster --auto`
11527 verbose stack Exit status 1
11527 verbose stack     at EventEmitter.<anonymous> (/usr/local/lib/node_modules/npm/lib/utils/lifecycle.js:283:16)
11527 verbose stack     at emitTwo (events.js:87:13)
11527 verbose stack     at EventEmitter.emit (events.js:172:7)
11527 verbose stack     at ChildProcess.<anonymous> (/usr/local/lib/node_modules/npm/lib/utils/spawn.js:40:14)
11527 verbose stack     at emitTwo (events.js:87:13)
11527 verbose stack     at ChildProcess.emit (events.js:172:7)
11527 verbose stack     at maybeClose (internal/child_process.js:821:16)
11527 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:211:5)
11528 verbose pkgid generator-jhipster@4.5.2
11529 verbose cwd /home/thomas/Documents/softeng/project/CS673-Project
11530 verbose Linux 4.4.0-53-generic
11531 verbose argv "/usr/bin/nodejs" "/usr/local/bin/npm" "install" "-g" "generator-jhipster"
11532 verbose node v4.2.6
11533 verbose npm  v5.0.3
11534 error code ELIFECYCLE
11535 error errno 1
11536 error generator-jhipster@4.5.2 install: `tabtab install --name jhipster --auto`
11536 error Exit status 1
11537 error Failed at the generator-jhipster@4.5.2 install script.
11537 error This is probably not a problem with npm. There is likely additional logging output above.
11538 verbose exit [ 1, true ]

Thank you so much


问:
Does grape provide a template to build services
https://github.com/intridea/grape

Is there a way to automatically generate a template for an application which will use grape to provide REST like interfaces. I am looking for something like "rails new app" which will provide me the skeleton to build on. If not what should I be using?

答:
grape-starter seems to be what you're looking for.

Install the gem (gem install grape-starter) and create your new API with grape-starter new awesome_api.

For more options, such as choosing an ORM, or setting the prefix, use grape-starter -h. I recommend to have a look on the README.


问:
Change div order on smaller width screens in YUI Pure CSS
Here's an image of what I'm trying to do in YUI Pure CSS on a smaller width screen:

My HTML is pretty straight forward:

```<code><div class="pure-g">
    <div class="pure-u-1 pure-u-sm-1-2">

        <div class="pure-g">
            <div class="pure-u-1>
                A
            </div>
        </div>

        <div class="pure-g">
            <div class="pure-u-1>
                B
            </div>
        </div>

        <div class="pure-g">
            <div class="pure-u-1>
                C
            </div>
        </div>

    </div>
    <div class="pure-u-1 pure-u-sm-1-2">

        <div class="pure-g">
            <div class="pure-u-1>
                D
            </div>
        </div>

        <div class="pure-g">
            <div class="pure-u-1>
                E
            </div>
        </div>

        <div class="pure-g">
            <div class="pure-u-1>
                F
            </div>
        </div>

    </div>
</div>
</code>```

Is there a way to do this with just YUI Pure CSS or would I need to use JQuery/Javascript?

答: Sure, make A, B, and C float left and D, E, and F float right at a larger screen width. But they would have to be taken out of the "pure-u-1 pure-u-sm-1-2" divs.</p>

Body:
Here's an image of what I'm trying to do in YUI Pure CSS on a smaller width screen:

My HTML is pretty straight forward:

                A

                B

                C

                D

                E

                F

Is there a way to do this with just YUI Pure CSS or would I need to use JQuery/Javascript?


问:
Jenkins pipeline BuildDiscarderProperty
I am trying to utilize BuildDiscarderProperty option with our jenkins job template. But currently it is working only with properties function which is not favoring with usage of job template. Could someone help us to configure BuildDiscarderProperty option without using properties function?
Thanks</p>

答:
Found the solution. Used General job definition at Groovy Template for pipeline. It is not breaking anything but just deleting old builds</p>

```<code><flow-definition>
<properties>
  <jenkins.model.BuildDiscarderProperty>
  <strategy class="hudson.tasks.LogRotator">
    <daysToKeep>365</daysToKeep>
    <numToKeep>30</numToKeep>
    <artifactDaysToKeep>-1</artifactDaysToKeep>
    <artifactNumToKeep>-1</artifactNumToKeep>
  </strategy>
  </jenkins.model.BuildDiscarderProperty>
  <org.jenkinsci.plugins.workflow.job.properties.PipelineTriggersJobProperty>
</org.jenkinsci.plugins.workflow.job.properties.PipelineTriggersJobProperty>
</properties>

</flow-definition>
</code>```

Title: Jenkins pipeline BuildDiscarderProperty

Body:
Found the solution. Used General job definition at Groovy Template for pipeline. It is not breaking anything but just deleting old builds

<flow-definition>
<properties>
  <jenkins.model.BuildDiscarderProperty>
  <strategy class="hudson.tasks.LogRotator">
    <daysToKeep>365</daysToKeep>
    <numToKeep>30</numToKeep>
    <artifactDaysToKeep>-1</artifactDaysToKeep>
    <artifactNumToKeep>-1</artifactNumToKeep>
  </strategy>
  </jenkins.model.BuildDiscarderProperty>
  <org.jenkinsci.plugins.workflow.job.properties.PipelineTriggersJobProperty>
</org.jenkinsci.plugins.workflow.job.properties.PipelineTriggersJobProperty>
</properties>

</flow-definition>


问:
JavaScript: How to get string between brackets
I want to be able to get a string in between a bracket opened ( and a bracket closed ).

```<code>myString = "MT Mokwa (40,000)"
</code>```

How can I get 40,000 from the string?

答:
Both of these examples assume that the string will always have a set of parenthesis, opening before closing.

I suggest using substring and indexOf for this:

```<code>var result = myString.substring( myString.indexOf( '(' ) + 1, myString.indexOf( ')' ) );
</code>```

You can also use a regex if you prefer:

```<code>var result = /\(([^)]*)\)/.exec(myString)[1];
</code>```

Body:
I want to be able to get a string in between a bracket opened ( and a bracket closed ).

myString = "MT Mokwa (40,000)"

How can I get 40,000 from the string?

Body:
Both of these examples assume that the string will always have a set of parenthesis, opening before closing.

I suggest using substring and indexOf for this:

var result = myString.substring( myString.indexOf( '(' ) + 1, myString.indexOf( ')' ) );

You can also use a regex if you prefer:

var result = /\(([^)]*)\)/.exec(myString)[1];


问:
Assigning an integer to a character variable
I was trying to assign an integer to a char, unsigned char and signed char variables, to understand the results of the same. I am running this code on a 64 bit Mac OS. I am baffled with the response and am looking for someone to help me out with the same. I am not looking  at the sizeof result, I am only trying to understand why printing the value of variables result in weird characters.

```<code> #include<iostream>
 using namespace std;

 int main() {
     char a = 2;
     unsigned char b = 10;
     signed char c = 200;
     cout<<"Regular char variable value "<<a<<"\t"<<"size of the variable is "<<sizeof(a)<<"\n";
     cout<<"Regular char variable value "<<b<<"\t"<<"size of the variable is "<<sizeof(b)<<"\n";
     cout<<"Regular char variable value "<<c<<"\t"<<"size of the variable is "<<sizeof(c)<<"\n";

 }
</code>```

And the output of this code is following:

```<code>Regular char variable value     size of the variable is 1
Regular char variable value
                size of the variable is 1
Regular char variable value ?   size of the variable is 1
</code>```

Please note that the 2nd line in the output is garbled, which adds to the complexity of the output.

答:
It is because cout<<a tries to print a as a character instead of a number (the same for b and c).

Looking at an ASCII table

tells you that character 2 is STX, 10 is LINEFEED, and 200 is up in the non-standard special characters section, or would be. Note that you assign 200 to a signed char whose maximum value is 127, so you'll actually end up with a negative number.

Since none of these characters have visible representations on the terminal, you'll see blanks.

To print them in numerical fashion you should use, e.g.

```<code>cout<<(int)a;
</code>```

Body:
I was trying to assign an integer to a char, unsigned char and signed char variables, to understand the results of the same. I am running this code on a 64 bit Mac OS. I am baffled with the response and am looking for someone to help me out with the same. I am not looking  at the sizeof result, I am only trying to understand why printing the value of variables result in weird characters.

 #include<iostream>
 using namespace std;

 int main() {
     char a = 2;
     unsigned char b = 10;
     signed char c = 200;
     cout<<"Regular char variable value "<<a<<"\t"<<"size of the variable is "<<sizeof(a)<<"\n";
     cout<<"Regular char variable value "<<b<<"\t"<<"size of the variable is "<<sizeof(b)<<"\n";
     cout<<"Regular char variable value "<<c<<"\t"<<"size of the variable is "<<sizeof(c)<<"\n";

 }

And the output of this code is following:

Regular char variable value     size of the variable is 1
Regular char variable value
                size of the variable is 1
Regular char variable value ?   size of the variable is 1

Please note that the 2nd line in the output is garbled, which adds to the complexity of the output.

Body:
It is because cout<<a tries to print a as a character instead of a number (the same for b and c).

Looking at an ASCII table

tells you that character 2 is STX, 10 is LINEFEED, and 200 is up in the non-standard special characters section, or would be. Note that you assign 200 to a signed char whose maximum value is 127, so you'll actually end up with a negative number.

Since none of these characters have visible representations on the terminal, you'll see blanks.

To print them in numerical fashion you should use, e.g.

cout<<(int)a;


问:
How open a page on facebook lite app
I'm trying to create a Visit us on facebook thing, I want to rather open the page on facebook app (if the user have it) if don't then open on normal browser. This is my code based in @Jared Rummler answer

```<code>  private void showPage(String url) {
        Uri uri = Uri.parse(url);
        try {
            ApplicationInfo applicationInfo = getPackageManager().getApplicationInfo("com.facebook.katana", 0);
            if (applicationInfo.enabled) {
                uri = Uri.parse("fb://facewebmodal/f?href=" + url);
            }
        } catch (PackageManager.NameNotFoundException ignored) {
            try {
                ApplicationInfo applicationInfo = getPackageManager().getApplicationInfo("com.facebook.lite", 0);
                if (applicationInfo.enabled) {
                    uri = Uri.parse("fb://facewebmodal/f?href=" + url);
                }
            } catch (PackageManager.NameNotFoundException e) {
                //do nothing
            }
        }

        startActivity(new Intent(Intent.ACTION_VIEW, uri));
    }
</code>```

and to url I'm using the string:

```<code>"https://www.facebook.com/<my_page_name>"
</code>```

Ok. However it just only works to normal facebook app. Anyone know what I have to change to make it works with facebook lite app?

I'm catching the following error on logcat:

```<code>E/AndroidRuntime: FATAL EXCEPTION: main Process: com.technology.softwares.click.rs, PID: 4086                                                 android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW dat=fb://facewebmodal/f?href=https://www.facebook.com/<my_page_name>
</code>```

Thanks

答:
Try inserting
    intent.setPackage("com.facebook.mlite"); immediately before starting your
    Activity, e.g., </p>

```<code>private void showPage(String url) {
    Uri uri = Uri.parse(url);
    try {
        ApplicationInfo applicationInfo =
 getPackageManager().getApplicationInfo("com.facebook.katana", 0);
        if (applicationInfo.enabled) {
            uri = Uri.parse("fb://facewebmodal/f?href=" + url);
        }
    } catch (PackageManager.NameNotFoundException ignored) {
        try {
            ApplicationInfo applicationInfo = getPackageManager().getApplicationInfo("com.facebook.lite", 0);
            if (applicationInfo.enabled) {
                uri = Uri.parse("fb://facewebmodal/f?href=" + url);
            }
        } catch (PackageManager.NameNotFoundException e) {
            //do nothing
        }
    }
    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
    intent.setPackage("com.facebook.mlite");
    startActivity(intent);
}
</code>```

Title: How open a page on facebook lite app

Body:
I'm trying to create a Visit us on facebook thing, I want to rather open the page on facebook app (if the user have it) if don't then open on normal browser. This is my code based in @Jared Rummler answer

  private void showPage(String url) {
        Uri uri = Uri.parse(url);
        try {
            ApplicationInfo applicationInfo = getPackageManager().getApplicationInfo("com.facebook.katana", 0);
            if (applicationInfo.enabled) {
                uri = Uri.parse("fb://facewebmodal/f?href=" + url);
            }
        } catch (PackageManager.NameNotFoundException ignored) {
            try {
                ApplicationInfo applicationInfo = getPackageManager().getApplicationInfo("com.facebook.lite", 0);
                if (applicationInfo.enabled) {
                    uri = Uri.parse("fb://facewebmodal/f?href=" + url);
                }
            } catch (PackageManager.NameNotFoundException e) {
                //do nothing
            }
        }

        startActivity(new Intent(Intent.ACTION_VIEW, uri));
    }

and to url I'm using the string:

"https://www.facebook.com/<my_page_name>"

Ok. However it just only works to normal facebook app. Anyone know what I have to change to make it works with facebook lite app?

I'm catching the following error on logcat:

E/AndroidRuntime: FATAL EXCEPTION: main Process: com.technology.softwares.click.rs, PID: 4086                                                 android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW dat=fb://facewebmodal/f?href=https://www.facebook.com/<my_page_name>

Thanks

Body:
Try inserting
    intent.setPackage("com.facebook.mlite"); immediately before starting your
    Activity, e.g.,

private void showPage(String url) {
    Uri uri = Uri.parse(url);
    try {
        ApplicationInfo applicationInfo =
 getPackageManager().getApplicationInfo("com.facebook.katana", 0);
        if (applicationInfo.enabled) {
            uri = Uri.parse("fb://facewebmodal/f?href=" + url);
        }
    } catch (PackageManager.NameNotFoundException ignored) {
        try {
            ApplicationInfo applicationInfo = getPackageManager().getApplicationInfo("com.facebook.lite", 0);
            if (applicationInfo.enabled) {
                uri = Uri.parse("fb://facewebmodal/f?href=" + url);
            }
        } catch (PackageManager.NameNotFoundException e) {
            //do nothing
        }
    }
    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
    intent.setPackage("com.facebook.mlite");
    startActivity(intent);
}


问:
Send variable from one Chef recipe to another in order to trigger a resource block
In one recipe I have a rubyblock that ultimately obtains the port of a service that I'd like to restart.

Individually the recipes work fine and I am now trying to tie the two together.

I cannot seem to pass the variable to the other recipe having tried to follow a custom resource example.

my default recipe that obtains the port is:

```<code> Chef::Log.info("Port: #{port}")

 Chef::Resource::Notification.new("stop-solr_#{port}", :run, self)
</code>```

I'm trying to trigger the resource block of the name 'stop-solr_'portNumber'' using the notification sender.

My other recipe looks like the following and has a start/stop service purpose

```<code>    solrCore = "solr_#{port}"

#define the service - does nothing
service solrCore do
  action :nothing
end

#do something that triggers
execute "start-solr_#{port}" do
  Chef::Log.info('triggers start')
  action :nothing
  notifies :start, run_context.resource_collection.find(:service => "#{solrCore}")
end

execute "stop-solr_#{port}" do
  # some stuff
  # on success...
  Chef::Log.info('triggers restart')
  notifies :stop, run_context.resource_collection.find(:service => "#{solrCore}"), :immediately
  notifies :run, "execute[start-solr_#{port}]"
end
</code>```

My main problem (I think) is that the variable solrCore uses 'port' which I cannot seem to obtain.

Is anyone able to help with what I need ot do in order to get this working?

Thanks in advance.

答:
Variables in Ruby are local by default. You would have to use a global variable to share state between files, either a real Ruby global variable ($foo) or using the global node.run_state hash we expose to all recipes.

That said: there is a reason that mutable global variables have been a CS cliché for decades. Code like this is very fragile and difficult to debug. I would consider turning both of those recipes into custom resources and calling them from the same recipe with the same input port.

Body:
In one recipe I have a rubyblock that ultimately obtains the port of a service that I'd like to restart.

Individually the recipes work fine and I am now trying to tie the two together.

I cannot seem to pass the variable to the other recipe having tried to follow a custom resource example.

my default recipe that obtains the port is:

 Chef::Log.info("Port: #{port}")

 Chef::Resource::Notification.new("stop-solr_#{port}", :run, self)

I'm trying to trigger the resource block of the name 'stop-solr_'portNumber'' using the notification sender.

My other recipe looks like the following and has a start/stop service purpose

    solrCore = "solr_#{port}"

#define the service - does nothing
service solrCore do
  action :nothing
end

#do something that triggers
execute "start-solr_#{port}" do
  Chef::Log.info('triggers start')
  action :nothing
  notifies :start, run_context.resource_collection.find(:service => "#{solrCore}")
end

execute "stop-solr_#{port}" do
  # some stuff
  # on success...
  Chef::Log.info('triggers restart')
  notifies :stop, run_context.resource_collection.find(:service => "#{solrCore}"), :immediately
  notifies :run, "execute[start-solr_#{port}]"
end

My main problem (I think) is that the variable solrCore uses 'port' which I cannot seem to obtain.

Is anyone able to help with what I need ot do in order to get this working?

Thanks in advance.


问:
Java: How can I read and store them in array by a new line in ArrayList?
Here is what my .txt file looks like (but more than 100 elements per line and more than 100 lines):

```<code>-0.89094    -0.86099    -0.82438    -0.78214    -0.73573    -0.68691    -0.63754
-0.42469    -0.3924     -0.36389    -0.33906    -0.31795    -0.30056    -0.28692
</code>```

What I want to do is read this .txt file and store them in Arryalist. The problem is when I read and store this data, they put all of this in the same array (I want them to store in 2 arrays split by a line).

Here is my code:

```<code>public class ReadStore {
    public static void main(String[] args) throws IOException {

    Scanner inFile = new Scanner(new File("Untitled.txt")).useDelimiter("\\s");
    ArrayList<Float> temps = new ArrayList<Float>();

    while (inFile.hasNextFloat()) {
      // find next line
      float token = inFile.nextFloat();
      temps.add(token);

    }

    inFile1.close();

    Float [] tempsArray = temps.toArray(new Float[0]);
    for (Float s : tempsArray) {
      System.out.println(s);
    }
  }
</code>```

Any suggestion for making this works?

答:
I'm assuming that the number of floats on each line might differ from line to line. If they're all the same, I'd suggest reading them into one big list and then splitting it into sublists.

But if you want to have all the floats on a line be in a single list, it seems like the best approach is to read the file line by line. Then, split each line into tokens, convert to float, and collect the results into a list. The overall result will be a list of list of float. This is pretty easy to do with Java 8 streams:

```<code>static List<List<Float>> readData() throws IOException {
    Pattern pat = Pattern.compile("\\s+");
    try (Stream<String> allLines = Files.lines(Paths.get(filename))) {
        return allLines.map(line -> pat.splitAsStream(line)
                                       .map(Float::parseFloat)
                                       .collect(Collectors.toList()))
                       .collect(Collectors.toList());
    }
}
</code>```

Note the use of Files.lines to get a stream of lines, and also note the use of try-with-resources on the resulting stream.

If you have Java 9, you can simplify this a tiny bit by using Scanner instead of Pattern.splitAsStream to parse the tokens on each line:

```<code>static List<List<Float>> readData9() throws IOException {
    try (Stream<String> allLines = Files.lines(Paths.get(filename))) {
        return allLines.map(Scanner::new)
                       .map(sc -> sc.tokens()
                                    .map(Float::parseFloat)
                                    .collect(Collectors.toList()))
                       .collect(Collectors.toList());
    }
}
</code>```

Body:
Here is what my .txt file looks like (but more than 100 elements per line and more than 100 lines):

-0.89094    -0.86099    -0.82438    -0.78214    -0.73573    -0.68691    -0.63754
-0.42469    -0.3924     -0.36389    -0.33906    -0.31795    -0.30056    -0.28692

What I want to do is read this .txt file and store them in Arryalist. The problem is when I read and store this data, they put all of this in the same array (I want them to store in 2 arrays split by a line).

Here is my code:

public class ReadStore {
    public static void main(String[] args) throws IOException {

    Scanner inFile = new Scanner(new File("Untitled.txt")).useDelimiter("\\s");
    ArrayList<Float> temps = new ArrayList<Float>();

    while (inFile.hasNextFloat()) {
      // find next line
      float token = inFile.nextFloat();
      temps.add(token);

    }

    inFile1.close();

    Float [] tempsArray = temps.toArray(new Float[0]);
    for (Float s : tempsArray) {
      System.out.println(s);
    }
  }

Any suggestion for making this works?

Body:
I'm assuming that the number of floats on each line might differ from line to line. If they're all the same, I'd suggest reading them into one big list and then splitting it into sublists.

But if you want to have all the floats on a line be in a single list, it seems like the best approach is to read the file line by line. Then, split each line into tokens, convert to float, and collect the results into a list. The overall result will be a list of list of float. This is pretty easy to do with Java 8 streams:

static List<List<Float>> readData() throws IOException {
    Pattern pat = Pattern.compile("\\s+");
    try (Stream<String> allLines = Files.lines(Paths.get(filename))) {
        return allLines.map(line -> pat.splitAsStream(line)
                                       .map(Float::parseFloat)
                                       .collect(Collectors.toList()))
                       .collect(Collectors.toList());
    }
}

Note the use of Files.lines to get a stream of lines, and also note the use of try-with-resources on the resulting stream.

If you have Java 9, you can simplify this a tiny bit by using Scanner instead of Pattern.splitAsStream to parse the tokens on each line:

static List<List<Float>> readData9() throws IOException {
    try (Stream<String> allLines = Files.lines(Paths.get(filename))) {
        return allLines.map(Scanner::new)
                       .map(sc -> sc.tokens()
                                    .map(Float::parseFloat)
                                    .collect(Collectors.toList()))
                       .collect(Collectors.toList());
    }
}


问:
Error while doing animations on react native
I'm having problem while trying to do animations on react native
it throws an error that says I can't assign the x value. Anybody knows what can it be?

undefined is not an object (evaluating '_this.state.animateXY.xinterpolate')

```<code>  import {
  View,
  Text,
  StyleSheet,
  Animated,
  Image,
  Easing,
  TouchableHighlight,
  Dimensions,

 } from 'react-native';

const {width, height} = Dimensions.get('window');

class AddPost extends Component {
    constructor(){
        super()
        this.state ={
            animate: new Animated.Value(30),
            animateXY: new Animated.Value({x:0, y:0}),
           // radius: new Animated.Value(0)
        }
        this.animateInterpolate = this.state.animateXY.x.interpolate({
            inputRange: [0,150],
            outputRange: [1,2]
        })
    }
    componentWillMount(){
        Animated.sequence([
            Animated.timing(this.state.animateXY, {
                toValue: {x: height / 2, y: 0},
                duration:2000
            }),
            Animated.timing(this.state.animate, {
                toValue: 60,
                duration:2000
            }),
            /*Animated.timing(this.state.animate, {
                toValue: 40,
                duration:2000
            }),*/
        ]).start()
    }
    render() {
        return (
            <TouchableHighlight onPress={onPress}>
            <View style={styles.container}>
                <Animated.View style={{
                    width: this.state.animate,
                    height: this.state.animate,
                    backgroundColor: 'blue',
                    position: 'absolute',
                    top: this.state.animateX.x,
                    left: this.state.animateY.y,
                   // transform:[{scale: this.animateInterpolate}],
                    borderRadius: this.state.radius
                }}/>
            </View>
            </TouchableHighlight>
        );
    }
}
</code>```

答:
this.state.animateX is simply not declared.

You need to set animatedXY to 0 : animateX: new Animated.Value(0)

Then set your animation :

```<code>Animated.timing(this.state.animateX, {
    toValue: height/2,
    duration:2000
}),
</code>```

Then you can set the value of your X :

```<code>top: this.state.animateX
</code>```

Body:
I'm having problem while trying to do animations on react native
it throws an error that says I can't assign the x value. Anybody knows what can it be?

undefined is not an object (evaluating '_this.state.animateXY.xinterpolate')

  import {
  View,
  Text,
  StyleSheet,
  Animated,
  Image,
  Easing,
  TouchableHighlight,
  Dimensions,

 } from 'react-native';

const {width, height} = Dimensions.get('window');

class AddPost extends Component {
    constructor(){
        super()
        this.state ={
            animate: new Animated.Value(30),
            animateXY: new Animated.Value({x:0, y:0}),
           // radius: new Animated.Value(0)
        }
        this.animateInterpolate = this.state.animateXY.x.interpolate({
            inputRange: [0,150],
            outputRange: [1,2]
        })
    }
    componentWillMount(){
        Animated.sequence([
            Animated.timing(this.state.animateXY, {
                toValue: {x: height / 2, y: 0},
                duration:2000
            }),
            Animated.timing(this.state.animate, {
                toValue: 60,
                duration:2000
            }),
            /*Animated.timing(this.state.animate, {
                toValue: 40,
                duration:2000
            }),*/
        ]).start()
    }
    render() {
        return (
            <TouchableHighlight onPress={onPress}>
            <View style={styles.container}>
                <Animated.View style={{
                    width: this.state.animate,
                    height: this.state.animate,
                    backgroundColor: 'blue',
                    position: 'absolute',
                    top: this.state.animateX.x,
                    left: this.state.animateY.y,
                   // transform:[{scale: this.animateInterpolate}],
                    borderRadius: this.state.radius
                }}/>
            </View>
            </TouchableHighlight>
        );
    }
}

Body:
this.state.animateX is simply not declared.

You need to set animatedXY to 0 : animateX: new Animated.Value(0)

Then set your animation :

Animated.timing(this.state.animateX, {
    toValue: height/2,
    duration:2000
}),

Then you can set the value of your X :

top: this.state.animateX


问:
Align text underneath images in css
I'd like to make some sort of a program page for a festival. I want to create a list of images with little text underneath. I don't succeed in placing the text underneath (it always ends up next to the images instead of underneath). Can somebody help?

It should look like this:

[img1] [img2] [img3]

[text1] [text2] [text3]

[img4] [img5]

[text4] [text5]

... and so on

The size of the images is fixed, so that the rows with only 2 images are the same size as those who have 3.

This is my code in CSS thus far:

For the texts (small and big):

```<code>.prog_big{width:321px; height:434px; margin-left:30px; font-family: Lucida Sans,Calibri; font-size:16px; float:left; text-align:center}

.prog_small{width:207px; height:283px; margin-left:30px; font-family: Lucida Sans,Calibri; font-size:16px; float:left;text-align:center}
</code>```

For the images (small and big):

```<code>.poster_big{width:321px; height:434px; margin-left:30px; float:left}

.poster_small{width:207px; height:283px; margin-left:30px; float:left}
</code>```

答:
A flexbox solution:

.row {
  display: flex;
  flex-flow: row;
  justify-content: flex-start;
}

.column {
  display: flex;
  flex-flow: column;
  justify-content: flex-start;
  margin-right: 10px;
}

p {
  width: 100%;
  text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row">
  <div class="column">
    <img src="http://placehold.it/100" />
    <p>Text 1</p>
  </div>
  <div class="column">
    <img src="http://placehold.it/100" />
    <p>Text 2</p>
  </div>
</div>
<div class="row">
  <div class="column">
    <img src="http://placehold.it/60" />
    <p>Text 3</p>
  </div>
  <div class="column">
    <img src="http://placehold.it/60" />
    <p>Text 4</p>
  </div>
  <div class="column">
    <img src="http://placehold.it/60" />
    <p>Text 5</p>
  </div>
</div></code>```

Title: Align text underneath images in css

Body:
I'd like to make some sort of a program page for a festival. I want to create a list of images with little text underneath. I don't succeed in placing the text underneath (it always ends up next to the images instead of underneath). Can somebody help?

It should look like this:

[img1] [img2] [img3]

[text1] [text2] [text3]

[img4] [img5]

[text4] [text5]

... and so on

The size of the images is fixed, so that the rows with only 2 images are the same size as those who have 3.

This is my code in CSS thus far:

For the texts (small and big):

.prog_big{width:321px; height:434px; margin-left:30px; font-family: Lucida Sans,Calibri; font-size:16px; float:left; text-align:center}

.prog_small{width:207px; height:283px; margin-left:30px; font-family: Lucida Sans,Calibri; font-size:16px; float:left;text-align:center}

For the images (small and big):

.poster_big{width:321px; height:434px; margin-left:30px; float:left}

.poster_small{width:207px; height:283px; margin-left:30px; float:left}

Body:
A flexbox solution:

.row {
  display: flex;
  flex-flow: row;
  justify-content: flex-start;
}

.column {
  display: flex;
  flex-flow: column;
  justify-content: flex-start;
  margin-right: 10px;
}

p {
  width: 100%;
  text-align: center;
}

<div class="row">
  <div class="column">
    <img src="http://placehold.it/100" />
    <p>Text 1</p>
  </div>
  <div class="column">
    <img src="http://placehold.it/100" />
    <p>Text 2</p>
  </div>
</div>
<div class="row">
  <div class="column">
    <img src="http://placehold.it/60" />
    <p>Text 3</p>
  </div>
  <div class="column">
    <img src="http://placehold.it/60" />
    <p>Text 4</p>
  </div>
  <div class="column">
    <img src="http://placehold.it/60" />
    <p>Text 5</p>
  </div>
</div>


问:
Chef Users resource (check if exists?)
I know how to create a user resource:

```<code>user "random" do
  supports :manage_home => true
  comment "Random User"
  uid 1234
  gid "users"
  home "/home/random"
  shell "/bin/bash"
  password "$1$JJsvHslV$szsCjVEroftprNn4JHtDi."
end
</code>```

But I'm unsure how to use Chef to find a list of all users on a current node. I looked at inspecting node[:users] during a chef-client run, but only node[:current_user] is available to me. Is there a way, in a Chef recipe, to ask if a regular user exists?

I'm in a situation where I shouldn't/can't create users (due to company regulations, but I definitely shouldn't proceed with the installation of other things defined in my cookbook unless xyz users already exist.)

答:
I was getting the same undefined method '[]' for nil:NilClass error message as Tom Klino.  I suspect that those having trouble with coderanger's solution have disabled the passwd Ohai plugin.

It is very common for those of us with large directory environments to disable the passwd plugin in client.rb to avoid the 413 error ("Request Entity Too Large") when the client report runs.  Check /etc/chef/client.rb for:

ohai.disabled_plugins [:Passwd]

With this plugin disabled, node['etc']['passwd'] is unavailable to your recipes, hence the error.  In my environment, re-enabling the plugin fixes this error.

Title: Chef Users resource (check if exists?)

Body:
I know how to create a user resource:

user "random" do
  supports :manage_home => true
  comment "Random User"
  uid 1234
  gid "users"
  home "/home/random"
  shell "/bin/bash"
  password "$1$JJsvHslV$szsCjVEroftprNn4JHtDi."
end

But I'm unsure how to use Chef to find a list of all users on a current node. I looked at inspecting node[:users] during a chef-client run, but only node[:current_user] is available to me. Is there a way, in a Chef recipe, to ask if a regular user exists?

I'm in a situation where I shouldn't/can't create users (due to company regulations, but I definitely shouldn't proceed with the installation of other things defined in my cookbook unless xyz users already exist.)


问:
PHP Anonymous object - integer properties
I've created an anonymous object, using PDO FETCH_OBJ from my DB. I can access most properties fine using:

```<code>$myObject->name;
$myObject->age;
</code>```

etc.

But I have one field in my DB that starts with an integer. '130x90_url

When trying to access $myObject->130x90_url; I then get :

```<code>syntax error, unexpected '130' (T_LNUMBER), expecting identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$'
</code>```

I can't see anything in the manual about this, but would of thought others would of come across this issue?

答:
You might also be able to assign the property name to a variable and use that as a property.</p>

```<code>$property = "130x90_url";
$value = $myObject->$property;
</code>```

Body:
I've created an anonymous object, using PDO FETCH_OBJ from my DB. I can access most properties fine using:

$myObject->name;
$myObject->age;

etc.

But I have one field in my DB that starts with an integer. '130x90_url

When trying to access $myObject->130x90_url; I then get :

syntax error, unexpected '130' (T_LNUMBER), expecting identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$'

I can't see anything in the manual about this, but would of thought others would of come across this issue?

Body:
You might also be able to assign the property name to a variable and use that as a property.

$property = "130x90_url";
$value = $myObject->$property;


问:
Time of creation of key in redis
Suppose  I do this in redis at 13:30 20 Feb 2020,

```<code>> set foo "bar spam"
OK
</code>```

I want to get time of creation of foo. Is there something like

```<code>> gettime foo
13:30 20 Feb 2020
</code>```

?

答:
There is another, similar option to solve this, for the use case when you need timer to detect expired value without deleting the value itself:

```<code>MULTI
SET foo "bar"
SET foo:alive 1 EX 30
EXEC
</code>```

Here 30 - is a desired timeout. You can then determine whether value is still "alive" with:

```<code>EXISTS foo:alive
</code>```

Title: Time of creation of key in redis

Body:
Suppose  I do this in redis at 13:30 20 Feb 2020,

> set foo "bar spam"
OK

I want to get time of creation of foo. Is there something like

> gettime foo
13:30 20 Feb 2020

?

Body:
There is another, similar option to solve this, for the use case when you need timer to detect expired value without deleting the value itself:

MULTI
SET foo "bar"
SET foo:alive 1 EX 30
EXEC

Here 30 - is a desired timeout. You can then determine whether value is still "alive" with:

EXISTS foo:alive


问:
circleci - cannot read env variables defined inside script
I write a script for setting env variables.

```<code>export DB_HOST='127.0.0.1'
export DB_USER='ubuntu'
export DB_PWD=''
export DB_NAME='circle_test'
</code>```

My circle.yml look like this

```<code>machine:
  timezone: Asia/Taipei
  services:
    - mysql

dependencies:
  pre:
    - sudo apt-get update
    - nvm install 7.9 && npm install

test:
  pre:
    - source ./config/test_config.sh
    - sh ./config/test_config.sh
    - pwd
    - printenv
  override:
    - nvm use 7.9 && npm test
</code>```

My nodejs application cannot read the env variables and I didn't saw in the printenv also.

I don't want to write env variables directly into circle.yml file because I would like to have prod_config.sh、dev_config.sh to dynamically change.

How can I do that ?

答:
Every separate command (lines prefixed with -) is run in its own shell. This is why your environment variables, which you source, don't exists in the following commands. There's three ways I see going about this:

1) Define your environment variables in circle.yml. I know you said you don't want to do this, but this is the by far the easiest and most clear method.

2) You can prefix the lines that need the variables with the source command. For example:

```<code>test:
  override:
    - source ./config/test_config.sh; nvm use 7.9 && npm test
</code>```

3) Take advantage of multiline YAML:

```<code>test:
  override:
    - >
      source ./config/test_config.sh
      nvm use 7.9 && npm test
</code>```

4) Or place all of the commands in its on Bash file and just run that script:

```<code>test:
  override:
    - ./all-commands-script.sh
</code>```

-Ricardo N Feliciano

Developer Evangelist, CircleCI

Body:
I write a script for setting env variables.

export DB_HOST='127.0.0.1'
export DB_USER='ubuntu'
export DB_PWD=''
export DB_NAME='circle_test'

My circle.yml look like this

machine:
  timezone: Asia/Taipei
  services:
    - mysql

dependencies:
  pre:
    - sudo apt-get update
    - nvm install 7.9 && npm install

test:
  pre:
    - source ./config/test_config.sh
    - sh ./config/test_config.sh
    - pwd
    - printenv
  override:
    - nvm use 7.9 && npm test

My nodejs application cannot read the env variables and I didn't saw in the printenv also.

I don't want to write env variables directly into circle.yml file because I would like to have prod_config.sh、dev_config.sh to dynamically change.

How can I do that ?

Body:
Every separate command (lines prefixed with -) is run in its own shell. This is why your environment variables, which you source, don't exists in the following commands. There's three ways I see going about this:

1) Define your environment variables in circle.yml. I know you said you don't want to do this, but this is the by far the easiest and most clear method.

2) You can prefix the lines that need the variables with the source command. For example:

test:
  override:
    - source ./config/test_config.sh; nvm use 7.9 && npm test

3) Take advantage of multiline YAML:

test:
  override:
    - >
      source ./config/test_config.sh
      nvm use 7.9 && npm test

4) Or place all of the commands in its on Bash file and just run that script:

test:
  override:
    - ./all-commands-script.sh

-Ricardo N Feliciano

Developer Evangelist, CircleCI


问:
Linux static linking is dead?
In fact, -static gcc flag on Linux doesn't work now. Let me cite from the GNU libc FAQ:

2.22. Even statically linked programs need some shared libraries
  which is not acceptable for me. What
  can I do?

{AJ} NSS (for details just type `info
  libc "Name Service Switch"') won't
  work properly without shared
  libraries.  NSS allows using different
  services (e.g. NIS, files, db, hesiod)
  by just changing one configuration
  file (/etc/nsswitch.conf) without
  relinking any programs.  The only
  disadvantage is that now static
  libraries need to access shared
  libraries.  This is handled
  transparently by the GNU C library.

A solution is to configure glibc with
  --enable-static-nss.  In this case you can create a static binary that will
  use only the services dns and files
  (change /etc/nsswitch.conf for this).
  You need to link explicitly against
  all these services. For example:

```<code> gcc -static test-netdb.c -o test-netdb \
   -Wl,--start-group -lc -lnss_files -lnss_dns -lresolv -Wl,--end-group
</code>```

The problem with this approach is
  that you've got to link every static
  program that uses NSS routines with
  all those libraries.

  {UD} In fact, one cannot say anymore that a libc compiled with this option
  is using NSS.  There is no switch
  anymore.  Therefore it is highly
  recommended not to use
  --enable-static-nss since this makes the behaviour of the programs on the
  system inconsistent.

Concerning that fact is there any reasonable way now to create a full-functioning static build on Linux or static linking is completely dead on Linux? I mean static build which:

Behaves exactly the same way as
dynamic build do (static-nss with
inconsistent behaviour is evil!);

Works on reasonable variations of glibc environment and Linux versions;

答:
I think this is very annoying, and I think it is arrogant to call a feature "useless" because it has problems dealing with certain use cases.  The biggest problem with the glibc approach is that it hard-codes paths to system libraries (gconv as well as nss), and thus it breaks when people try to run a static binary on a Linux distribution different from the one it was built for.

Anyway, you can work around the gconv issue by setting GCONV_PATH to point to the appropriate location, this allowed me to take binaries built on Ubuntu and run them on Red Hat.

Title: Linux static linking is dead?

Body:
In fact, -static gcc flag on Linux doesn't work now. Let me cite from the GNU libc FAQ:

2.22. Even statically linked programs need some shared libraries
  which is not acceptable for me. What
  can I do?

{AJ} NSS (for details just type `info
  libc "Name Service Switch"') won't
  work properly without shared
  libraries.  NSS allows using different
  services (e.g. NIS, files, db, hesiod)
  by just changing one configuration
  file (/etc/nsswitch.conf) without
  relinking any programs.  The only
  disadvantage is that now static
  libraries need to access shared
  libraries.  This is handled
  transparently by the GNU C library.

A solution is to configure glibc with
  --enable-static-nss.  In this case you can create a static binary that will
  use only the services dns and files
  (change /etc/nsswitch.conf for this).
  You need to link explicitly against
  all these services. For example:

 gcc -static test-netdb.c -o test-netdb \
   -Wl,--start-group -lc -lnss_files -lnss_dns -lresolv -Wl,--end-group

The problem with this approach is
  that you've got to link every static
  program that uses NSS routines with
  all those libraries.

  {UD} In fact, one cannot say anymore that a libc compiled with this option
  is using NSS.  There is no switch
  anymore.  Therefore it is highly
  recommended not to use
  --enable-static-nss since this makes the behaviour of the programs on the
  system inconsistent.

Concerning that fact is there any reasonable way now to create a full-functioning static build on Linux or static linking is completely dead on Linux? I mean static build which:

Behaves exactly the same way as
dynamic build do (static-nss with
inconsistent behaviour is evil!);

Works on reasonable variations of glibc environment and Linux versions;