问:
Core Audio specify which audio track to decode
I am able to successfully get the decoded PCM data of an audio file using Core Audio API. Below is the reduced code that shows how do I do that:

```<code>CFStringRef urlStr = CFStringCreateWithCString(kCFAllocatorDefault, "file.m4a", kCFStringEncodingUTF8);
CFURLRef urlRef = CFURLCreateWithFileSystemPath(NULL, urlStr, kCFURLPOSIXPathStyle, false);

ExtAudioFileOpenURL(urlRef, &m_audioFile);

bzero(&m_outputFormat, sizeof(AudioStreamBasicDescription));
m_outputFormat.mFormatFlags = kAudioFormatFlagIsSignedInteger | kAudioFormatFlagsNativeEndian | kAudioFormatFlagIsPacked;
m_outputFormat.mSampleRate = m_inputFormat.mSampleRate;
m_outputFormat.mFormatID = kAudioFormatLinearPCM;
m_outputFormat.mChannelsPerFrame = m_inputFormat.mChannelsPerFrame;
m_outputFormat.mBytesPerFrame = sizeof(short) * m_outputFormat.mChannelsPerFrame;
m_outputFormat.mBitsPerChannel = sizeof(short) * 8;
m_outputFormat.mFramesPerPacket = 1;
m_outputFormat.mBytesPerPacket = m_outputFormat.mBytesPerFrame * m_outputFormat.mFramesPerPacket;

ExtAudioFileSetProperty(m_audioFile, kExtAudioFileProperty_ClientDataFormat, sizeof(m_outputFormat), &m_outputFormat)

short* transformData = new short[sampleCount];

AudioBufferList fillBufList;
fillBufList.mNumberBuffers = 1;
fillBufList.mBuffers[0].mNumberChannels = channels;
fillBufList.mBuffers[0].mDataByteSize = m_sampleCount * sizeof(short);
fillBufList.mBuffers[0].mData = (void*)(&transformData[0]);

ExtAudioFileRead(m_audioFile, &m_frameCount, &fillBufList);
</code>```

I am interested in how can I specify the audio track I want to decode (suppose that media file contains more than one)?

答: One method is to decode all tracks and then extract (copy) the desired track data (every other sample for interleaved stereo, etc.) into another buffer, array, or file.  Compared to the decode time, the extra copy time is insignificant.</p>

Body:
I am able to successfully get the decoded PCM data of an audio file using Core Audio API. Below is the reduced code that shows how do I do that:

CFStringRef urlStr = CFStringCreateWithCString(kCFAllocatorDefault, "file.m4a", kCFStringEncodingUTF8);
CFURLRef urlRef = CFURLCreateWithFileSystemPath(NULL, urlStr, kCFURLPOSIXPathStyle, false);

ExtAudioFileOpenURL(urlRef, &m_audioFile);

bzero(&m_outputFormat, sizeof(AudioStreamBasicDescription));
m_outputFormat.mFormatFlags = kAudioFormatFlagIsSignedInteger | kAudioFormatFlagsNativeEndian | kAudioFormatFlagIsPacked;
m_outputFormat.mSampleRate = m_inputFormat.mSampleRate;
m_outputFormat.mFormatID = kAudioFormatLinearPCM;
m_outputFormat.mChannelsPerFrame = m_inputFormat.mChannelsPerFrame;
m_outputFormat.mBytesPerFrame = sizeof(short) * m_outputFormat.mChannelsPerFrame;
m_outputFormat.mBitsPerChannel = sizeof(short) * 8;
m_outputFormat.mFramesPerPacket = 1;
m_outputFormat.mBytesPerPacket = m_outputFormat.mBytesPerFrame * m_outputFormat.mFramesPerPacket;

ExtAudioFileSetProperty(m_audioFile, kExtAudioFileProperty_ClientDataFormat, sizeof(m_outputFormat), &m_outputFormat)

short* transformData = new short[sampleCount];

AudioBufferList fillBufList;
fillBufList.mNumberBuffers = 1;
fillBufList.mBuffers[0].mNumberChannels = channels;
fillBufList.mBuffers[0].mDataByteSize = m_sampleCount * sizeof(short);
fillBufList.mBuffers[0].mData = (void*)(&transformData[0]);

ExtAudioFileRead(m_audioFile, &m_frameCount, &fillBufList);

I am interested in how can I specify the audio track I want to decode (suppose that media file contains more than one)?


来源: stackexchange

问:
CSS overriding subsequent attributes
Say I have a div for the main body text of a webpage, and a navigation div for links to the rest of the website. Now say I want the links in the body text to be green instead of the usual blue, but I want the links in the navigation div to be yet another color, perhaps red. If I make links green in CSS, then all the links will be green. If I make the text in the navigation div red with CSS, the link attributes seem to override the div's attributes for links in the navigation div. How can I target only certain links when no links have any classes attached to them?

答:
Use descendant selectors.

Style regular links, then only links within the #nav div:

```<code>a:link { color: blue;
    }
a:visited { color: purple;
    }

.navigation a:link, .navigation a:visited { color: green
    }
</code>```

ContentLicense: CC BY-SA 2.5

Title: CSS overriding subsequent attributes

Body:
Use descendant selectors.

Style regular links, then only links within the #nav div:

a:link { color: blue;
    }
a:visited { color: purple;
    }

.navigation a:link, .navigation a:visited { color: green
    }


问:
Can you use auto with a comma
Can you use an auto deduced type where you have a comma to indicate initialization of two or more variables. Like this:

```<code> auto p = c.begin(), e = c.end();
</code>```

Or is the presence of two initializations  (potentially) too confusing for a compiler? What does the C++ standard allow?

答: Yes you can initialize them that way as long as they are of the same type (which they are in your example).</p>

ContentLicense: CC BY-SA 4.0

Title: Can you use auto with a comma

Body:
Can you use an auto deduced type where you have a comma to indicate initialization of two or more variables. Like this:

 auto p = c.begin(), e = c.end();

Or is the presence of two initializations  (potentially) too confusing for a compiler? What does the C++ standard allow?

ContentLicense: CC BY-SA 3.0


问:
How can I call a function before it is defined?
I have an AJAX call placed inside a function, which is called through PHP when there is an error (such as an input field is empty) to display a notification to the user, however I am receiving this error:

Uncaught ReferenceError: sendnotification is not defined

I know why this is... but I don't know how to fix it. It is because I am calling a function which has not yet been defined. Here is an extremely cut-down version of two of my files:

index.php:

```<code><?php

include('con.php'); // the file which connects to the database

echo'<script>sendnotification();</script>'; // calls the function which is in footer.php

include('header.php'); // the file which contains the document headers and imports the jQuery and other libraries

include('footer.php');

?>
</code>```

I cannot place the echo line after I import header.php because it is inside a function which validates a form and other if statements will cause a 'headers already sent' error.

footer.php:

```<code><script>
function sendnotification() {
   // do something
}
</script>
</code>```

答:
echo''; will immediately call the send notification function. However, since you defined the function in the footer, it will throw an error, since the footer hasn't loaded yet.

To fix this, put the

```<code><script>
function sendnotification() {
   // do something
}
</script>
</code>```

Somewhere above the

Or, you could check if the document is ready.

```<code><script>
function sendnotification() {
    let interval = setInterval(() => {
        if (document.readyState === "complete") {
            clearInterval(interval);
            // do something
        }
     }, 100);
}
</script>
</code>```

OwnerDisplayName: anon

LastEditorDisplayName: anon

Body:
I have an AJAX call placed inside a function, which is called through PHP when there is an error (such as an input field is empty) to display a notification to the user, however I am receiving this error:

Uncaught ReferenceError: sendnotification is not defined

I know why this is... but I don't know how to fix it. It is because I am calling a function which has not yet been defined. Here is an extremely cut-down version of two of my files:

index.php:

<?php

include('con.php'); // the file which connects to the database

echo''; // calls the function which is in footer.php

include('header.php'); // the file which contains the document headers and imports the jQuery and other libraries

include('footer.php');

?>

I cannot place the echo line after I import header.php because it is inside a function which validates a form and other if statements will cause a 'headers already sent' error.

footer.php:

Body:
echo'<script>sendnotification();</script>'; will immediately call the send notification function. However, since you defined the function in the footer, it will throw an error, since the footer hasn't loaded yet.

To fix this, put the

<script>
function sendnotification() {
   // do something
}
</script>

Somewhere above the <script>sendnotification();</script>

Or, you could check if the document is ready.

<script>
function sendnotification() {
    let interval = setInterval(() => {
        if (document.readyState === "complete") {
            clearInterval(interval);
            // do something
        }
     }, 100);
}
</script>


问:
creating scratch card android
I'm trying to implement a simple "scratch card". The java code is taken by an android demo about painting (WHERE to find Android "Fingerpaint" demo? (Android Studio era)) and what i want is simply to show the image below the surfaceview.

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">

 <ImageView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:src="@drawable/android"
    android:scaleType="fitXY"
    />

<com.example.jammtup.ErasableView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    /></RelativeLayout>
</code>```

the java code :

```<code>public class ErasableView extends SurfaceView {

private Bitmap mBitmap;
private Canvas mCanvas;
private Paint mPaint;
private Path mPath;
private Paint mBitmapPaint;

public ErasableView(Context context) {
    super(context);
    mPaint = new Paint();
    mPath = new Path();
    mBitmapPaint = new Paint(Paint.DITHER_FLAG);
}

public void init() {

    setFocusableInTouchMode(true);

    mPaint.setAntiAlias(true);
    mPaint.setDither(true);
    mPaint.setColor(Color.TRANSPARENT);
    mPaint.setStyle(Paint.Style.STROKE);
    mPaint.setStrokeWidth(64);
    mPaint.setColor(0xFFFF0000);
    mPaint.setStrokeCap(Paint.Cap.ROUND);
    mPaint.setStrokeJoin(Paint.Join.ROUND);
    mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));

}

@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    super.onSizeChanged(w, h, oldw, oldh);
    mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
    mCanvas = new Canvas(mBitmap);

}

@Override
protected void onDraw(Canvas canvas) {

    canvas.drawColor(Color.TRANSPARENT);
    canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
    canvas.drawPath(mPath, mPaint);
}

private float mX, mY;
private static final float TOUCH_TOLERANCE = 4;

private void touch_start(float x, float y) {
    mPath.reset();
    mPath.moveTo(x, y);
    mX = x;
    mY = y;
}

private void touch_move(float x, float y) {
    float dx = Math.abs(x - mX);
    float dy = Math.abs(y - mY);
    if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
        mPath.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2);
        mX = x;
        mY = y;
    }
}

private void touch_up() {
    mPath.lineTo(mX, mY);
    // commit the path to our offscreen
    mCanvas.drawPath(mPath, mPaint);
    // kill this so we don't double draw
    mPath.reset();
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    float x = event.getX();
    float y = event.getY();

    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            touch_start(x, y);
            invalidate();
            break;
        case MotionEvent.ACTION_MOVE:
            touch_move(x, y);
            invalidate();
            break;
        case MotionEvent.ACTION_UP:
            touch_up();
            invalidate();
            break;
    }
    return true;
} }
</code>```

what i get is a black view not erasable. That does not allow to show the image below.

i need your help !!

答:
Try to use this instead of your view If you want the whole project just check out my Github repository https://github.com/amarvadla/ScratchCoupon

```<code>    import android.content.Context;
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.graphics.Canvas;
    import android.graphics.Paint;
    import android.graphics.Path;
    import android.graphics.PorterDuff;
    import android.graphics.PorterDuffXfermode;
    import android.graphics.Rect;
    import android.graphics.drawable.BitmapDrawable;
    import android.os.AsyncTask;
    import android.support.v4.content.ContextCompat;
    import android.text.TextPaint;
    import android.util.AttributeSet;
    import android.view.Gravity;
    import android.view.MotionEvent;
    import android.widget.TextView;
</code>```

public class ScratchTextView extends TextView {

```<code>Bitmap scratchBitmap;
public interface IRevealListener {
    public void onRevealed(ScratchTextView tv);
    public void onRevealPercentChangedListener(ScratchTextView stv, float percent);
}

public static final float STROKE_WIDTH = 12f;

private float mX, mY;
private static final float TOUCH_TOLERANCE = 4;

/**
 * Bitmap holding the scratch region.
 */
private Bitmap mScratchBitmap;

/**
 * Drawable canvas area through which the scratchable area is drawn.
 */
public static Canvas mCanvas;

/**
 * Path holding the erasing path done by the user.
 */
private Path mErasePath;

/**
 * Path to indicate where the user have touched.
 */
private Path mTouchPath;

/**
 * Paint properties for drawing the scratch area.
 */
private Paint mBitmapPaint;

/**
 * Paint properties for erasing the scratch region.
 */
private Paint mErasePaint;

/**
 * Gradient paint properties that lies as a background for scratch region.
 */
private Paint mGradientBgPaint;

/**
 * Sample Drawable bitmap having the scratch pattern.
 */
private BitmapDrawable mDrawable;

/**
 * Listener object callback reference to send back the callback when the text has been revealed.
 */
private IRevealListener mRevealListener;

/**
 * Reveal percent value.
 */
private float mRevealPercent;

/**
 * Thread Count
 */
private int mThreadCount = 0;

public ScratchTextView(Context context) {
    super(context);
    init();

}

public ScratchTextView(Context context, AttributeSet set) {
    super(context, set);
    init();
}

public ScratchTextView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    init();
}

/**
 * Set the strokes width based on the parameter multiplier.
 * @param multiplier can be 1,2,3 and so on to set the stroke width of the paint.
 */
public void setStrokeWidth(int multiplier) {
    mErasePaint.setStrokeWidth(multiplier * STROKE_WIDTH);
}

/**
 * Initialises the paint drawing elements.
 */
private void init() {

    mTouchPath = new Path();

    mErasePaint = new Paint();
    mErasePaint.setAntiAlias(true);
    mErasePaint.setDither(true);
    mErasePaint.setColor(0xFFFF0000);
    mErasePaint.setStyle(Paint.Style.STROKE);
    mErasePaint.setStrokeJoin(Paint.Join.BEVEL);
    mErasePaint.setStrokeCap(Paint.Cap.ROUND);
    mErasePaint.setXfermode(new PorterDuffXfermode(
            PorterDuff.Mode.CLEAR));
    setStrokeWidth(6);

    mGradientBgPaint = new Paint();

    mErasePath = new Path();
    mBitmapPaint = new Paint(Paint.DITHER_FLAG);

    scratchBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.spiderman);
    mDrawable = new BitmapDrawable(getResources(), scratchBitmap);

}

@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    super.onSizeChanged(w, h, oldw, oldh);
    mScratchBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
    mCanvas = new Canvas(mScratchBitmap);

    Rect rect = new Rect(0, 0, mScratchBitmap.getWidth(), mScratchBitmap.getHeight());
    mDrawable.setBounds(rect);

    int startGradientColor = ContextCompat.getColor(getContext(), R.color.colorPrimary);
    int endGradientColor = ContextCompat.getColor(getContext(), R.color.colorAccent);

    mCanvas.drawRect(rect, mGradientBgPaint);
    mDrawable.draw(mCanvas);
}

@Override
protected void onDraw(Canvas canvas) {

    super.onDraw(canvas);
    canvas.drawBitmap(mScratchBitmap, 0, 0, mBitmapPaint);
    canvas.drawPath(mErasePath, mErasePaint);

}

private void touch_start(float x, float y) {
    mErasePath.reset();
    mErasePath.moveTo(x, y);
    mX = x;
    mY = y;
}

private void touch_move(float x, float y) {

    float dx = Math.abs(x - mX);
    float dy = Math.abs(y - mY);
    if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
        mErasePath.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2);
        mX = x;
        mY = y;

        drawPath();
    }

    mTouchPath.reset();
    mTouchPath.addCircle(mX, mY, 30, Path.Direction.CW);

}

private void drawPath() {
    mErasePath.lineTo(mX, mY);
    // commit the path to our offscreen
    mCanvas.drawPath(mErasePath, mErasePaint);
    // kill this so we don't double draw
    mTouchPath.reset();
    mErasePath.reset();
    mErasePath.moveTo(mX, mY);

    checkRevealed();
}

/**
 * Reveals the hidden text by erasing the scratch area.
 */
public void reveal() {

    int[] bounds = getTextBounds(1.5f);
    int left = bounds[0];
    int top = bounds[1];
    int right = bounds[2];
    int bottom = bounds[3];

    Paint paint = new Paint();
    paint.setXfermode(new PorterDuffXfermode(
            PorterDuff.Mode.CLEAR));

    mCanvas.drawRect(left, top, right, bottom, paint);
    checkRevealed();
    invalidate();
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    float x = event.getX();
    float y = event.getY();

    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            touch_start(x, y);
            invalidate();
            break;
        case MotionEvent.ACTION_MOVE:
            touch_move(x, y);
            invalidate();
            break;
        case MotionEvent.ACTION_UP:
            drawPath();
            invalidate();
            break;
        default:
            break;
    }
    return true;
}

public int getColor() {
    return mErasePaint.getColor();
}

public void setRevealListener(IRevealListener listener) {
    this.mRevealListener = listener;
}

public boolean isRevealed() {
    return mRevealPercent == 1;
}

private void checkRevealed() {

    if(! isRevealed() && mRevealListener != null) {

        int[] bounds = getTextBounds();
        int left = bounds[0];
        int top = bounds[1];
        int width = bounds[2] - left;
        int height = bounds[3] - top;

        // Do not create multiple calls to compare.
        if(mThreadCount > 1) {
            return;
        }

        mThreadCount++;

        new AsyncTask<Integer, Void, Float>() {

            @Override
            protected Float doInBackground(Integer... params) {

                try {
                    int left = params[0];
                    int top = params[1];
                    int width = params[2];
                    int height = params[3];

                    Bitmap croppedBitmap = Bitmap.createBitmap(mScratchBitmap, left, top, width, height);

                    return BitmapUtils.getTransparentPixelPercent(croppedBitmap);
                } finally {
                    mThreadCount--;

                }
            }

            public void onPostExecute(Float percentRevealed) {

                // check if not revealed before.
                if( ! isRevealed()) {

                    float oldValue = mRevealPercent;
                    mRevealPercent = percentRevealed;

                    if(oldValue != percentRevealed) {
                        mRevealListener.onRevealPercentChangedListener(ScratchTextView.this, percentRevealed);
                    }

                    // if now revealed.
                    if( isRevealed()) {
                        mRevealListener.onRevealed(ScratchTextView.this);
                    }
                }
            }
        }.execute(left, top, width, height);

    }
}

private static int[] getTextDimens(String text, Paint paint) {

    int end = text.length();
    Rect bounds = new Rect();
    paint.getTextBounds(text, 0, end, bounds);
    int width = bounds.left + bounds.width();
    int height = bounds.bottom + bounds.height();

    return new int[] { width, height};
}

private int[] getTextBounds() {
    return getTextBounds(1f);
}

private int[] getTextBounds(float scale) {

    int paddingLeft = getPaddingLeft();
    int paddingTop = getPaddingTop();
    int paddingRight = getPaddingRight();
    int paddingBottom = getPaddingBottom();

    int vwidth = getWidth();
    int vheight = getHeight();

    int centerX = vwidth/2;
    int centerY = vheight/2;

    TextPaint paint = getPaint();

    String text = getText().toString();

    int[] dimens = getTextDimens(text, paint);
    int width = dimens[0];
    int height = dimens[1];

    int lines = getLineCount();
    height = height * lines;
    width = width / lines;

    int left = 0;
    int top = 0;

    if(height > vheight) {
        height = vheight - ( paddingBottom + paddingTop);
    }
    else {
        height = (int) (height * scale);
    }

    if(width > vwidth) {
        width = vwidth - (paddingLeft + paddingRight);
    }
    else {
        width = (int) (width * scale);
    }

    int gravity = getGravity();

    //todo Gravity.START
    if((gravity & Gravity.LEFT) == Gravity.LEFT) {
        left = paddingLeft;
    }
    //todo Gravity.END
    else if((gravity & Gravity.RIGHT) == Gravity.RIGHT) {
        left = (vwidth - paddingRight) - width;
    }
    else if((gravity & Gravity.CENTER_HORIZONTAL) == Gravity.CENTER_HORIZONTAL) {
        left = centerX - width / 2;
    }

    if((gravity & Gravity.TOP) == Gravity.TOP) {
        top = paddingTop;
    }
    else if((gravity & Gravity.BOTTOM) == Gravity.BOTTOM) {
        top = (vheight - paddingBottom) - height;
    }

    else if((gravity & Gravity.CENTER_VERTICAL) == Gravity.CENTER_VERTICAL) {
        top = centerY - height / 2;
    }

    return new int[] {left, top, left + width, top + height};
}
</code>```

Title: creating scratch card android

Body:
I'm trying to implement a simple "scratch card". The java code is taken by an android demo about painting (WHERE to find Android "Fingerpaint" demo? (Android Studio era)) and what i want is simply to show the image below the surfaceview.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">

 <ImageView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:src="@drawable/android"
    android:scaleType="fitXY"
    />

<com.example.jammtup.ErasableView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    /></RelativeLayout>

the java code :

public class ErasableView extends SurfaceView {

private Bitmap mBitmap;
private Canvas mCanvas;
private Paint mPaint;
private Path mPath;
private Paint mBitmapPaint;

public ErasableView(Context context) {
    super(context);
    mPaint = new Paint();
    mPath = new Path();
    mBitmapPaint = new Paint(Paint.DITHER_FLAG);
}

public void init() {

    setFocusableInTouchMode(true);

    mPaint.setAntiAlias(true);
    mPaint.setDither(true);
    mPaint.setColor(Color.TRANSPARENT);
    mPaint.setStyle(Paint.Style.STROKE);
    mPaint.setStrokeWidth(64);
    mPaint.setColor(0xFFFF0000);
    mPaint.setStrokeCap(Paint.Cap.ROUND);
    mPaint.setStrokeJoin(Paint.Join.ROUND);
    mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));

}

@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    super.onSizeChanged(w, h, oldw, oldh);
    mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
    mCanvas = new Canvas(mBitmap);

}

@Override
protected void onDraw(Canvas canvas) {

    canvas.drawColor(Color.TRANSPARENT);
    canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
    canvas.drawPath(mPath, mPaint);
}

private float mX, mY;
private static final float TOUCH_TOLERANCE = 4;

private void touch_start(float x, float y) {
    mPath.reset();
    mPath.moveTo(x, y);
    mX = x;
    mY = y;
}

private void touch_move(float x, float y) {
    float dx = Math.abs(x - mX);
    float dy = Math.abs(y - mY);
    if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
        mPath.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2);
        mX = x;
        mY = y;
    }
}

private void touch_up() {
    mPath.lineTo(mX, mY);
    // commit the path to our offscreen
    mCanvas.drawPath(mPath, mPaint);
    // kill this so we don't double draw
    mPath.reset();
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    float x = event.getX();
    float y = event.getY();

    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            touch_start(x, y);
            invalidate();
            break;
        case MotionEvent.ACTION_MOVE:
            touch_move(x, y);
            invalidate();
            break;
        case MotionEvent.ACTION_UP:
            touch_up();
            invalidate();
            break;
    }
    return true;
} }

what i get is a black view not erasable. That does not allow to show the image below.

i need your help !!

Body:
Try to use this instead of your view If you want the whole project just check out my Github repository https://github.com/amarvadla/ScratchCoupon

    import android.content.Context;
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.graphics.Canvas;
    import android.graphics.Paint;
    import android.graphics.Path;
    import android.graphics.PorterDuff;
    import android.graphics.PorterDuffXfermode;
    import android.graphics.Rect;
    import android.graphics.drawable.BitmapDrawable;
    import android.os.AsyncTask;
    import android.support.v4.content.ContextCompat;
    import android.text.TextPaint;
    import android.util.AttributeSet;
    import android.view.Gravity;
    import android.view.MotionEvent;
    import android.widget.TextView;

public class ScratchTextView extends TextView {

Bitmap scratchBitmap;
public interface IRevealListener {
    public void onRevealed(ScratchTextView tv);
    public void onRevealPercentChangedListener(ScratchTextView stv, float percent);
}

public static final float STROKE_WIDTH = 12f;

private float mX, mY;
private static final float TOUCH_TOLERANCE = 4;

/**
 * Bitmap holding the scratch region.
 */
private Bitmap mScratchBitmap;

/**
 * Drawable canvas area through which the scratchable area is drawn.
 */
public static Canvas mCanvas;

/**
 * Path holding the erasing path done by the user.
 */
private Path mErasePath;

/**
 * Path to indicate where the user have touched.
 */
private Path mTouchPath;

/**
 * Paint properties for drawing the scratch area.
 */
private Paint mBitmapPaint;

/**
 * Paint properties for erasing the scratch region.
 */
private Paint mErasePaint;

/**
 * Gradient paint properties that lies as a background for scratch region.
 */
private Paint mGradientBgPaint;

/**
 * Sample Drawable bitmap having the scratch pattern.
 */
private BitmapDrawable mDrawable;

/**
 * Listener object callback reference to send back the callback when the text has been revealed.
 */
private IRevealListener mRevealListener;

/**
 * Reveal percent value.
 */
private float mRevealPercent;

/**
 * Thread Count
 */
private int mThreadCount = 0;

public ScratchTextView(Context context) {
    super(context);
    init();

}

public ScratchTextView(Context context, AttributeSet set) {
    super(context, set);
    init();
}

public ScratchTextView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    init();
}

/**
 * Set the strokes width based on the parameter multiplier.
 * @param multiplier can be 1,2,3 and so on to set the stroke width of the paint.
 */
public void setStrokeWidth(int multiplier) {
    mErasePaint.setStrokeWidth(multiplier * STROKE_WIDTH);
}

/**
 * Initialises the paint drawing elements.
 */
private void init() {

    mTouchPath = new Path();

    mErasePaint = new Paint();
    mErasePaint.setAntiAlias(true);
    mErasePaint.setDither(true);
    mErasePaint.setColor(0xFFFF0000);
    mErasePaint.setStyle(Paint.Style.STROKE);
    mErasePaint.setStrokeJoin(Paint.Join.BEVEL);
    mErasePaint.setStrokeCap(Paint.Cap.ROUND);
    mErasePaint.setXfermode(new PorterDuffXfermode(
            PorterDuff.Mode.CLEAR));
    setStrokeWidth(6);

    mGradientBgPaint = new Paint();

    mErasePath = new Path();
    mBitmapPaint = new Paint(Paint.DITHER_FLAG);

    scratchBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.spiderman);
    mDrawable = new BitmapDrawable(getResources(), scratchBitmap);

}

@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    super.onSizeChanged(w, h, oldw, oldh);
    mScratchBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
    mCanvas = new Canvas(mScratchBitmap);

    Rect rect = new Rect(0, 0, mScratchBitmap.getWidth(), mScratchBitmap.getHeight());
    mDrawable.setBounds(rect);

    int startGradientColor = ContextCompat.getColor(getContext(), R.color.colorPrimary);
    int endGradientColor = ContextCompat.getColor(getContext(), R.color.colorAccent);

    mCanvas.drawRect(rect, mGradientBgPaint);
    mDrawable.draw(mCanvas);
}

@Override
protected void onDraw(Canvas canvas) {

    super.onDraw(canvas);
    canvas.drawBitmap(mScratchBitmap, 0, 0, mBitmapPaint);
    canvas.drawPath(mErasePath, mErasePaint);

}

private void touch_start(float x, float y) {
    mErasePath.reset();
    mErasePath.moveTo(x, y);
    mX = x;
    mY = y;
}

private void touch_move(float x, float y) {

    float dx = Math.abs(x - mX);
    float dy = Math.abs(y - mY);
    if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
        mErasePath.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2);
        mX = x;
        mY = y;

        drawPath();
    }

    mTouchPath.reset();
    mTouchPath.addCircle(mX, mY, 30, Path.Direction.CW);

}

private void drawPath() {
    mErasePath.lineTo(mX, mY);
    // commit the path to our offscreen
    mCanvas.drawPath(mErasePath, mErasePaint);
    // kill this so we don't double draw
    mTouchPath.reset();
    mErasePath.reset();
    mErasePath.moveTo(mX, mY);

    checkRevealed();
}

/**
 * Reveals the hidden text by erasing the scratch area.
 */
public void reveal() {

    int[] bounds = getTextBounds(1.5f);
    int left = bounds[0];
    int top = bounds[1];
    int right = bounds[2];
    int bottom = bounds[3];

    Paint paint = new Paint();
    paint.setXfermode(new PorterDuffXfermode(
            PorterDuff.Mode.CLEAR));

    mCanvas.drawRect(left, top, right, bottom, paint);
    checkRevealed();
    invalidate();
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    float x = event.getX();
    float y = event.getY();

    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            touch_start(x, y);
            invalidate();
            break;
        case MotionEvent.ACTION_MOVE:
            touch_move(x, y);
            invalidate();
            break;
        case MotionEvent.ACTION_UP:
            drawPath();
            invalidate();
            break;
        default:
            break;
    }
    return true;
}

public int getColor() {
    return mErasePaint.getColor();
}

public void setRevealListener(IRevealListener listener) {
    this.mRevealListener = listener;
}

public boolean isRevealed() {
    return mRevealPercent == 1;
}

private void checkRevealed() {

    if(! isRevealed() && mRevealListener != null) {

        int[] bounds = getTextBounds();
        int left = bounds[0];
        int top = bounds[1];
        int width = bounds[2] - left;
        int height = bounds[3] - top;

        // Do not create multiple calls to compare.
        if(mThreadCount > 1) {
            return;
        }

        mThreadCount++;

        new AsyncTask<Integer, Void, Float>() {

            @Override
            protected Float doInBackground(Integer... params) {

                try {
                    int left = params[0];
                    int top = params[1];
                    int width = params[2];
                    int height = params[3];

                    Bitmap croppedBitmap = Bitmap.createBitmap(mScratchBitmap, left, top, width, height);

                    return BitmapUtils.getTransparentPixelPercent(croppedBitmap);
                } finally {
                    mThreadCount--;

                }
            }

            public void onPostExecute(Float percentRevealed) {

                // check if not revealed before.
                if( ! isRevealed()) {

                    float oldValue = mRevealPercent;
                    mRevealPercent = percentRevealed;

                    if(oldValue != percentRevealed) {
                        mRevealListener.onRevealPercentChangedListener(ScratchTextView.this, percentRevealed);
                    }

                    // if now revealed.
                    if( isRevealed()) {
                        mRevealListener.onRevealed(ScratchTextView.this);
                    }
                }
            }
        }.execute(left, top, width, height);

    }
}

private static int[] getTextDimens(String text, Paint paint) {

    int end = text.length();
    Rect bounds = new Rect();
    paint.getTextBounds(text, 0, end, bounds);
    int width = bounds.left + bounds.width();
    int height = bounds.bottom + bounds.height();

    return new int[] { width, height};
}

private int[] getTextBounds() {
    return getTextBounds(1f);
}

private int[] getTextBounds(float scale) {

    int paddingLeft = getPaddingLeft();
    int paddingTop = getPaddingTop();
    int paddingRight = getPaddingRight();
    int paddingBottom = getPaddingBottom();

    int vwidth = getWidth();
    int vheight = getHeight();

    int centerX = vwidth/2;
    int centerY = vheight/2;

    TextPaint paint = getPaint();

    String text = getText().toString();

    int[] dimens = getTextDimens(text, paint);
    int width = dimens[0];
    int height = dimens[1];

    int lines = getLineCount();
    height = height * lines;
    width = width / lines;

    int left = 0;
    int top = 0;

    if(height > vheight) {
        height = vheight - ( paddingBottom + paddingTop);
    }
    else {
        height = (int) (height * scale);
    }

    if(width > vwidth) {
        width = vwidth - (paddingLeft + paddingRight);
    }
    else {
        width = (int) (width * scale);
    }

    int gravity = getGravity();

    //todo Gravity.START
    if((gravity & Gravity.LEFT) == Gravity.LEFT) {
        left = paddingLeft;
    }
    //todo Gravity.END
    else if((gravity & Gravity.RIGHT) == Gravity.RIGHT) {
        left = (vwidth - paddingRight) - width;
    }
    else if((gravity & Gravity.CENTER_HORIZONTAL) == Gravity.CENTER_HORIZONTAL) {
        left = centerX - width / 2;
    }

    if((gravity & Gravity.TOP) == Gravity.TOP) {
        top = paddingTop;
    }
    else if((gravity & Gravity.BOTTOM) == Gravity.BOTTOM) {
        top = (vheight - paddingBottom) - height;
    }

    else if((gravity & Gravity.CENTER_VERTICAL) == Gravity.CENTER_VERTICAL) {
        top = centerY - height / 2;
    }

    return new int[] {left, top, left + width, top + height};
}


问:
blinking an led using timer interrupt (atmega 128)
I'm trying to blink an led without using the delay function.
I came across using the timer interrupt and I tried it, and it compiles fine. But the output is fixed on PORTA = 0x01; so, I believe the ISR function is not working. Is there anything I am missing in the code? Thanks.</p>

```<code>#include <asf.h>
#include <avr/interrupt.h>

volatile unsigned int count=0;
volatile unsigned int tTime=0;

void port_init(void) {
    PORTA = 0xff;
}

ISR(TIMER0_OVF_vect)
{
    TCNT0 = 206;
    count++;
    if (count < 625) {
        PORTA=0x01;
    }
    else if ((count > 625) && (count < 1250)) {
        PORTA=0x00;
    }
    else {
        count=0;
    }
}

int main (void)
{
    board_init();
    port_init();

    TCCR0 = 0x06; //setting dispensing ratio
    TCNT0 = 206; //initial value of register
    TIMSK = 0x01; //enabling interrupt
    SREG=0x80;

    DDRA=0xff;
    while(1){
    }
}
</code>```

答:
You have a logic error in your ISR() function.  Once count hits 625 the first two if/else-if clauses will be false (because 625 is neither less than, nor greater than, 625), thus the final else clause will execute and reset count to zero.  The result of this is that the else-if clause that sets PORTA=0x00 will never execute.

To fix, change the first if from < to <=, like so:

```<code>if (count <= 625) {
</code>```

Body:
I'm trying to blink an led without using the delay function.
I came across using the timer interrupt and I tried it, and it compiles fine. But the output is fixed on PORTA = 0x01; so, I believe the ISR function is not working. Is there anything I am missing in the code? Thanks.

#include <asf.h>
#include <avr/interrupt.h>

volatile unsigned int count=0;
volatile unsigned int tTime=0;

void port_init(void) {
    PORTA = 0xff;
}

ISR(TIMER0_OVF_vect)
{
    TCNT0 = 206;
    count++;
    if (count < 625) {
        PORTA=0x01;
    }
    else if ((count > 625) && (count < 1250)) {
        PORTA=0x00;
    }
    else {
        count=0;
    }
}

int main (void)
{
    board_init();
    port_init();

    TCCR0 = 0x06; //setting dispensing ratio
    TCNT0 = 206; //initial value of register
    TIMSK = 0x01; //enabling interrupt
    SREG=0x80;

    DDRA=0xff;
    while(1){
    }
}

Body:
You have a logic error in your ISR() function.  Once count hits 625 the first two if/else-if clauses will be false (because 625 is neither less than, nor greater than, 625), thus the final else clause will execute and reset count to zero.  The result of this is that the else-if clause that sets PORTA=0x00 will never execute.

To fix, change the first if from < to <=, like so:

if (count <= 625) {


问:
Attempted to load class "Memcached" from the global namespace. Did you forget a "use" statement?
I have setup existing symfony project to my local machine(windows). After composer install i get a error like this .

ClassNotFoundException in Memcached.php line 6:

Attempted to load class "Memcached" from the global namespace.
Did you forget a "use" statement?

答:
Without detailed look into your configuration, I can only offer you a checklist with which you could give it a shot and see which part is missing.

The quesiton is tagged under symfony, so I assume that you installed a bundle. Was it leaseweb/memcache-bundle, or was some other?

Try examinging your vendor directory and try to identify if you have any of Memcached related classes.

If question to (1) is false, you may be missing some psr-4 mappings. Try examining your autoload.php and look for Memcached specific namespace.

Do you actually have php-memcached php extension installed? Have you enabled it? Try running php -m and look for php-memcached or something like that.

Please provide more info and we might be able to narrow it down.

Hope this helps.


问:
Javascript timestamp to relative time
I'm looking for a nice JS snippet to convert a timestamp (e.g. from Twitter API) to a nice user friendly relative time (e.g. 2 seconds ago, one week ago etc).

Anyone care to share some of their favourite methods (preferably not using plugins)?

答:
You can use machinepack-datetime for this purpose. It is easy and clear with its defined API.</p>

```<code>tutorialSchema.virtual('createdOn').get(function () {
    const DateTime = require('machinepack-datetime');
    let timeAgoString = "";
    try {
        timeAgoString = DateTime.timeFrom({
            toWhen: DateTime.parse({
                datetime: this.createdAt
            }).execSync(),
            fromWhen: new Date().getTime()
        }).execSync();
    } catch(err) {
        console.log('error getting createdon', err);
    }
    return timeAgoString; // a second ago
});
</code>```

Title: Javascript timestamp to relative time

Body:
You can use machinepack-datetime for this purpose. It is easy and clear with its defined API.

tutorialSchema.virtual('createdOn').get(function () {
    const DateTime = require('machinepack-datetime');
    let timeAgoString = "";
    try {
        timeAgoString = DateTime.timeFrom({
            toWhen: DateTime.parse({
                datetime: this.createdAt
            }).execSync(),
            fromWhen: new Date().getTime()
        }).execSync();
    } catch(err) {
        console.log('error getting createdon', err);
    }
    return timeAgoString; // a second ago
});


问:
How do use PHP file_get_contents or cURL with a log-in page that I'm already logged into
If I go to a website, example.com/page1.php, it is a log-in page.  When I log-in, it takes me to example.com/page2.php.  If I close my browser and come back to page1 later, I’m still logged in and it automatically takes me to page2.  That means there’s a cookie set and it knows I already logged in.
I want to use file_get_contents to get page2.php.  When I try it, I get the contents of the log-in page instead.  I assume that’s because file_get_contents doesn’t know a cookie is set and page2 is saying, you shouldn’t be here, you’re not logged in, so it bumps me back to page 1.
I realize I can use cURL to do the log-in, create a cookie and get the contents, like this….

```<code>$url = 'https://www.example.com/page1.php'; // the url of the login page
$post_data = "urerid=myusername&password=mypassword ";  // The login data to post
$ch = curl_init(); // Create a curl object
curl_setopt($ch, CURLOPT_URL, $url ); // Set the URL
curl_setopt($ch, CURLOPT_POST, 1 ); // This is a POST query
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data); //Set the post data
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // Get the content
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // Follow Location redirects
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt'); // Set cookie storing files
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookie.txt');
$output = curl_exec($ch); // Execute the action to login
</code>```

My problem is , I don’t want to log-in again (for reasons I don’t want to get into).  Is there a way to let file_get_contents, cURL, or some other function, know I’m previously logged in and get the contents of page2.  Since example.com is setting a cookie, can I access that cookie somehow and use it to avoid logging in again?

答:
Why it wont work:

If the website is creating security cookie against xss , you cant simply take one user cookies and send request from diffrent IP while using them.

Even if the website is not using security hash , you cant access cookies belongs to a diffrent domain due security resones (you dont want that gmail.com could access your microsoft.com cookies)

to cut it short - the only way that could work is by :

Use SSO (with partner to the destination domain).

Use Cross-Domain support (with partner to the destination domain).

Get Access Tokens (like facebook is doing) if supported by the destination domain.

Request your users to login from your domain (by trusting you - which is bad) in order to let your site be able to access the other domain data.

Body:
If I go to a website, example.com/page1.php, it is a log-in page.  When I log-in, it takes me to example.com/page2.php.  If I close my browser and come back to page1 later, I’m still logged in and it automatically takes me to page2.  That means there’s a cookie set and it knows I already logged in.
I want to use file_get_contents to get page2.php.  When I try it, I get the contents of the log-in page instead.  I assume that’s because file_get_contents doesn’t know a cookie is set and page2 is saying, you shouldn’t be here, you’re not logged in, so it bumps me back to page 1.
I realize I can use cURL to do the log-in, create a cookie and get the contents, like this….

$url = 'https://www.example.com/page1.php'; // the url of the login page
$post_data = "urerid=myusername&password=mypassword ";  // The login data to post
$ch = curl_init(); // Create a curl object
curl_setopt($ch, CURLOPT_URL, $url ); // Set the URL
curl_setopt($ch, CURLOPT_POST, 1 ); // This is a POST query
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data); //Set the post data
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // Get the content
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // Follow Location redirects
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt'); // Set cookie storing files
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookie.txt');
$output = curl_exec($ch); // Execute the action to login

My problem is , I don’t want to log-in again (for reasons I don’t want to get into).  Is there a way to let file_get_contents, cURL, or some other function, know I’m previously logged in and get the contents of page2.  Since example.com is setting a cookie, can I access that cookie somehow and use it to avoid logging in again?


问:
const char* cppString to NSString not working if it contains smiles
I have cpp const char* string which contains " playlist" characters.
I am trying to convert it into NSString and I am getting "@(NULL)" string.

Following are my steps to convert it.

```<code> string cppString = " playlist"; //Cpp data type
</code>```

I have one method where I am passing my cpp string like

NSString *str = [self charStringToString:cppString.c_str()];

and the method returns NSString object after some operations:

```<code>+ (NSString *)charStringToString:(const char*)cppStringConst
{
   if ( cppStringConst == NULL || cppStringConst == nullptr  )
   {
      return @"";
   }
   NSString *outputString = [NSString stringWithFormat:@"%@", [NSString stringWithUTF8String:cppStringConst]];
   if ( [outputString isEqualToString:@"(null)"] == YES )
   {
      //it should not come here if I am passing  playlist
        return @"";
   }
   return outputString;
}
</code>```

Could anyone resolve my problem??

答: Take a look at this answer to a similar question. I'm suspicious of the encoding being used in your const char * string.

Body:
I have cpp const char* string which contains " playlist" characters.
I am trying to convert it into NSString and I am getting "@(NULL)" string.

Following are my steps to convert it.

 string cppString = " playlist"; //Cpp data type

I have one method where I am passing my cpp string like

NSString *str = [self charStringToString:cppString.c_str()];

and the method returns NSString object after some operations:

+ (NSString *)charStringToString:(const char*)cppStringConst
{
   if ( cppStringConst == NULL || cppStringConst == nullptr  )
   {
      return @"";
   }
   NSString *outputString = [NSString stringWithFormat:@"%@", [NSString stringWithUTF8String:cppStringConst]];
   if ( [outputString isEqualToString:@"(null)"] == YES )
   {
      //it should not come here if I am passing  playlist
        return @"";
   }
   return outputString;
}

Could anyone resolve my problem??


问:
Find a character in a data frame and change adjacent rows
I have a large data frame with 250,000 rows and 35 columns. A simpler sample can be generated by the following code:

```<code>data.frame(a=letters[sample(10,26,replace = T)],b=letters[1:26],c=letters[26:1])
</code>```

I want to search for every occurrence of a chosen character, let's say "h" and then change the cell containing "h" and 5 rows above "h" to NA.

答:
You need to be careful that the generated indexes do not include negative
values.  For example, if a 'h' is in row 3, then only rows 1, 2, and 3 need to
be set to NA.  df[3 -0:4, ] <- NA will no generate the needed result.

For this example, we will generate a data.frame df1 and a second copy,
df2, to make it easy to compare the results.  Notice that in column 'a'
there is an 'h' in row 2.

```<code>set.seed(2)
df1 <- df2 <-
  data.frame(a = letters[sample(10,26,replace = T)],
             b = c(letters[1:25],NA),
             c = c(letters[25:1],NA))
df1
#    a    b    c
# 1  b    a    y
# 2  h    b    x
# 3  f    c    w
# 4  b    d    v
# 5  j    e    u
# 6  j    f    t
# 7  b    g    s
# 8  i    h    r
# 9  e    i    q
# 10 f    j    p
# 11 f    k    o
# 12 c    l    n
# 13 h    m    m
# 14 b    n    l
# 15 e    o    k
# 16 i    p    j
# 17 j    q    i
# 18 c    r    h
# 19 e    s    g
# 20 a    t    f
# 21 g    u    e
# 22 d    v    d
# 23 i    w    c
# 24 b    x    b
# 25 d    y    a
# 26 e <NA> <NA>
</code>```

use lapply to find the row indexes within each column where an 'h' occurs

```<code>h_idx <- lapply(df1, function(x) which(x == "h"))
# $a
# [1]  2 13
#
# $b
# [1] 8
#
# $c
# [1] 18
</code>```

using lapply again, we build the row indexes to set to NA in each of the
columns.  Notice that the seq call starts from a max of the index minus four
and 1, this will prevent negative or zero indexes being called.

```<code>na_idx <- lapply(h_idx,
                 function(x) {
                   lapply(x, function(xx) {seq(max(c(xx - 4, 1)), xx, by = 1) })
                 })
na_idx
# $a
# $a[[1]]
# [1] 1 2
#
# $a[[2]]
# [1]  9 10 11 12 13
#
#
# $b
# $b[[1]]
# [1] 4 5 6 7 8
#
#
# $c
# $c[[1]]
# [1] 14 15 16 17 18
</code>```

for each column, set the needed rows to NA

```<code>for(cl in seq_along(df2)) {
  for (rws in na_idx[[cl]]) {
    df2[rws, cl] <- NA
  }
}
</code>```

The result

```<code>cbind(df1, df2)
#    a    b    c    a    b    c
# 1  b    a    y <NA>    a    y
# 2  h    b    x <NA>    b    x
# 3  f    c    w    f    c    w
# 4  b    d    v    b <NA>    v
# 5  j    e    u    j <NA>    u
# 6  j    f    t    j <NA>    t
# 7  b    g    s    b <NA>    s
# 8  i    h    r    i <NA>    r
# 9  e    i    q <NA>    i    q
# 10 f    j    p <NA>    j    p
# 11 f    k    o <NA>    k    o
# 12 c    l    n <NA>    l    n
# 13 h    m    m <NA>    m    m
# 14 b    n    l    b    n <NA>
# 15 e    o    k    e    o <NA>
# 16 i    p    j    i    p <NA>
# 17 j    q    i    j    q <NA>
# 18 c    r    h    c    r <NA>
# 19 e    s    g    e    s    g
# 20 a    t    f    a    t    f
# 21 g    u    e    g    u    e
# 22 d    v    d    d    v    d
# 23 i    w    c    i    w    c
# 24 b    x    b    b    x    b
# 25 d    y    a    d    y    a
# 26 e <NA> <NA>    e <NA> <NA>
</code>```

Body:
I have a large data frame with 250,000 rows and 35 columns. A simpler sample can be generated by the following code:

data.frame(a=letters[sample(10,26,replace = T)],b=letters[1:26],c=letters[26:1])

I want to search for every occurrence of a chosen character, let's say "h" and then change the cell containing "h" and 5 rows above "h" to NA.

Body:
You need to be careful that the generated indexes do not include negative
values.  For example, if a 'h' is in row 3, then only rows 1, 2, and 3 need to
be set to NA.  df[3 -0:4, ] <- NA will no generate the needed result.

For this example, we will generate a data.frame df1 and a second copy,
df2, to make it easy to compare the results.  Notice that in column 'a'
there is an 'h' in row 2.

set.seed(2)
df1 <- df2 <-
  data.frame(a = letters[sample(10,26,replace = T)],
             b = c(letters[1:25],NA),
             c = c(letters[25:1],NA))
df1
#    a    b    c
# 1  b    a    y
# 2  h    b    x
# 3  f    c    w
# 4  b    d    v
# 5  j    e    u
# 6  j    f    t
# 7  b    g    s
# 8  i    h    r
# 9  e    i    q
# 10 f    j    p
# 11 f    k    o
# 12 c    l    n
# 13 h    m    m
# 14 b    n    l
# 15 e    o    k
# 16 i    p    j
# 17 j    q    i
# 18 c    r    h
# 19 e    s    g
# 20 a    t    f
# 21 g    u    e
# 22 d    v    d
# 23 i    w    c
# 24 b    x    b
# 25 d    y    a
# 26 e <NA> <NA>

use lapply to find the row indexes within each column where an 'h' occurs

h_idx <- lapply(df1, function(x) which(x == "h"))
# $a
# [1]  2 13
#
# $b
# [1] 8
#
# $c
# [1] 18

using lapply again, we build the row indexes to set to NA in each of the
columns.  Notice that the seq call starts from a max of the index minus four
and 1, this will prevent negative or zero indexes being called.

na_idx <- lapply(h_idx,
                 function(x) {
                   lapply(x, function(xx) {seq(max(c(xx - 4, 1)), xx, by = 1) })
                 })
na_idx
# $a
# $a[[1]]
# [1] 1 2
#
# $a[[2]]
# [1]  9 10 11 12 13
#
#
# $b
# $b[[1]]
# [1] 4 5 6 7 8
#
#
# $c
# $c[[1]]
# [1] 14 15 16 17 18

for each column, set the needed rows to NA

for(cl in seq_along(df2)) {
  for (rws in na_idx[[cl]]) {
    df2[rws, cl] <- NA
  }
}

The result

cbind(df1, df2)
#    a    b    c    a    b    c
# 1  b    a    y <NA>    a    y
# 2  h    b    x <NA>    b    x
# 3  f    c    w    f    c    w
# 4  b    d    v    b <NA>    v
# 5  j    e    u    j <NA>    u
# 6  j    f    t    j <NA>    t
# 7  b    g    s    b <NA>    s
# 8  i    h    r    i <NA>    r
# 9  e    i    q <NA>    i    q
# 10 f    j    p <NA>    j    p
# 11 f    k    o <NA>    k    o
# 12 c    l    n <NA>    l    n
# 13 h    m    m <NA>    m    m
# 14 b    n    l    b    n <NA>
# 15 e    o    k    e    o <NA>
# 16 i    p    j    i    p <NA>
# 17 j    q    i    j    q <NA>
# 18 c    r    h    c    r <NA>
# 19 e    s    g    e    s    g
# 20 a    t    f    a    t    f
# 21 g    u    e    g    u    e
# 22 d    v    d    d    v    d
# 23 i    w    c    i    w    c
# 24 b    x    b    b    x    b
# 25 d    y    a    d    y    a
# 26 e <NA> <NA>    e <NA> <NA>


问:
Need Assistance With Inserting New Child XML Element With PHP
I've been browsing around for hours now and there is no simple explaination or demonstration of how to insert a new child element into an XML file and then save the XML file.

Here is the XML Tree.. (very simple)

```<code>< book >

    <chapter>
        <title>Everyday Italian</title>
        <year>2005</year>
    </chapter>
    <chapter>
        <title>Harry Potter</title>
        <year>2005</year>
    </chapter>
    <chapter>
        <title>XQuery Kick Start</title>
        <year>2003</year>
    </chapter>

< / book >
</code>```

...
I would deeply appreciate any help with this. Once again to recap, I have a PHP file and it its goal is to insert a new "chapter" with specifieid "title" and "year" and then save the new file (basically overwriting the book.xml file)

答:
There is an example inside the php-manual which gives you  all informations you need:
http://php.net/manual/en/domdocument.save.php

The methods you need:

DOMDocument->load()

  //load xml from a file

DOMDocument->createElement()

//create a element-node

DOMDocument->createTextNode()

//create a textNode

DOMNode->appendChild()

//append one node to another

DOMDocument->save()

//save XML into a file

,

```<code><?php
  //create a document
  $doc=new DOMDocument;
  //load the file
  $doc->load('book.xml');
  //create chapter-element
  $chapter=$doc->createElement('chapter');
  //create title-element
  $title=$doc->createElement('title');
  //insert text to the title
  $title->appendChild($doc->createTextNode('new title for a new chapter'));
  //create year-element
  $year=$doc->createElement('year');
  //insert text to the year
  $year->appendChild($doc->createTextNode('new year for a new chapter'));
  //append title and year to the chapter
  $chapter->appendChild($title);
  $chapter->appendChild($year);
  //append the chapter to the root-element
  $doc->documentElement->appendChild($chapter);
  //save it into the file
  $doc->save('book.xml');
?>
</code>```

Body:
I've been browsing around for hours now and there is no simple explaination or demonstration of how to insert a new child element into an XML file and then save the XML file.

Here is the XML Tree.. (very simple)

< book >

    <chapter>
        <title>Everyday Italian</title>
        <year>2005</year>
    </chapter>
    <chapter>
        <title>Harry Potter</title>
        <year>2005</year>
    </chapter>
    <chapter>
        <title>XQuery Kick Start</title>
        <year>2003</year>
    </chapter>

< / book >

...
I would deeply appreciate any help with this. Once again to recap, I have a PHP file and it its goal is to insert a new "chapter" with specifieid "title" and "year" and then save the new file (basically overwriting the book.xml file)

Body:
There is an example inside the php-manual which gives you  all informations you need:
http://php.net/manual/en/domdocument.save.php

The methods you need:

DOMDocument->load()

  //load xml from a file

DOMDocument->createElement()

//create a element-node

DOMDocument->createTextNode()

//create a textNode

DOMNode->appendChild()

//append one node to another

DOMDocument->save()

//save XML into a file

,

<?php
  //create a document
  $doc=new DOMDocument;
  //load the file
  $doc->load('book.xml');
  //create chapter-element
  $chapter=$doc->createElement('chapter');
  //create title-element
  $title=$doc->createElement('title');
  //insert text to the title
  $title->appendChild($doc->createTextNode('new title for a new chapter'));
  //create year-element
  $year=$doc->createElement('year');
  //insert text to the year
  $year->appendChild($doc->createTextNode('new year for a new chapter'));
  //append title and year to the chapter
  $chapter->appendChild($title);
  $chapter->appendChild($year);
  //append the chapter to the root-element
  $doc->documentElement->appendChild($chapter);
  //save it into the file
  $doc->save('book.xml');
?>


问:
Can I trigger CSS transitions via selectors other than ":hover" and ":active"?
I'm learning about transitions in CSS3 via sololearn.com, where the only examples given for using transitions are in conjunction with the :hover selector.

Everything else I can find uses either that or :active with no explanation of what other selectors can be used or why selectors other than these two are not shown as examples.

Is there a way to start transitions without interaction from the user? Or would that require JavaScript?

答:
tl;dr

You can use any selector to initiate a transition, but you don't really need one for it. All you need is to:

set the transition properties on the element

change the value of the property to be transitioned.

You can do both of the above without using CSS selectors, which are nothing more than a handy method available for setting DOM element properties.

initial answer

transitions work with any selector whatsoever. But they are not related to any selector and you don't really need selectors to perform CSS transitions.

All you need for a transition to work is to set the following transition properties:

transition-duration,

transition-delay,

transition-timing-function

transition-property. (has to be animatable for transition to work).

After this, whenever the property named in transition-property changes its value between two animatable values, the change between the initial and the set value happens according to the set transition properties.

This happens regardless of what exactly triggers the change of value for the transitioned property

It could:

change because a particular CSS selector (you defined) starts or stops applying (matching the element);

be changed directly using JavaScript.

Or, of course, by a combination of the two (i.e. use JavaScript to apply a class, which changes the value of the property being transitioned)

So, in effect, the answer to your question is: transitions work with any selector but they also work without one. They work based on DOM element property values, regardless of any selector.

A common way to demonstrate a transition is using :hover state because all one needs to do to switch between selectors (which is to control / demonstrate / observe the transition) is. well,... hover!

On:

For example is there a way to start transitions without interaction from the user?

Of course there is! A very basic example is to add a class on  when all page resources have finished loading.

When  element is created it doesn't have the class and when all resources have finished loading, the Window's onload event triggers. We can use this event to add the class. If a transition is properly defined on body and the transitioned property changes because a stronger selector now applies on the element, the transition will happen. Without any user interaction.

See it working:

window.onload = function() {
  document.querySelector('body').classList.add('loaded')
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  background-color: #fff;
  transition: background-color 1s linear;
}
.loaded { background-color: #212121;}</code>```

You could also set a recursive function that toggles the state of an element and calls itself after a set amount of time, effectively toggling the state back after the set time, in a continuous cycle:

For the above example this would mean:

window.onload = toggleBodyClass;
function toggleBodyClass() {
  document.querySelector('body').classList.toggle('loaded');
  setTimeout(toggleBodyClass, 1234);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  background-color: #fff;
  transition: background-color 1s linear;
}
.loaded { background-color: #212121;}</code>```

If the question is: "Can a selector start/stop applying without the use of JavaScript and/or user interaction?" It really translates to:

"Are there transitions triggered by something else than what usually triggers a transition?", with possible answers varying from:
"Why do you want to know?" to "Is there web browsing without JavaScript and/or user interaction?"

Body:
tl;dr

You can use any selector to initiate a transition, but you don't really need one for it. All you need is to:

set the transition properties on the element

change the value of the property to be transitioned.

You can do both of the above without using CSS selectors, which are nothing more than a handy method available for setting DOM element properties.

initial answer

transitions work with any selector whatsoever. But they are not related to any selector and you don't really need selectors to perform CSS transitions.

All you need for a transition to work is to set the following transition properties:

transition-duration,

transition-delay,

transition-timing-function

transition-property. (has to be animatable for transition to work).

After this, whenever the property named in transition-property changes its value between two animatable values, the change between the initial and the set value happens according to the set transition properties.

This happens regardless of what exactly triggers the change of value for the transitioned property

It could:

change because a particular CSS selector (you defined) starts or stops applying (matching the element);

be changed directly using JavaScript.

Or, of course, by a combination of the two (i.e. use JavaScript to apply a class, which changes the value of the property being transitioned)

So, in effect, the answer to your question is: transitions work with any selector but they also work without one. They work based on DOM element property values, regardless of any selector.

A common way to demonstrate a transition is using :hover state because all one needs to do to switch between selectors (which is to control / demonstrate / observe the transition) is. well,... hover!

On:

For example is there a way to start transitions without interaction from the user?

Of course there is! A very basic example is to add a class on <body> when all page resources have finished loading.

When <body> element is created it doesn't have the class and when all resources have finished loading, the Window's onload event triggers. We can use this event to add the class. If a transition is properly defined on body and the transitioned property changes because a stronger selector now applies on the element, the transition will happen. Without any user interaction.

See it working:

window.onload = function() {
  document.querySelector('body').classList.add('loaded')
}

body {
  background-color: #fff;
  transition: background-color 1s linear;
}
.loaded { background-color: #212121;}

You could also set a recursive function that toggles the state of an element and calls itself after a set amount of time, effectively toggling the state back after the set time, in a continuous cycle:

For the above example this would mean:

window.onload = toggleBodyClass;
function toggleBodyClass() {
  document.querySelector('body').classList.toggle('loaded');
  setTimeout(toggleBodyClass, 1234);
}

body {
  background-color: #fff;
  transition: background-color 1s linear;
}
.loaded { background-color: #212121;}

If the question is: "Can a selector start/stop applying without the use of JavaScript and/or user interaction?" It really translates to:

"Are there transitions triggered by something else than what usually triggers a transition?", with possible answers varying from:
"Why do you want to know?" to "Is there web browsing without JavaScript and/or user interaction?"


问:
Run subscription only once
I need to run userProfiles$.subscribe(async res => { only once. But it works infinitely. Can you tell me how to avoid it?

This is the video of that issue:

.ts

```<code>async loginWithGoogle(): Promise<void> {
    try {
      const result = await this.afAuth.auth.signInWithPopup(new firebase.auth.GoogleAuthProvider());
      const userId: string = result.additionalUserInfo.profile.id;
      const userProfile: AngularFirestoreDocument<UserProfile> = this.fireStore.doc(`userProfile/${userId}`);
      const userProfiles: AngularFirestoreCollection<UserProfile> = this.fireStore.collection('userProfile/', ref => ref.where('email', '==', result.additionalUserInfo.profile.email));
      const userProfiles$: Observable<UserProfile[]> = userProfiles.valueChanges();

      userProfiles$.subscribe(async res => { //problem is here
        if (res.length == 0) {
          await userProfile.set({
            id: userId,
            email: result.additionalUserInfo.profile.email,
            creationTime: moment().format(),
            lastSignInTime: moment().format()
          });
        } else {
          await userProfile.update({
            lastSignInTime: moment().format()
          });
        }
      });
    }
    catch (err) {
      console.log(err);
    }
  }
</code>```

I have tried to convert it to promise like below. But no difference. Maybe I did it wrong?

```<code> userProfiles$.map(async res => {
        if (res.length == 0) {
          await userProfile.set({
            id: userId, email: result.additionalUserInfo.profile.email,
            creationTime: moment().format(),
            lastSignInTime: moment().format()
          });
        }
      }).toPromise();
</code>```

Versions:

```<code> "typescript": "2.4.2"
 "rxjs": "5.5.2",
</code>```

答:
Promise way:

```<code>userProfiles$.toPromise().then((res) => {
   if (res.length == 0) {
      await userProfile.set({
         id: userId, email: result.additionalUserInfo.profile.email,
         creationTime: moment().format(),
         lastSignInTime: moment().format()
      });
   }
}).catch(err => {
   // handle error
});
</code>```

Firstly you convert it to promise then listen to it via .then() method and wait for resolved promise.

Observable .take(1)

```<code>userProfiles$.take(1).subscribe(async res => { //problem is here
        if (res.length == 0) {
          await userProfile.set({
            id: userId,
            email: result.additionalUserInfo.profile.email,
            creationTime: moment().format(),
            lastSignInTime: moment().format()
          });
        } else {
          await userProfile.update({
            lastSignInTime: moment().format()
          });
        }
      });
</code>```

Notice for toPromise way don't forget to import toPromise from rxjs operators and for take you should also import take method from rxjs

Update. Angular version >= 6

Since angular 6 it is required to have rxjs >= 6. In which now operators like take are now importable and used in .pipe() method. You can read more here

```<code>// somewhere at the top of file
import { take } from 'rxjs/operators';

userProfiles$.pipe(take(1)).subscribe(async res => { //problem is here
        if (res.length == 0) {
          await userProfile.set({
            id: userId,
            email: result.additionalUserInfo.profile.email,
            creationTime: moment().format(),
            lastSignInTime: moment().format()
          });
        } else {
          await userProfile.update({
            lastSignInTime: moment().format()
          });
        }
      });
</code>```

Title: Run subscription only once

Body:
I need to run userProfiles$.subscribe(async res => { only once. But it works infinitely. Can you tell me how to avoid it?

This is the video of that issue:

.ts

async loginWithGoogle(): Promise<void> {
    try {
      const result = await this.afAuth.auth.signInWithPopup(new firebase.auth.GoogleAuthProvider());
      const userId: string = result.additionalUserInfo.profile.id;
      const userProfile: AngularFirestoreDocument<UserProfile> = this.fireStore.doc(`userProfile/${userId}`);
      const userProfiles: AngularFirestoreCollection<UserProfile> = this.fireStore.collection('userProfile/', ref => ref.where('email', '==', result.additionalUserInfo.profile.email));
      const userProfiles$: Observable<UserProfile[]> = userProfiles.valueChanges();

      userProfiles$.subscribe(async res => { //problem is here
        if (res.length == 0) {
          await userProfile.set({
            id: userId,
            email: result.additionalUserInfo.profile.email,
            creationTime: moment().format(),
            lastSignInTime: moment().format()
          });
        } else {
          await userProfile.update({
            lastSignInTime: moment().format()
          });
        }
      });
    }
    catch (err) {
      console.log(err);
    }
  }

I have tried to convert it to promise like below. But no difference. Maybe I did it wrong?

 userProfiles$.map(async res => {
        if (res.length == 0) {
          await userProfile.set({
            id: userId, email: result.additionalUserInfo.profile.email,
            creationTime: moment().format(),
            lastSignInTime: moment().format()
          });
        }
      }).toPromise();

Versions:

 "typescript": "2.4.2"
 "rxjs": "5.5.2",

Body:
Promise way:

userProfiles$.toPromise().then((res) => {
   if (res.length == 0) {
      await userProfile.set({
         id: userId, email: result.additionalUserInfo.profile.email,
         creationTime: moment().format(),
         lastSignInTime: moment().format()
      });
   }
}).catch(err => {
   // handle error
});

Firstly you convert it to promise then listen to it via .then() method and wait for resolved promise.

Observable .take(1)

userProfiles$.take(1).subscribe(async res => { //problem is here
        if (res.length == 0) {
          await userProfile.set({
            id: userId,
            email: result.additionalUserInfo.profile.email,
            creationTime: moment().format(),
            lastSignInTime: moment().format()
          });
        } else {
          await userProfile.update({
            lastSignInTime: moment().format()
          });
        }
      });

Notice for toPromise way don't forget to import toPromise from rxjs operators and for take you should also import take method from rxjs

Update. Angular version >= 6

Since angular 6 it is required to have rxjs >= 6. In which now operators like take are now importable and used in .pipe() method. You can read more here

// somewhere at the top of file
import { take } from 'rxjs/operators';

userProfiles$.pipe(take(1)).subscribe(async res => { //problem is here
        if (res.length == 0) {
          await userProfile.set({
            id: userId,
            email: result.additionalUserInfo.profile.email,
            creationTime: moment().format(),
            lastSignInTime: moment().format()
          });
        } else {
          await userProfile.update({
            lastSignInTime: moment().format()
          });
        }
      });


问:
GPUImageView inside SKScene as SKNode material - Playing transparent video on ARKit
In Project -A- I used GPUImageView to display Video (recorded on greenscreen) with transparency. Using the GPUImageChromaKeyBlendFilter, and so on.
and works Superb.

Another project -B- based on ARKIT shows me in the space a plain with VIDEO and it also works fine using SKVideoNode and AVPlayer.

Now the question is to combine it all together in one :) So in space I want to display Video but with transparency ...
Unfortunately, I can not render a GPUImageView on any SpriteKit element, and then add to SKScene, which is an animated texture for SCNPlane,  is it possible at all? Or maybe there is other way to render Video with transparencies with ARKit.?

Thx for any suggestions

答:
I had the same task! See my solution here. </p>

<p>I basically implemented ChromaKeyMaterial from Lësha Turkowski and wrote this code to place and play the video.  </p>

```<code>import UIKit
import ARKit

class ARTransVC: UIViewController{

@IBOutlet weak var arSceneView: ARSCNView!
let configuration = ARWorldTrackingConfiguration()

private var player: AVPlayer = {
    guard let url = Bundle.main.url(forResource: "FY3A4278", withExtension: "mp4") else { fatalError() }
    return AVPlayer(url: url)
}()

override func viewDidLoad() {
    super.viewDidLoad()
    self.arSceneView.debugOptions = [ARSCNDebugOptions.showWorldOrigin, ARSCNDebugOptions.showFeaturePoints]
    self.arSceneView.session.run(configuration)

    //a delay for ARKit to capture the surroundings
    DispatchQueue.main.asyncAfter(deadline: .now() + 3) {

        // A SpriteKit scene to contain the SpriteKit video node
        let spriteKitScene = SKScene(size: CGSize(width: self.arSceneView.frame.width, height: self.arSceneView.frame.height))
        spriteKitScene.scaleMode = .aspectFit
        spriteKitScene.backgroundColor = .clear
        spriteKitScene.scaleMode = .aspectFit

        //Create the SpriteKit video node, containing the video player
        let videoSpriteKitNode = SKVideoNode(avPlayer: self.player)
        videoSpriteKitNode.position = CGPoint(x: spriteKitScene.size.width / 2.0, y: spriteKitScene.size.height / 2.0)
        videoSpriteKitNode.size = spriteKitScene.size
        videoSpriteKitNode.yScale = -1.0
        videoSpriteKitNode.play()
        spriteKitScene.addChild(videoSpriteKitNode)

        // To make the video loop
        self.player.actionAtItemEnd = .none
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(ARTransVC.playerItemDidReachEnd),
            name: NSNotification.Name.AVPlayerItemDidPlayToEndTime,
            object:  self.player.currentItem)

        // Create the SceneKit scene
        let scene = SCNScene()
        self.arSceneView.scene = scene

        //Create a SceneKit plane and add the SpriteKit scene as its material
        let background = SCNPlane(width: CGFloat(1), height: CGFloat(1))
        background.firstMaterial?.diffuse.contents = spriteKitScene
        let chromaKeyMaterial = ChromaKeyMaterial()
        chromaKeyMaterial.diffuse.contents = self.player

        let backgroundNode = SCNNode(geometry: background)
        backgroundNode.geometry?.firstMaterial?.isDoubleSided = true
        backgroundNode.geometry!.materials = [chromaKeyMaterial]

        backgroundNode.position = SCNVector3(0,0,-2.0)
        scene.rootNode.addChildNode(backgroundNode)

        //video does not start without delaying the player
        //playing the video before just results in [SceneKit] Error: Cannot get pixel buffer (CVPixelBufferRef)
        DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
            self.player.seek(to:CMTimeMakeWithSeconds(1, 1000))
            self.player.play()
        }
    }
}

@objc func playerItemDidReachEnd(notification: NSNotification) {
    if let playerItem: AVPlayerItem = notification.object as? AVPlayerItem {
        playerItem.seek(to: kCMTimeZero, completionHandler: nil)
    }
}
</code>```

Body:
I had the same task! See my solution here.

I basically implemented ChromaKeyMaterial from Lësha Turkowski and wrote this code to place and play the video.

import UIKit
import ARKit

class ARTransVC: UIViewController{

@IBOutlet weak var arSceneView: ARSCNView!
let configuration = ARWorldTrackingConfiguration()

private var player: AVPlayer = {
    guard let url = Bundle.main.url(forResource: "FY3A4278", withExtension: "mp4") else { fatalError() }
    return AVPlayer(url: url)
}()

override func viewDidLoad() {
    super.viewDidLoad()
    self.arSceneView.debugOptions = [ARSCNDebugOptions.showWorldOrigin, ARSCNDebugOptions.showFeaturePoints]
    self.arSceneView.session.run(configuration)

    //a delay for ARKit to capture the surroundings
    DispatchQueue.main.asyncAfter(deadline: .now() + 3) {

        // A SpriteKit scene to contain the SpriteKit video node
        let spriteKitScene = SKScene(size: CGSize(width: self.arSceneView.frame.width, height: self.arSceneView.frame.height))
        spriteKitScene.scaleMode = .aspectFit
        spriteKitScene.backgroundColor = .clear
        spriteKitScene.scaleMode = .aspectFit

        //Create the SpriteKit video node, containing the video player
        let videoSpriteKitNode = SKVideoNode(avPlayer: self.player)
        videoSpriteKitNode.position = CGPoint(x: spriteKitScene.size.width / 2.0, y: spriteKitScene.size.height / 2.0)
        videoSpriteKitNode.size = spriteKitScene.size
        videoSpriteKitNode.yScale = -1.0
        videoSpriteKitNode.play()
        spriteKitScene.addChild(videoSpriteKitNode)

        // To make the video loop
        self.player.actionAtItemEnd = .none
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(ARTransVC.playerItemDidReachEnd),
            name: NSNotification.Name.AVPlayerItemDidPlayToEndTime,
            object:  self.player.currentItem)

        // Create the SceneKit scene
        let scene = SCNScene()
        self.arSceneView.scene = scene

        //Create a SceneKit plane and add the SpriteKit scene as its material
        let background = SCNPlane(width: CGFloat(1), height: CGFloat(1))
        background.firstMaterial?.diffuse.contents = spriteKitScene
        let chromaKeyMaterial = ChromaKeyMaterial()
        chromaKeyMaterial.diffuse.contents = self.player

        let backgroundNode = SCNNode(geometry: background)
        backgroundNode.geometry?.firstMaterial?.isDoubleSided = true
        backgroundNode.geometry!.materials = [chromaKeyMaterial]

        backgroundNode.position = SCNVector3(0,0,-2.0)
        scene.rootNode.addChildNode(backgroundNode)

        //video does not start without delaying the player
        //playing the video before just results in [SceneKit] Error: Cannot get pixel buffer (CVPixelBufferRef)
        DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
            self.player.seek(to:CMTimeMakeWithSeconds(1, 1000))
            self.player.play()
        }
    }
}

@objc func playerItemDidReachEnd(notification: NSNotification) {
    if let playerItem: AVPlayerItem = notification.object as? AVPlayerItem {
        playerItem.seek(to: kCMTimeZero, completionHandler: nil)
    }
}


问:
Applicability of Reflection
There are some great articles out there such as this one on Reflection.

What I want to know is real world examples where it is used and real world reasons or when it's useful and why outside the raw "you can get type info"...I get all that in this article and others.

Ok, so what, it doesn't really help me in context to actual programming situations.  I'm trying to figure out how people are using it in apps, good examples of times that they have been used just to get my head wrapped around when you'd want to use it.

答: Reflection is useful for run-time plugins. When you make a program that can be extended via plugins, by definition you don't know what the classes and methods are at compile-time, so you use reflection to load the libraries at run-time and then call the appropriate methods.</p>

Title: Applicability of Reflection


问:
Read values From xml file and store each row into different list in python
I have been trying to load values from a xml file and store it in different lists. Can somebody show me a possible way?  Any help is appreciated.
xml file has 4 rows of float numbers like this:

1.34566 1.56777 1.454534 1.436234 1.363546 1.43642353

2.45432 2.34251 2.324323 2.324232 2.342342 2.23423423

0.45234 0.32423 0.324233 0.324233 0.324234 0.23423432

1.32423 1.43324 1.324334 1.343422 1.324343 1.34234234

I want to import this float numbers into four lists List1,List2,List3,List4 in python.

I know to store it into one list, but i want to store each row into separate list. Can somebody please help me with this code ?

答:
You can make a list of lists and then do whatever you want with the data gathered there.
sample code could be :

```<code>superList = []
for x in range(1, your last row):
   temp = []
   while i < your number of columns:
      temp.append(sheet.cell(row = x, column = i).value)
   superList.append(temp)
</code>```

Pretty basic. Where sheet is the variable that "holds" your file.
So what this does, is that it creates a list out of every row and then puts all of these lists in a "super" list. So superList[0] will have the first row, superList[1] the second row etc.

Body:
You can make a list of lists and then do whatever you want with the data gathered there.
sample code could be :

superList = []
for x in range(1, your last row):
   temp = []
   while i < your number of columns:
      temp.append(sheet.cell(row = x, column = i).value)
   superList.append(temp)

Pretty basic. Where sheet is the variable that "holds" your file.
So what this does, is that it creates a list out of every row and then puts all of these lists in a "super" list. So superList[0] will have the first row, superList[1] the second row etc.


问:
Xamarin.Forms - Xamarin.Forms.Maps broken references in Droid Project
I need to implement Map functionality into an application that I'm building.
And I was folliwing this guide.

I downloaded the package and did all of the configuration.
I haven't implemented the Map class into my project yet, I only did the configuration required for both platforms (Android and iOS).

The Portable project and the iOS project are fine, the problem here is the Android project.

It has some broken references, these ones:

And when I try to compile the Android project, I get this error and these warnings:

Can anybody give me a hand? Thanks in advance.

EDIT:
As a sidenote, I'm using the Sdk installed by Android Studio, and that one has the latest Google Play Services installed.

UPDATE:
I just upgraded the version of my Xamarin.GooglePlayServices one by one (the one listed up there in the first image) for some reason it downloaded a really old version of those. So I just upgraded them, and it seems those references are fine now.

But I still get the error:
The "ResolveLibraryProjectImports" tasks failed unexpectedly.

答:
SOLUTION:

I unloaded the Android project, added this:

```<code><UseShortFileNames>True</UseShortFileNames>
</code>```

To every property group in the .csproj file.

Load my android project back, and it all worked fine now.

Body:
SOLUTION:

I unloaded the Android project, added this:

<UseShortFileNames>True</UseShortFileNames>

To every property group in the .csproj file.

Load my android project back, and it all worked fine now.


问:
Create transducer from ordinary code
How would I create a transducer from the following ordinary code, where combo is the alias for clojure.math.combinatorics:

```<code>(defn row->evenly-divided [xs]
  (->> (combo/combinations (sort-by - xs) 2)
       (some (fn [[big small]]
               (assert (>= big small))
               (let [res (/ big small)]
                 (when (int? res)
                   res))))))
</code>```

As noted in a comment transducers are only applicable for processing each item. With this is mind I've made the code a little more transducer friendly by shifting the sorting so that it is now being done for each item. I don't think there's anything that can be done about the combinations part however!

```<code>(defn row->evenly-divided [xs]
  (->> (combo/combinations xs 2)
       (some (fn [xy]
               (let [res (apply / (sort-by - xy))]
                 (when (int? res)
                   res))))))
</code>```

答:
This is the same function but with an introduced transducer:</p>

```<code>(def x-row->evenly-divided (comp
                             (map (partial sort-by -))
                             (map (partial apply /))
                             (filter int?)))

(defn row->evenly-divided-2 [xs]
  (->> (combo/combinations xs 2)
       (sequence x-row->evenly-divided)
       first))
</code>```

Title: Create transducer from ordinary code

Body:
How would I create a transducer from the following ordinary code, where combo is the alias for clojure.math.combinatorics:

(defn row->evenly-divided [xs]
  (->> (combo/combinations (sort-by - xs) 2)
       (some (fn [[big small]]
               (assert (>= big small))
               (let [res (/ big small)]
                 (when (int? res)
                   res))))))

As noted in a comment transducers are only applicable for processing each item. With this is mind I've made the code a little more transducer friendly by shifting the sorting so that it is now being done for each item. I don't think there's anything that can be done about the combinations part however!

(defn row->evenly-divided [xs]
  (->> (combo/combinations xs 2)
       (some (fn [xy]
               (let [res (apply / (sort-by - xy))]
                 (when (int? res)
                   res))))))

Body:
This is the same function but with an introduced transducer:

(def x-row->evenly-divided (comp
                             (map (partial sort-by -))
                             (map (partial apply /))
                             (filter int?)))

(defn row->evenly-divided-2 [xs]
  (->> (combo/combinations xs 2)
       (sequence x-row->evenly-divided)
       first))


问:
PageSize in kendo grid - make it clickable to show number of items displayed
I have a kendo grid component in angular 2 application, which loads the data in grid dynamically. In the grid i have a kendogridbinding where pageSize is set to 10. so suppose if i have 100 items it shows 1- 10 of 100, i am looking for making 100 as clickable so when i hover mouse over 100, hand symbol comes up and on click it will show me all 100 items.

grid.comp.html

```<code><kendo-grid #grid [kendoGridBinding]="gridData" [pageSize]="10" [pageable]="true" style="cursor:pointer">
            <kendo-grid-column *ngFor="let column of columns" [field]="getColumnField(column)" [title]="getColumnTitle(column)" [width]="getColumnWidth(column)">
                <template kendoGridHeaderTemplate let-column="column">
                    <span style=color:red; [title]="column.title" (click)="onTemplateSpanClick($event)">{{column.title}} </span>
                </template>
                <template kendoGridCellTemplate let-dataItem let-rowIndex="rowIndex">
                    <span *ngIf="column!== 'Status'" [title]="column.title">
                         <span [title]="column.title">
                   {{dataItem[column]}}
                   <!-- <span [innerHTML]="dataItem[column]"></span>  -->
                   </span>
                    </span>
                </template>
            </kendo-grid-column>
        </kendo-grid>
</code>```

![image of pagesize, 5 should be clickable
]1

答:
You can use PagerTemplate and provide the desired content (and respective event handlers and CSS for the custom elements), e.g.:

```<code><ng-template
        kendoPagerTemplate
        let-totalPages="totalPages"
        let-currentPage="currentPage"
        let-skip="skip"
        let-total="total">
         <kendo-pager-prev-buttons></kendo-pager-prev-buttons>
         <kendo-pager-numeric-buttons [buttonCount]="10"></kendo-pager-numeric-buttons>
         <kendo-pager-next-buttons></kendo-pager-next-buttons>
         <span>{{ skip + 1 }} - {{ skip + pageSize }} of <span class="custom" (click)="showAll()">{{ total }} items</span></span>
      </ng-template>
</code>```

EXAMPLE

Body:
I have a kendo grid component in angular 2 application, which loads the data in grid dynamically. In the grid i have a kendogridbinding where pageSize is set to 10. so suppose if i have 100 items it shows 1- 10 of 100, i am looking for making 100 as clickable so when i hover mouse over 100, hand symbol comes up and on click it will show me all 100 items.

grid.comp.html

<kendo-grid #grid [kendoGridBinding]="gridData" [pageSize]="10" [pageable]="true" style="cursor:pointer">
            <kendo-grid-column *ngFor="let column of columns" [field]="getColumnField(column)" [title]="getColumnTitle(column)" [width]="getColumnWidth(column)">
                <template kendoGridHeaderTemplate let-column="column">
                    {{column.title}}
                </template>
                <template kendoGridCellTemplate let-dataItem let-rowIndex="rowIndex">

                   {{dataItem[column]}}

                </template>
            </kendo-grid-column>
        </kendo-grid>

![image of pagesize, 5 should be clickable
]1

Body:
You can use PagerTemplate and provide the desired content (and respective event handlers and CSS for the custom elements), e.g.:

<ng-template
        kendoPagerTemplate
        let-totalPages="totalPages"
        let-currentPage="currentPage"
        let-skip="skip"
        let-total="total">
         <kendo-pager-prev-buttons></kendo-pager-prev-buttons>
         <kendo-pager-numeric-buttons [buttonCount]="10"></kendo-pager-numeric-buttons>
         <kendo-pager-next-buttons></kendo-pager-next-buttons>
         <span>{{ skip + 1 }} - {{ skip + pageSize }} of <span class="custom" (click)="showAll()">{{ total }} items</span></span>
      </ng-template>

EXAMPLE


问:
jQuery passing parameters into .ajax()
I'm having issues passing parameters/variables into the ajax() function.

The function below accepts two parameters. One is 'element', the success option of .ajax() uses, that works fine so no need to focus on that. The 'tx' is either a single value like 'menu' or a couple of values separated by a colon like this: "menu:categories:brands"

If there is only one value in 'tx' then only one AJAX request needs to be sent and that works fine. If there is more than one value in 'tx' the function split's it using ":" is the delimiter and then passes offset[0] as the value of 'tx' into the AJAX request and then store's the rest of the values in 'x'.

What I'm having issues with is running this function recursively once the AJAX request is complete for the first value. The var 'more' stores a bool value if there is more values left to process or not. However, when I write in an if argument using 'more == true' into the success or complete option of .ajax() it doesn't reflect the value stored in that variables, it always returns false.

Before some one answers, with "You should structure the function that calls this function to only pass a single value into that parameter," lets suppose that this is an impossible venture that is outside the realm of my control.

I have no idea why this happening. I know it's probably something very simple that I'm overlooking but I've been up for about 16 hours now and this issue has plagued me for at least half that time.

Any help here is appreciated. Here is the function:

```<code>function getContent(element, tx) {
    e = element
    modAmount = tx.split(':')
    if (modAmount.length > 1) {
        x = ''
        tx = modAmount[0]
        for (i=1;i<modAmount.length;i++) {
            x = x + modAmount[i]
            if (i != (modAmount.length)-1){
                x = x+":"
            }
        }
        more = true
    }
    else {
        more = false
        tx = modAmount[0]
    }
    $.ajax({
        type: "POST",
        url: "getModule.php",
        data: "modName="+tx+"&DB=<?php echo DB ?>",
        success: function(data){
            if ($( element ).find('p').text() == "No Content"){
                $( element ).find('p').remove();
                $( element ).html("<div onclick='destroy(this)' id='destroy' class='ui-corner-all destroy' title='Remove Module'>"+data+"</div>")
            }
            else {
                $( element ).append("<div onclick='destroy(this)' id='destroy' class='ui-corner-all destroy' title='Remove Module'>"+data+"</div>");
            }
        },
        complete: function() {
            if (more == true) {alert(x)} // always returns false
        }
    });

}
</code>```

答:
There's already one glaring error here: you're not declaring your local variables using the var keyword. This means that there's only one instance of any of those variables, in the global context.

I'm not sure if this is your problem, but it certainly seems like it could be. Consider the case where you call getContent "foo:bar". The first call sets more to true, but then the second recursive call sets more back to false. When the first XmlHttpRequest finishes, the completion callback will see the value of false rather than the true you were expecting, since those two calls are sharing the same variable for more.

You should read up on how JavaScript/ECMAScript scoping works, and gain a solid understanding of how closures work in the language. This will prevent a lot of head-scratching in the future. Google around for writings by Douglas Crockford; that's a good starting point.

tl;dr: define your local variables using the var keyword.

Title: jQuery passing parameters into .ajax()

Body:
I'm having issues passing parameters/variables into the ajax() function.

The function below accepts two parameters. One is 'element', the success option of .ajax() uses, that works fine so no need to focus on that. The 'tx' is either a single value like 'menu' or a couple of values separated by a colon like this: "menu:categories:brands"

If there is only one value in 'tx' then only one AJAX request needs to be sent and that works fine. If there is more than one value in 'tx' the function split's it using ":" is the delimiter and then passes offset[0] as the value of 'tx' into the AJAX request and then store's the rest of the values in 'x'.

What I'm having issues with is running this function recursively once the AJAX request is complete for the first value. The var 'more' stores a bool value if there is more values left to process or not. However, when I write in an if argument using 'more == true' into the success or complete option of .ajax() it doesn't reflect the value stored in that variables, it always returns false.

Before some one answers, with "You should structure the function that calls this function to only pass a single value into that parameter," lets suppose that this is an impossible venture that is outside the realm of my control.

I have no idea why this happening. I know it's probably something very simple that I'm overlooking but I've been up for about 16 hours now and this issue has plagued me for at least half that time.

Any help here is appreciated. Here is the function:

function getContent(element, tx) {
    e = element
    modAmount = tx.split(':')
    if (modAmount.length > 1) {
        x = ''
        tx = modAmount[0]
        for (i=1;i<modAmount.length;i++) {
            x = x + modAmount[i]
            if (i != (modAmount.length)-1){
                x = x+":"
            }
        }
        more = true
    }
    else {
        more = false
        tx = modAmount[0]
    }
    $.ajax({
        type: "POST",
        url: "getModule.php",
        data: "modName="+tx+"&DB=<?php echo DB ?>",
        success: function(data){
            if ($( element ).find('p').text() == "No Content"){
                $( element ).find('p').remove();
                $( element ).html("
"+data+"
")
            }
            else {
                $( element ).append("
"+data+"
");
            }
        },
        complete: function() {
            if (more == true) {alert(x)} // always returns false
        }
    });

}