text:
package at.grabner.circleprogress;

import android.animation.TimeInterpolator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.SweepGradient;
import android.graphics.Typeface;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.DecelerateInterpolator;

import java.lang.ref.WeakReference;

/**
 * An circle view, similar to Android's ProgressBar.
 * Can be used in 'value mode' or 'spinning mode'.
 *
 * In spinning mode it can be used like a intermediate progress bar.
 *
 * In value mode it can be used as a progress bar or to visualize any other value.
 * Setting a value is fully animated. There are also nice transitions from animating to value mode.
 *
 * Typical use case would be to load a new value. During the loading time set the CircleView to spinning.
 * As soon as you got your nur value, just set it {@link #setValueAnimated(float, long) setValueAnimated}, it automatically animated.
 *
 *
 * @author Jakob Grabner, based on the Progress wheel of Todd Davies
 *         https://github.com/Todd-Davies/CircleView
 *
 *         Licensed under the Creative Commons Attribution 3.0 license see:
 *         http://creativecommons.org/licenses/by/3.0/
 */
public class CircleProgressView extends View {

    /**
     * The log tag.
     */
    private final static String TAG = "CircleView";
    private static final boolean DEBUG =  false;

    //region members
    //value animation
    private float mCurrentValue = 15;
    private float mValueTo = 0;
    private float mValueFrom = 0;
    private float mMaxValue = 100;

    // spinner animation
    private float mSpinningBarLengthCurrent = 0;
    private float mSpinningBarLengthOrig = 42;
    private float mCurrentSpinnerDegreeValue = 0;

    //Sizes (with defaults)
    private int mLayoutHeight = 0;
    private int mLayoutWidth = 0;
    private int mFullRadius = 100;
    private int mCircleRadius = 80;
    private int mBarWidth = 40;
    private int mRimWidth = 40;
    private int mTextSize = 20;
    private float mContourSize = 1;
    private float mTextScale = 1;
    private float mUnitScale = 1;

    //Padding (with defaults)
    private int mPaddingTop = 5;
    private int mPaddingBottom = 5;
    private int mPaddingLeft = 5;
    private int mPaddingRight = 5;
    //Colors (with defaults)
    private final int mBarColorStandard =  0xff009688; //stylish blue
    private int mContourColor = 0xAA000000;
    private int mSpinnerColor = mBarColorStandard; //stylish blue
    private int mFillColor = 0x00000000;  //transparent
    private int mRimColor = 0xAA83d0c9;
    private int mTextColor = 0xFF000000;
    private int mUnitColor = 0xFF000000;
    private int[] mBarColors = new int[]{
            mBarColorStandard, //stylish blue
            mBarColorStandard, //stylish blue
    };
    //Caps
    private Paint.Cap mBarStrokeCap = Paint.Cap.BUTT;
    private Paint.Cap mSpinnerStrokeCap = Paint.Cap.BUTT;
    //Paints
    private Paint mBarPaint = new Paint();
    private Paint mBarSpinnerPaint = new Paint();
    private Paint mCirclePaint = new Paint();
    private Paint mRimPaint = new Paint();
    private Paint mTextPaint = new Paint();
    private Paint mUnitTextPaint = new Paint();
    private Paint mContourPaint = new Paint();
    //Rectangles
    private RectF mCircleBounds = new RectF();
    private RectF mInnerCircleBounds = new RectF();
    private RectF mTextBounds = new RectF();
    private RectF mUnitBounds = new RectF();
    private RectF mCircleOuterContour = new RectF();
    private RectF mCircleInnerContour = new RectF();
    //Animation
    //The amount of degree to move the bar by on each draw
    private float mSpinSpeed = 2.8f;
    private double mAnimationDuration = 900;

    //The number of milliseconds to wait in between each draw
    private int mDelayMillis = 15;

    // helper for AnimationState.END_SPINNING_START_ANIMATING
    private boolean mDrawArcWhileSpinning;

    //The animation handler containing the animation state machine.
    private Handler mAnimationHandler = new AnimationHandler(this);

    //The current state of the animation state machine.
    private AnimationState mAnimationState = AnimationState.IDLE;

    // The interpolator for value animations
    private TimeInterpolator mInterpolator = new AccelerateDecelerateInterpolator();

    //Other
    // The text to show
    private String mText = "";

    private String mUnit = "";
    private int mTextLength;
    /**
     * Indicates if the given text or the current percentage value should be shown.
     * true: current value (percentage or value)
     * false: given text
     */
    private boolean mAutoTextValue;
    private boolean mAutoTextSize;
    private boolean mShowPercentAsAutoValue = true;

    private boolean mShowUnit = false;
    /**
     * Relative size of the unite string to the value string.
     */
    private float mRelativeUniteSize = 0.3f;

    //endregion members

    /**
     * The constructor for the CircleView
     *
     * @param context
     * @param attrs
     */
    public CircleProgressView(Context context, AttributeSet attrs) {
        super(context, attrs);

        parseAttributes(context.obtainStyledAttributes(attrs,
                R.styleable.CircleProgressView));
    }

    /**
     * Parse the attributes passed to the view from the XML
     *
     * @param a the attributes to parse
     */
    private void parseAttributes(TypedArray a) {
        setBarWidth((int) a.getDimension(R.styleable.CircleProgressView_barWidth,
                mBarWidth));

        setRimWidth((int) a.getDimension(R.styleable.CircleProgressView_rimWidth,
                mRimWidth));

        setSpinSpeed((int) a.getDimension(R.styleable.CircleProgressView_spinSpeed,
                mSpinSpeed));

        if (a.hasValue(R.styleable.CircleProgressView_barColor) && a.hasValue(R.styleable.CircleProgressView_barColor1) && a.hasValue(R.styleable.CircleProgressView_barColor2) && a.hasValue(R.styleable.CircleProgressView_barColor3)) {
            mBarColors = new int[]{a.getColor(R.styleable.CircleProgressView_barColor, mBarColorStandard), a.getColor(R.styleable.CircleProgressView_barColor1, mBarColorStandard), a.getColor(R.styleable.CircleProgressView_barColor2, mBarColorStandard), a.getColor(R.styleable.CircleProgressView_barColor3, mBarColorStandard)};

        } else if (a.hasValue(R.styleable.CircleProgressView_barColor) && a.hasValue(R.styleable.CircleProgressView_barColor1) && a.hasValue(R.styleable.CircleProgressView_barColor2)) {

            mBarColors = new int[]{a.getColor(R.styleable.CircleProgressView_barColor, mBarColorStandard), a.getColor(R.styleable.CircleProgressView_barColor1, mBarColorStandard), a.getColor(R.styleable.CircleProgressView_barColor2, mBarColorStandard)};

        } else if (a.hasValue(R.styleable.CircleProgressView_barColor) && a.hasValue(R.styleable.CircleProgressView_barColor1)) {

            mBarColors = new int[]{a.getColor(R.styleable.CircleProgressView_barColor, mBarColorStandard), a.getColor(R.styleable.CircleProgressView_barColor1, mBarColorStandard)};

        } else {
            mBarColors = new int[]{a.getColor(R.styleable.CircleProgressView_barColor, mBarColorStandard), a.getColor(R.styleable.CircleProgressView_barColor, mBarColorStandard)};
        }

        setSpinBarColor(a.getColor(R.styleable.CircleProgressView_spinColor, mSpinnerColor));

        setSpinningBarLength(mSpinningBarLengthOrig = a.getDimension(R.styleable.CircleProgressView_spinBarLength,
                mSpinningBarLengthOrig));

        setTextSize((int) a.getDimension(R.styleable.CircleProgressView_textSize, -1));

        setTextColor(a.getColor(R.styleable.CircleProgressView_textColor,
                -1));

        setUnitColor(a.getColor(R.styleable.CircleProgressView_unitColor,
                -1));

        //if the mText is empty, show current percentage value
        setText(a.getString(R.styleable.CircleProgressView_text));

        setRimColor(a.getColor(R.styleable.CircleProgressView_rimColor,
                mRimColor));

        setFillColor(a.getColor(R.styleable.CircleProgressView_fillColor,
                mFillColor));

        setContourColor(a.getColor(R.styleable.CircleProgressView_contourColor, mContourColor));
        setContourSize(a.getDimension(R.styleable.CircleProgressView_contourSize, mContourSize));

        setMaxValue(a.getDimension(R.styleable.CircleProgressView_maxValue, mMaxValue));

        setUnit(a.getString(R.styleable.CircleProgressView_unit));
        setShowUnit(a.getBoolean(R.styleable.CircleProgressView_showUnit, mShowUnit));

        setTextScale(a.getDimension(R.styleable.CircleProgressView_textScale, mTextScale));
        setUnitScale(a.getDimension(R.styleable.CircleProgressView_unitScale, mUnitScale));

        // Recycle
        a.recycle();
    }

    /*
 * When this is called, make the view square.
 * From: http://www.jayway.com/2012/12/12/creating-custom-android-views-part-4-measuring-and-how-to-force-a-view-to-be-square/
 *
 */
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        // The first thing that happen is that we call the superclass
        // implementation of onMeasure. The reason for that is that measuring
        // can be quite a complex process and calling the super method is a
        // convenient way to get most of this complexity handled.
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        // We can't use getWidth() or getHeight() here. During the measuring
        // pass the view has not gotten its final size yet (this happens first
        // at the start of the layout pass) so we have to use getMeasuredWidth()
        // and getMeasuredHeight().
        int size = 0;
        int width = getMeasuredWidth();
        int height = getMeasuredHeight();
        int widthWithoutPadding = width - getPaddingLeft() - getPaddingRight();
        int heightWithoutPadding = height - getPaddingTop() - getPaddingBottom();

        // Finally we have some simple logic that calculates the size of the view
        // and calls setMeasuredDimension() to set that size.
        // Before we compare the width and height of the view, we remove the padding,
        // and when we set the dimension we add it back again. Now the actual content
        // of the view will be square, but, depending on the padding, the total dimensions
        // of the view might not be.
        if (widthWithoutPadding > heightWithoutPadding) {
            size = heightWithoutPadding;
        } else {
            size = widthWithoutPadding;
        }

        // If you override onMeasure() you have to call setMeasuredDimension().
        // This is how you report back the measured size.  If you don't call
        // setMeasuredDimension() the parent will throw an exception and your
        // application will crash.
        // We are calling the onMeasure() method of the superclass so we don't
        // actually need to call setMeasuredDimension() since that takes care
        // of that. However, the purpose with overriding onMeasure() was to
        // change the default behaviour and to do that we need to call
        // setMeasuredDimension() with our own values.
        setMeasuredDimension(size + getPaddingLeft() + getPaddingRight(), size + getPaddingTop() + getPaddingBottom());
    }

    private RectF getInnerCircleRect(RectF _circleBounds) {

        double circleWidth = +_circleBounds.width()-(Math.max(mBarWidth, mRimWidth)) - (mContourSize *2);
//        circleWidth = _circleBounds.width();
        double width = ((circleWidth/2d) * Math.sqrt(2d));
        float widthDelta = (_circleBounds.width() - (float) width) / 2f;

        float scaleX = 1;
        float scaleY = 1;
        if (isShowUnit()) {
            scaleX = 0.77f; // scaleX square to rectangle, so the longer text with unit fits better
            scaleY = 1.33f;
        }

        return new RectF(_circleBounds.left + (widthDelta*scaleX), _circleBounds.top + (widthDelta*scaleY), _circleBounds.right - (widthDelta*scaleX), _circleBounds.bottom -  (widthDelta*scaleY));

    }

    private  float calcTextSizeForCircle(String _text, Paint _textPaint, RectF _circleBounds) {

        //get mTextBounds bounds
        RectF innerCircleBounds = getInnerCircleRect(_circleBounds);
        return calcTextSizeForRect(_text, _textPaint, innerCircleBounds);

    }

    private static float calcTextSizeForRect(String _text, Paint _textPaint, RectF _rectBounds) {

        Matrix matrix = new Matrix();
        Rect textBoundsTmp = new Rect();

        //get current mText bounds
        _textPaint.getTextBounds(_text, 0, _text.length(), textBoundsTmp);
        RectF textBoundsTmpF = new RectF(textBoundsTmp);

        matrix.setRectToRect(textBoundsTmpF, _rectBounds, Matrix.ScaleToFit.CENTER);
        float values[] = new float[9];
        matrix.getValues(values);
        return _textPaint.getTextSize() * values[Matrix.MSCALE_X];

    }

    /**
     * Use onSizeChanged instead of onAttachedToWindow to get the dimensions of the view,
     * because this method is called after measuring the dimensions of MATCH_PARENT & WRAP_CONTENT.
     * Use this dimensions to setup the bounds and paints.
     */
    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);

        // Share the dimensions
        mLayoutWidth = w;
        mLayoutHeight = h;

        setupBounds();
        setupPaints();
        invalidate();
    }

    //region setter / getter

    public Paint.Cap getSpinnerStrokeCap() {
        return mSpinnerStrokeCap;
    }

    public void setSpinnerStrokeCap(Paint.Cap _spinnerStrokeCap) {
        mSpinnerStrokeCap = _spinnerStrokeCap;
    }

    public Paint.Cap getBarStrokeCap() {
        return mBarStrokeCap;
    }

    public void setBarStrokeCap(Paint.Cap _barStrokeCap) {
        mBarStrokeCap = _barStrokeCap;
    }

    public int getContourColor() {
        return mContourColor;
    }

    public void setContourColor(int _contourColor) {
        mContourColor = _contourColor;
    }

    public float getContourSize() {
        return mContourSize;
    }

    public void setContourSize(float _contourSize) {
        mContourSize = _contourSize;
    }

    /**
     * Set the text in the mCurrentValue bar. If no text (null or empty) is specified,
     * * the current percentage value is used
     * * (max value and current value are mandatory to do so).
     * *
     */
    public void setText(String text) {
        if (text == null || text.isEmpty()) {
            mText = "";
            mAutoTextValue = true;
        } else {
            mText = text;
            mAutoTextValue = false;
        }
        invalidate();
    }

    public String getUnit() {
        return mUnit;
    }

    public void setUnit(String _unit) {
        if (_unit == null) {
            mUnit = "";
        } else {
            mUnit = _unit;
        }
        invalidate();
    }

    /**
     * Returns the bounding rectangle of the given _text, with the size and style defined in the _textPaint centered in the middle of the _textBounds
     * @param _text   The text.
     * @param _textPaint The paint defining the text size and style.
     * @param _textBounds  The rect where the text will be centered.
     * @return The boinding box of the text centered in the _textBounds.
     */
    private  RectF getTextBounds(String _text, Paint _textPaint, RectF _textBounds) {

        Rect textBoundsTmp = new Rect();

        //get current text bounds
        _textPaint.getTextBounds(_text, 0, _text.length(), textBoundsTmp);

        //center in circle
        RectF textRect = new RectF();
        textRect.left = (_textBounds.left + ((_textBounds.width() - textBoundsTmp.width()) / 2));
        textRect.top = _textBounds.top + ((_textBounds.height() - textBoundsTmp.height()) / 2);
        textRect.right = textRect.left + textBoundsTmp.width();
        textRect.bottom = textRect.top + textBoundsTmp.height();

        return textRect;
    }

    public boolean isShowPercentAsAutoValue() {
        return mShowPercentAsAutoValue;
    }

    /**
     * If true and no text was specified. The percentage (max value, current value) is shown.
     * If false the current value is shown.
     * @param _showPercentAsAutoValue bool
     */
    public void setShowPercentAsAutoValue(boolean _showPercentAsAutoValue) {
        mShowPercentAsAutoValue = _showPercentAsAutoValue;
    }

    public int getTextSize() {
        return mTextSize;
    }

    /**
     * If text size was not set, it is automatically calculated
     * @param textSize The text size or 0 enable automatic size (default)
     */
    public void setTextSize(int textSize) {
        if (textSize > 0) {
            this.mTextSize = textSize;
            mAutoTextSize = false;
        } else {
            mAutoTextSize = true;
        }
    }

    public double getMaxValue() {
        return mMaxValue;
    }

    public void setMaxValue(float _maxValue) {
        mMaxValue = _maxValue;
    }

    public int getPaddingTop() {
        return mPaddingTop;
    }

    public void setPaddingTop(int paddingTop) {
        this.mPaddingTop = paddingTop;
    }

    public int getPaddingBottom() {
        return mPaddingBottom;
    }

    public void setPaddingBottom(int paddingBottom) {
        this.mPaddingBottom = paddingBottom;
    }

    public int getPaddingLeft() {
        return mPaddingLeft;
    }

    public void setPaddingLeft(int paddingLeft) {
        this.mPaddingLeft = paddingLeft;
    }

    public int getPaddingRight() {
        return mPaddingRight;
    }

    public void setPaddingRight(int paddingRight) {
        this.mPaddingRight = paddingRight;
    }

    public int getCircleRadius() {
        return mCircleRadius;
    }

    public boolean isShowUnit() {
        return mShowUnit;
    }

    public void setShowUnit(boolean _showUnit) {
        mShowUnit = _showUnit;
        mTextLength = 0; // triggers recalculating text sizes
        invalidate();
        mInnerCircleBounds = getInnerCircleRect(mCircleBounds);
    }

    /**
     * @return The scale value
     */
    public float getUnitScale() {
        return mUnitScale;
    }

    /**
     * Scale factor for unit text next to the main text
     * @param _unitScale The scale value between. 1 >= value > 0
     */
    public void setUnitScale(float _unitScale) {
        mUnitScale = _unitScale;
    }

    /**
     * @return The scale value
     */
    public float getTextScale() {
        return mTextScale;
    }
    /**
     * Scale factor for main text in the center of the circle view.
     * Only relevant if auto text size is enabled.
     * @param _textScale The scale value.
     */
    public void setTextScale(float _textScale) {
        mTextScale = _textScale;
    }

    /**
     * Length of spinning bar in degree.
     *
     * @param barLength length in degree
     */
    public void setSpinningBarLength(float barLength) {
        this.mSpinningBarLengthCurrent = mSpinningBarLengthOrig = barLength;
    }

    public int getBarWidth() {
        return mBarWidth;
    }

    public void setBarWidth(int barWidth) {
        this.mBarWidth = barWidth;
    }

    public int[] getBarColors() {
        return mBarColors;
    }

    public void setBarColor(int... barColors) {
        if (barColors.length == 1) {
            this.mBarColors = new int[]{barColors[0], barColors[0]};
        } else {
            this.mBarColors = barColors;
        }

    }

    public void setSpinBarColor(int _color) {
        mSpinnerColor = _color;
    }

    public int getFillColor() {
        return mFillColor;
    }

    public void setFillColor(int circleColor) {
        this.mFillColor = circleColor;
    }

    public int getRimColor() {
        return mRimColor;
    }

    public void setRimColor(int rimColor) {
        this.mRimColor = rimColor;
    }

    public Shader getRimShader() {
        return mRimPaint.getShader();
    }

    public void setRimShader(Shader shader) {
        this.mRimPaint.setShader(shader);
    }

    public int getTextColor(double value) {

        double percent = 1f / getMaxValue() * value;

        int index = (int) (mBarColors.length * percent);
        return mBarColors[index >= mBarColors.length ? mBarColors.length - 1 : index];
    }

    public int getTextColor() {
        return mTextColor;
    }

    /**
     * *
     * @param textColor the color or -1 to use auto color (depending on bar colors)
     */
    public void setTextColor(int textColor) {
        this.mTextColor = textColor;
    }

    public void setUnitColor(int textColor) {
        this.mUnitColor = textColor;
    }

    public float getSpinSpeed() {
        return mSpinSpeed;
    }

    /**
     *  The amount of degree to move the bar by on each draw
     * @param spinSpeed the speed of the spinner
     */
    public void setSpinSpeed(float spinSpeed) {
        this.mSpinSpeed = spinSpeed;
    }

    public int getRimWidth() {
        return mRimWidth;
    }

    public void setRimWidth(int rimWidth) {
        this.mRimWidth = rimWidth;
    }

    public int getDelayMillis() {
        return mDelayMillis;
    }

    public void setDelayMillis(int delayMillis) {
        this.mDelayMillis = delayMillis;
    }

    //endregion getter / setter

    //----------------------------------
    //region Setting up stuff
    //----------------------------------

    /**
     * Set the properties of the paints we're using to
     * draw all the things.
     *
     * Call this if you change colors after the view was drawn
     */
    public void setupPaints() {
        mBarPaint.setShader(new SweepGradient(mCircleBounds.centerX(), mCircleBounds.centerY(), mBarColors, null));
        Matrix matrix = new Matrix();
        mBarPaint.getShader().getLocalMatrix(matrix);

        matrix.postTranslate(-mCircleBounds.centerX(), -mCircleBounds.centerY());
        matrix.postRotate(-90);
        matrix.postTranslate(mCircleBounds.centerX(), mCircleBounds.centerY());
        mBarPaint.getShader().setLocalMatrix(matrix);

        mBarPaint.setAntiAlias(true);
        mBarPaint.setStrokeCap(mBarStrokeCap);
        mBarPaint.setStyle(Style.STROKE);
        mBarPaint.setStrokeWidth(mBarWidth);

        mBarSpinnerPaint.setAntiAlias(true);
        mBarSpinnerPaint.setStrokeCap(mSpinnerStrokeCap);
        mBarSpinnerPaint.setStyle(Style.STROKE);
        mBarSpinnerPaint.setStrokeWidth(mBarWidth);
        mBarSpinnerPaint.setColor(mSpinnerColor);

        mRimPaint.setColor(mRimColor);
        mRimPaint.setAntiAlias(true);
        mRimPaint.setStyle(Style.STROKE);
        mRimPaint.setStrokeWidth(mRimWidth);

        mCirclePaint.setColor(mFillColor);
        mCirclePaint.setAntiAlias(true);
        mCirclePaint.setStyle(Style.FILL);

        mTextPaint.setColor(mTextColor);
        mTextPaint.setStyle(Style.FILL);
        mTextPaint.setAntiAlias(true);
        mTextPaint.setTextSize(getTextSize());

        mUnitTextPaint.setColor(mUnitColor);
        mUnitTextPaint.setStyle(Style.FILL);
        mUnitTextPaint.setAntiAlias(true);
        mUnitTextPaint.setTextSize(getTextSize());

        mContourPaint.setColor(mContourColor);
        mContourPaint.setAntiAlias(true);
        mContourPaint.setStyle(Style.STROKE);
        mContourPaint.setStrokeWidth(mContourSize);
    }

    /**
     * Set the bounds of the component
     */
    private void setupBounds() {
        // Width should equal to Height, find the min value to setup the circle
        int minValue = Math.min(mLayoutWidth, mLayoutHeight);

        // Calc the Offset if needed
        int xOffset = mLayoutWidth - minValue;
        int yOffset = mLayoutHeight - minValue;

        // Add the offset
        mPaddingTop = this.getPaddingTop() + (yOffset / 2);
        mPaddingBottom = this.getPaddingBottom() + (yOffset / 2);
        mPaddingLeft = this.getPaddingLeft() + (xOffset / 2);
        mPaddingRight = this.getPaddingRight() + (xOffset / 2);

        int width = getWidth(); //this.getLayoutParams().width;
        int height = getHeight(); //this.getLayoutParams().height;

        mCircleBounds = new RectF(mPaddingLeft + mBarWidth,
                mPaddingTop + mBarWidth,
                width - mPaddingRight - mBarWidth,
                height - mPaddingBottom - mBarWidth);
        mInnerCircleBounds = getInnerCircleRect(mCircleBounds);
        mCircleInnerContour = new RectF(mCircleBounds.left + (mRimWidth / 2.0f) + (mContourSize / 2.0f), mCircleBounds.top + (mRimWidth / 2.0f) + (mContourSize / 2.0f), mCircleBounds.right - (mRimWidth / 2.0f) - (mContourSize / 2.0f), mCircleBounds.bottom - (mRimWidth / 2.0f) - (mContourSize / 2.0f));
        mCircleOuterContour = new RectF(mCircleBounds.left - (mRimWidth / 2.0f) - (mContourSize / 2.0f), mCircleBounds.top - (mRimWidth / 2.0f) - (mContourSize / 2.0f), mCircleBounds.right + (mRimWidth / 2.0f) + (mContourSize / 2.0f), mCircleBounds.bottom + (mRimWidth / 2.0f) + (mContourSize / 2.0f));

        mFullRadius = (width - mPaddingRight - mBarWidth) / 2;
        mCircleRadius = (mFullRadius - mBarWidth) + 1;
    }
    //endregion Setting up stuff

    //-----------------------
    //region draw all the things
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        if (DEBUG) {

            drawDebug(canvas);
        }

        float degrees = (360f / mMaxValue * mCurrentValue);

        //Draw the inner circle
        canvas.drawArc(mCircleBounds, 360, 360, false, mCirclePaint);
        //Draw the rim
        if(mRimWidth > 0){
            canvas.drawArc(mCircleBounds, 360, 360, false, mRimPaint);
        }
        if(mContourSize > 0){
            canvas.drawArc(mCircleOuterContour, 360, 360, false, mContourPaint);
            canvas.drawArc(mCircleInnerContour, 360, 360, false, mContourPaint);
        }

        //Draw spinner
        if (mAnimationState == AnimationState.SPINNING || mAnimationState == AnimationState.END_SPINNING) {
            drawSpinningArc(canvas);

        } else if (mAnimationState == AnimationState.END_SPINNING_START_ANIMATING) {
            //draw spinning arc
            drawSpinningArc(canvas);

            if (mDrawArcWhileSpinning) {
                drawCircleWithNumber(canvas, degrees);
            }

        } else {

            drawCircleWithNumber(canvas, degrees);
        }

    }

    private void drawSpinningArc(Canvas canvas) {

        if (mSpinningBarLengthCurrent < 0)
            mSpinningBarLengthCurrent = 1;
        float startAngle = (mCurrentSpinnerDegreeValue - 90 - mSpinningBarLengthCurrent);
        canvas.drawArc(mCircleBounds, startAngle, mSpinningBarLengthCurrent, false,
                mBarSpinnerPaint);

    }

    private void drawDebug(Canvas canvas){
        Paint innerRectPaint = new Paint();
        innerRectPaint.setColor(Color.YELLOW);
        canvas.drawRect(mCircleBounds, innerRectPaint);

        innerRectPaint.setColor(Color.MAGENTA);
        canvas.drawRect(mInnerCircleBounds, innerRectPaint);
    }

    private void drawCircleWithNumber(Canvas canvas, float _degrees) {

        float relativeGap = 1.03f; //gap size between text and unit
        boolean update = false;
        canvas.drawArc(mCircleBounds, -90, _degrees, false, mBarPaint);
        mTextPaint.setSubpixelText(true);
        mTextPaint.setLinearText(true);
        mTextPaint.setTypeface(Typeface.MONOSPACE);
        //Draw Text
        if (mTextColor == -1) //undefined
        {
            mTextPaint.setColor(getTextColor(mCurrentValue));
        }

        //set text
        String text = mText;
        if (mAutoTextValue) {
            if (mShowPercentAsAutoValue) {
                int percent = (int) (100 / mMaxValue * mCurrentValue);
                text = String.valueOf(percent);
            } else {
                text = String.valueOf((int) mCurrentValue);
            }
        }

        //set text size and position

        if (mAutoTextSize) {  // only re-calc position and size if string length changed
            if (mTextLength != text.length()) {
                update = true;
                mTextLength = text.length();
                if (mTextLength == 1) {
                    mInnerCircleBounds = new RectF(mInnerCircleBounds.left + (mInnerCircleBounds.width() * 0.1f), mInnerCircleBounds.top, mInnerCircleBounds.right - (mInnerCircleBounds.width() * 0.1f), mInnerCircleBounds.bottom);
                }else {
                    mInnerCircleBounds = getInnerCircleRect(mCircleBounds);
                }
                RectF textRect = mInnerCircleBounds;

                if (mShowUnit) {
                    //shrink text Rect so that there is space for the unit
                    textRect = new RectF(mInnerCircleBounds.left, mInnerCircleBounds.top, mInnerCircleBounds.right - ((mInnerCircleBounds.width() * (mRelativeUniteSize))*relativeGap), mInnerCircleBounds.bottom);
                }

                mTextPaint.setTextSize(calcTextSizeForRect(text, mTextPaint, textRect)* mTextScale);
                mTextBounds = getTextBounds(text, mTextPaint, textRect); // center text in text rect
            }

        } else {
            mTextBounds = getTextBounds(text, mTextPaint, mCircleBounds); //center text in circle
        }

        if (DEBUG){
            Paint rectPaint = new Paint();
            rectPaint.setColor(Color.GREEN);
            canvas.drawRect(mTextBounds, rectPaint);
        }

        canvas.drawText(text, mTextBounds.left-(mTextPaint.getTextSize()*0.09f), mTextBounds.bottom, mTextPaint);

        if (mShowUnit) {

            if (mUnitColor == -1) //undefined
            {
                mUnitTextPaint.setColor(getTextColor(mCurrentValue));
            }
            if (update) {
                //calc unit text position
                mUnitBounds = new RectF(mInnerCircleBounds.left + (mInnerCircleBounds.width() * (1 - mRelativeUniteSize) * relativeGap), mInnerCircleBounds.top, mInnerCircleBounds.right, mInnerCircleBounds.bottom);
                mUnitTextPaint.setTextSize(calcTextSizeForRect(mUnit, mUnitTextPaint, mUnitBounds) * mUnitScale);
                mUnitBounds = getTextBounds(mUnit, mUnitTextPaint, mUnitBounds);
                //move unite to top of text
                float dy = mTextBounds.top - mUnitBounds.top;
                mUnitBounds.offset(0, dy);
            }

            if (DEBUG){
                Paint rectPaint = new Paint();
                rectPaint.setColor(Color.RED);
                canvas.drawRect(mUnitBounds, rectPaint);
            }

            canvas.drawText(mUnit, mUnitBounds.left, mUnitBounds.bottom, mUnitTextPaint);
        }
    }

    //endregion draw

    //----------------------------------
    //region important getter / setter
    //----------------------------------
    /**
     * Turn off spin mode
     */
    public void stopSpinning() {
        mAnimationHandler.sendEmptyMessage(AnimationMsg.STOP_SPINNING.ordinal());
    }

    /**
     * Puts the view on spin mode
     */
    public void spin() {
        mAnimationHandler.sendEmptyMessage(AnimationMsg.START_SPINNING.ordinal());
    }

    /**
     * Set the value of the circle view without an animation.
     * Stops any currently active animations.
     */
    public void setValue(float _value) {
        Message msg = new Message();
        msg.what = AnimationMsg.SET_VALUE.ordinal();
        msg.obj = new float[]{_value, _value};
        mAnimationHandler.sendMessage(msg);
    }

    /**
     * Sets the value of the circle view with an animation.
     *
     * @param _valueFrom         start value of the animation
     * @param _valueTo           value after animation
     * @param _animationDuration the duration of the animation
     */
    public void setValueAnimated(float _valueFrom, float _valueTo, long _animationDuration) {
        mAnimationDuration = _animationDuration;
        Message msg = new Message();
        msg.what = AnimationMsg.SET_VALUE_ANIMATED.ordinal();
        msg.obj = new float[]{_valueFrom, _valueTo};
        mAnimationHandler.sendMessage(msg);
    }

    /**
     * Sets the value of the circle view with an animation.
     * The current value is used as the start value of the animation
     *
     * @param _valueTo           value after animation
     * @param _animationDuration the duration of the animation
     */
    public void setValueAnimated(float _valueTo, long _animationDuration) {

        mAnimationDuration = _animationDuration;
        Message msg = new Message();
        msg.what = AnimationMsg.SET_VALUE_ANIMATED.ordinal();
        msg.obj = new float[]{mCurrentValue, _valueTo};
        mAnimationHandler.sendMessage(msg);
    }

    /**
     * Sets the value of the circle view with an animation.
     * The current value is used as the start value of the animation
     *
     * @param _valueTo   value after animation
     */
    public void setValueAnimated(float _valueTo) {

        mAnimationDuration = 1200;
        Message msg = new Message();
        msg.what = AnimationMsg.SET_VALUE_ANIMATED.ordinal();
        msg.obj = new float[]{mCurrentValue, _valueTo};
        mAnimationHandler.sendMessage(msg);
    }
    //endregion important getter / setter

    //----------------------------------
    //region Animation stuff
    //----------------------------------

    private enum AnimationState {

        IDLE,
        SPINNING,
        END_SPINNING,
        END_SPINNING_START_ANIMATING,
        ANIMATING

    }

    private enum AnimationMsg {

        START_SPINNING,
        STOP_SPINNING,
        SET_VALUE,
        SET_VALUE_ANIMATED,
        TICK

    }

    private static class AnimationHandler extends Handler {
        private final WeakReference<CircleProgressView> mCircleViewWeakReference;
        // Spin bar length in degree at start of animation
        private float mSpinningBarLengthStart;
        private long mAnimationStartTime;
        private long mLengthChangeAnimationStartTime;
        private TimeInterpolator mLengthChangeInterpolator = new DecelerateInterpolator();
        private double mLengthChangeAnimationDuration;

        AnimationHandler(CircleProgressView _circleView) {
            super(_circleView.getContext().getMainLooper());
            mCircleViewWeakReference = new WeakReference<CircleProgressView>(_circleView);
        }

        @Override
        public void handleMessage(Message msg) {
            CircleProgressView circleView = mCircleViewWeakReference.get();
            if (circleView == null) {
                return;
            }
            AnimationMsg msgType = AnimationMsg.values()[msg.what];
            if (msgType == AnimationMsg.TICK)
                removeMessages(AnimationMsg.TICK.ordinal()); // necessary to remove concurrent ticks.

            //if (msgType != AnimationMsg.TICK)
            //    Log.d("JaGr", TAG + "LOG00099: State:" + circleView.mAnimationState + "     Received: " + msgType);

            switch (circleView.mAnimationState) {

                case IDLE:
                    switch (msgType) {

                        case START_SPINNING:
                            enterSpinning(circleView);

                            break;
                        case STOP_SPINNING:
                            //IGNORE not spinning
                            break;
                        case SET_VALUE:
                            setValue(msg, circleView);
                            break;
                        case SET_VALUE_ANIMATED:

                            enterSetValueAnimated(msg, circleView);
                            break;
                        case TICK:
                            removeMessages(AnimationMsg.TICK.ordinal()); // remove old ticks
                            //IGNORE nothing to do
                            break;
                    }
                    break;
                case SPINNING:
                    switch (msgType) {

                        case START_SPINNING:
                            //IGNORE already spinning
                            break;
                        case STOP_SPINNING:
                            enterEndSpinning(circleView);

                            break;
                        case SET_VALUE:
                            setValue(msg, circleView);
                            break;
                        case SET_VALUE_ANIMATED:
                            enterEndSpinningStartAnimating(circleView, msg);
                            break;
                        case TICK:
                            // set length

                            float length_delta = circleView.mSpinningBarLengthCurrent - circleView.mSpinningBarLengthOrig;
                            float t = (float) ((System.currentTimeMillis() - mLengthChangeAnimationStartTime)
                                                                / mLengthChangeAnimationDuration);
                            t = t > 1.0f ? 1.0f : t;
                            float interpolatedRatio = mLengthChangeInterpolator.getInterpolation(t);

                            if (Math.abs(length_delta) < 1) {
                                //spinner length is within bounds
                                circleView.mSpinningBarLengthCurrent = circleView.mSpinningBarLengthOrig;
                            } else if (circleView.mSpinningBarLengthCurrent < circleView.mSpinningBarLengthOrig) {
                                //spinner to short, --> grow
                                circleView.mSpinningBarLengthCurrent = mSpinningBarLengthStart + ((circleView.mSpinningBarLengthOrig - mSpinningBarLengthStart) * interpolatedRatio);
                            } else {
                                //spinner to long, --> shrink
                                circleView.mSpinningBarLengthCurrent = (mSpinningBarLengthStart - ((mSpinningBarLengthStart - circleView.mSpinningBarLengthOrig) * interpolatedRatio));
                            }

                            circleView.mCurrentSpinnerDegreeValue += circleView.mSpinSpeed; // spin speed value (in degree)

                            if (circleView.mCurrentSpinnerDegreeValue > 360) {
                                circleView.mCurrentSpinnerDegreeValue = 0;
                            }
                            circleView.mAnimationHandler.sendEmptyMessageDelayed(AnimationMsg.TICK.ordinal(), circleView.mDelayMillis);
                            circleView.invalidate();
                            break;
                    }

                    break;
                case END_SPINNING:
                    switch (msgType) {

                        case START_SPINNING:
                            circleView.mAnimationState = AnimationState.SPINNING;
                            circleView.mAnimationHandler.sendEmptyMessageDelayed(AnimationMsg.TICK.ordinal(), circleView.mDelayMillis);

                            break;
                        case STOP_SPINNING:
                            //IGNORE already stopping
                            break;
                        case SET_VALUE:
                            setValue(msg, circleView);
                            break;
                        case SET_VALUE_ANIMATED:
                            enterEndSpinningStartAnimating(circleView, msg);

                            break;
                        case TICK:

                            float t = (float) ((System.currentTimeMillis() - mLengthChangeAnimationStartTime)
                                    / mLengthChangeAnimationDuration);
                            t = t > 1.0f ? 1.0f : t;
                            float interpolatedRatio = mLengthChangeInterpolator.getInterpolation(t);
                            circleView.mSpinningBarLengthCurrent = (mSpinningBarLengthStart) * (1f - interpolatedRatio);

                            circleView.mCurrentSpinnerDegreeValue += circleView.mSpinSpeed; // spin speed value (not in percent)
                            if (circleView.mSpinningBarLengthCurrent < 0.01f) {
                                //end here, spinning finished
                                circleView.mAnimationState = AnimationState.IDLE;
                            }
                            circleView.mAnimationHandler.sendEmptyMessageDelayed(AnimationMsg.TICK.ordinal(), circleView.mDelayMillis);
                            circleView.invalidate();
                            break;
                    }

                    break;
                case END_SPINNING_START_ANIMATING:
                    switch (msgType) {

                        case START_SPINNING:
                            circleView.mDrawArcWhileSpinning = false;
                            enterSpinning(circleView);

                            break;
                        case STOP_SPINNING:
                            //IGNORE already stopping
                            break;
                        case SET_VALUE:
                            circleView.mDrawArcWhileSpinning = false;
                            setValue(msg, circleView);

                            break;
                        case SET_VALUE_ANIMATED:
                            circleView.mValueFrom = 0; // start from zero after spinning
                            circleView.mValueTo = ((float[]) msg.obj)[1];
                            circleView.mAnimationHandler.sendEmptyMessageDelayed(AnimationMsg.TICK.ordinal(), circleView.mDelayMillis);

                            break;
                        case TICK:
                            //shrink spinner till it has its original length
                            if (circleView.mSpinningBarLengthCurrent > circleView.mSpinningBarLengthOrig && !circleView.mDrawArcWhileSpinning) {
                                //spinner to long, --> shrink
                                float t = (float) ((System.currentTimeMillis() - mLengthChangeAnimationStartTime)
                                        / mLengthChangeAnimationDuration);
                                t = t > 1.0f ? 1.0f : t;
                                float interpolatedRatio = mLengthChangeInterpolator.getInterpolation(t);
                                circleView.mSpinningBarLengthCurrent = (mSpinningBarLengthStart) * (1f - interpolatedRatio);
                            }

                            // move spinner for spin speed value (not in percent)
                            circleView.mCurrentSpinnerDegreeValue += circleView.mSpinSpeed;

                            //if the start of the spinner reaches zero, start animating the value
                            if (circleView.mCurrentSpinnerDegreeValue > 360 && !circleView.mDrawArcWhileSpinning) {
                                mAnimationStartTime = System.currentTimeMillis();
                                circleView.mDrawArcWhileSpinning = true;
                                initReduceAnimation(circleView);
                            }

                            //value is already animating, calc animation value and reduce spinner
                            if (circleView.mDrawArcWhileSpinning) {
                                circleView.mCurrentSpinnerDegreeValue = 360;
                                circleView.mSpinningBarLengthCurrent -= circleView.mSpinSpeed;
                                calcNextAnimationValue(circleView);

                                float t = (float) ((System.currentTimeMillis() - mLengthChangeAnimationStartTime)
                                        / mLengthChangeAnimationDuration);
                                t = t > 1.0f ? 1.0f : t;
                                float interpolatedRatio = mLengthChangeInterpolator.getInterpolation(t);
                                circleView.mSpinningBarLengthCurrent = (mSpinningBarLengthStart) * (1f - interpolatedRatio);
                            }

                            //spinner is no longer visible switch state to animating
                            if (circleView.mSpinningBarLengthCurrent < 0.1) {
                                //spinning finished, start animating the current value
                                circleView.mAnimationState = AnimationState.ANIMATING;
                                circleView.invalidate();
                                circleView.mDrawArcWhileSpinning = false;
                                circleView.mSpinningBarLengthCurrent = circleView.mSpinningBarLengthOrig;

                            } else {
                                circleView.invalidate();
                            }
                            circleView.mAnimationHandler.sendEmptyMessageDelayed(AnimationMsg.TICK.ordinal(), circleView.mDelayMillis);
                            break;
                    }

                    break;
                case ANIMATING:
                    switch (msgType) {

                        case START_SPINNING:
                            enterSpinning(circleView);
                            break;
                        case STOP_SPINNING:
                            //Ignore, not spinning
                            break;
                        case SET_VALUE:
                            setValue(msg, circleView);
                            break;
                        case SET_VALUE_ANIMATED:
                            mAnimationStartTime = System.currentTimeMillis();
                            //restart animation from current value
                            circleView.mValueFrom = circleView.mCurrentValue;
                            circleView.mValueTo = ((float[]) msg.obj)[1];

                            break;
                        case TICK:
                            if(calcNextAnimationValue(circleView)){
                                //animation finished
                                circleView.mAnimationState = AnimationState.IDLE;
                                circleView.mCurrentValue = circleView.mValueTo;
                            }
                            circleView.mAnimationHandler.sendEmptyMessageDelayed(AnimationMsg.TICK.ordinal(), circleView.mDelayMillis);
                            circleView.invalidate();
                            break;
                    }

                    break;

            }
        }

        private void enterSetValueAnimated(Message msg, CircleProgressView _circleView) {
            _circleView.mValueFrom = ((float[]) msg.obj)[0];
            _circleView.mValueTo = ((float[]) msg.obj)[1];
            mAnimationStartTime = System.currentTimeMillis();
            _circleView.mAnimationState = AnimationState.ANIMATING;

            _circleView.mAnimationHandler.sendEmptyMessageDelayed(AnimationMsg.TICK.ordinal(), _circleView.mDelayMillis);
        }

        private void enterEndSpinningStartAnimating(CircleProgressView circleView, Message msg) {
            circleView.mAnimationState = AnimationState.END_SPINNING_START_ANIMATING;

            circleView.mValueFrom = 0; // start from zero after spinning
            circleView.mValueTo = ((float[]) msg.obj)[1];

            mLengthChangeAnimationStartTime = System.currentTimeMillis();
            mSpinningBarLengthStart = circleView.mSpinningBarLengthCurrent;

            circleView.mAnimationHandler.sendEmptyMessageDelayed(AnimationMsg.TICK.ordinal(), circleView.mDelayMillis);

        }

        private void enterEndSpinning(CircleProgressView circleView) {
            circleView.mAnimationState = AnimationState.END_SPINNING;

            initReduceAnimation(circleView);
            circleView.mAnimationHandler.sendEmptyMessageDelayed(AnimationMsg.TICK.ordinal(), circleView.mDelayMillis);
        }

        private void initReduceAnimation(CircleProgressView circleView) {
            float degreesTillFinish = circleView.mSpinningBarLengthCurrent;
            float stepsTillFinish = degreesTillFinish / circleView.mSpinSpeed;
            mLengthChangeAnimationDuration = (stepsTillFinish * circleView.mDelayMillis) * 2f;

            mLengthChangeAnimationStartTime = System.currentTimeMillis();
            mSpinningBarLengthStart = circleView.mSpinningBarLengthCurrent;
        }

        private void enterSpinning(CircleProgressView circleView) {
            circleView.mAnimationState = AnimationState.SPINNING;
            circleView.mSpinningBarLengthCurrent = (360f / circleView.mMaxValue * circleView.mCurrentValue);
            circleView.mCurrentSpinnerDegreeValue = (360f / circleView.mMaxValue * circleView.mCurrentValue);
            mLengthChangeAnimationStartTime = System.currentTimeMillis();
            mSpinningBarLengthStart = circleView.mSpinningBarLengthCurrent;

            //calc animation time
            float stepsTillFinish = circleView.mSpinningBarLengthOrig / circleView.mSpinSpeed;
            mLengthChangeAnimationDuration = ((stepsTillFinish * circleView.mDelayMillis) * 2f);

            circleView.mAnimationHandler.sendEmptyMessageDelayed(AnimationMsg.TICK.ordinal(), circleView.mDelayMillis);
        }

        /**
         * *
         * @param _circleView the circle view
         * @return false if animation still running, true if animation is finished.
         */
        private boolean calcNextAnimationValue(CircleProgressView _circleView) {
            float t = (float) ((System.currentTimeMillis() - mAnimationStartTime)
                    / _circleView.mAnimationDuration);
            t = t > 1.0f ? 1.0f : t;
            float interpolatedRatio = _circleView.mInterpolator.getInterpolation(t);

            _circleView.mCurrentValue = (_circleView.mValueFrom + ((_circleView.mValueTo - _circleView.mValueFrom) * interpolatedRatio));

            return t >= 1;
        }

        private void setValue(Message msg, CircleProgressView _circleView) {
            _circleView.mValueFrom = _circleView.mValueTo;
            _circleView.mCurrentValue = _circleView.mValueTo = ((float[]) msg.obj)[0];
            _circleView.mAnimationState = AnimationState.IDLE;
            _circleView.invalidate();
        }
    }

    //endregion Animation stuff
    //----------------------------------
}


text:
'use strict';

var express = require('express');
var mongoose = require('mongoose');
var passport = require('passport');
var session = require('express-session');
var morgan = require('morgan');
var bodyParser = require('body-parser');

var appRoutes = require('./app/routes/appRoutes.js');
var authRoutes = require('./app/routes/authRoutes.js');
var errorRoutes = require('./app/routes/errorRoutes.js');

var app = express();
//require('dotenv').load();
require('./app/config/passport')(passport);
app.use(morgan('dev'));

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

mongoose.connect(process.env.MONGO_URI);
mongoose.Promise = global.Promise;

app.set('view engine', 'pug');
app.set('views', process.cwd() + '/views');

app.use('/controllers', express.static(process.cwd() + '/app/controllers'));
app.use('/public', express.static(process.cwd() + '/public'));
app.use('/common', express.static(process.cwd() + '/app/common'));
app.use('/node_modules', express.static(process.cwd() + '/node_modules'));

app.use(session({
	secret: 'secretPollPlace',
	resave: false,
	saveUninitialized: true
}));

app.use(passport.initialize());
app.use(passport.session());

appRoutes(app, passport);
authRoutes(app, passport);
errorRoutes(app, passport);

var port = process.env.PORT || 8080;
app.listen(port,  function () {
	console.log('Node.js listening on port ' + port + '...');
});

redpajama_set_name: RedPajamaGithub


text:
'use strict';

var _ = require('lodash');
var Q = require('q');
var Page = require('../../../base/Page');
var deserialize = require('../../../base/deserialize');
var values = require('../../../base/values');

var RatePlanPage;
var RatePlanList;
var RatePlanInstance;
var RatePlanContext;

/* jshint ignore:start */
/**
 * @constructor Twilio.Preview.Wireless.RatePlanPage
 * @augments Page
 * @description Initialize the RatePlanPage
 *
 * @param {Twilio.Preview.Wireless} version - Version of the resource
 * @param {object} response - Response from the API
 * @param {object} solution - Path solution
 *
 * @returns RatePlanPage
 */
/* jshint ignore:end */
function RatePlanPage(version, response, solution) {
  // Path Solution
  this._solution = solution;

  Page.prototype.constructor.call(this, version, response, this._solution);
}

_.extend(RatePlanPage.prototype, Page.prototype);
RatePlanPage.prototype.constructor = RatePlanPage;

/* jshint ignore:start */
/**
 * Build an instance of RatePlanInstance
 *
 * @function getInstance
 * @memberof Twilio.Preview.Wireless.RatePlanPage
 * @instance
 *
 * @param {object} payload - Payload response from the API
 *
 * @returns RatePlanInstance
 */
/* jshint ignore:end */
RatePlanPage.prototype.getInstance = function getInstance(payload) {
  return new RatePlanInstance(
    this._version,
    payload
  );
};

/* jshint ignore:start */
/**
 * @constructor Twilio.Preview.Wireless.RatePlanList
 * @description Initialize the RatePlanList
 *
 * @param {Twilio.Preview.Wireless} version - Version of the resource
 */
/* jshint ignore:end */
function RatePlanList(version) {
  /* jshint ignore:start */
  /**
   * @function ratePlans
   * @memberof Twilio.Preview.Wireless
   * @instance
   *
   * @param {string} sid - sid of instance
   *
   * @returns {Twilio.Preview.Wireless.RatePlanContext}
   */
  /* jshint ignore:end */
  function RatePlanListInstance(sid) {
    return RatePlanListInstance.get(sid);
  }

  RatePlanListInstance._version = version;
  // Path Solution
  RatePlanListInstance._solution = {};
  RatePlanListInstance._uri = _.template(
    '/RatePlans' // jshint ignore:line
  )(RatePlanListInstance._solution);
  /* jshint ignore:start */
  /**
   * Streams RatePlanInstance records from the API.
   *
   * This operation lazily loads records as efficiently as possible until the limit
   * is reached.
   *
   * The results are passed into the callback function, so this operation is memory efficient.
   *
   * If a function is passed as the first argument, it will be used as the callback function.
   *
   * @function each
   * @memberof Twilio.Preview.Wireless.RatePlanList
   * @instance
   *
   * @param {object|function} opts - ...
   * @param {number} [opts.limit] -
   *         Upper limit for the number of records to return.
   *         each() guarantees never to return more than limit.
   *         Default is no limit
   * @param {number} [opts.pageSize=50] -
   *         Number of records to fetch per request,
   *         when not set will use the default value of 50 records.
   *         If no pageSize is defined but a limit is defined,
   *         each() will attempt to read the limit with the most efficient
   *         page size, i.e. min(limit, 1000)
   * @param {Function} [opts.callback] -
   *         Function to process each record. If this and a positional
   * callback are passed, this one will be used
   * @param {Function} [opts.done] -
   *          Function to be called upon completion of streaming
   * @param {Function} [callback] - Function to process each record
   */
  /* jshint ignore:end */
  RatePlanListInstance.each = function each(opts, callback) {
    opts = opts || {};
    if (_.isFunction(opts)) {
      opts = { callback: opts };
    } else if (_.isFunction(callback) && !_.isFunction(opts.callback)) {
      opts.callback = callback;
    }

    if (_.isUndefined(opts.callback)) {
      throw new Error('Callback function must be provided');
    }

    var done = false;
    var currentPage = 1;
    var limits = this._version.readLimits({
      limit: opts.limit,
      pageSize: opts.pageSize
    });

    function onComplete(error) {
      done = true;
      if (_.isFunction(opts.done)) {
        opts.done(error);
      }
    }

    function fetchNextPage(fn) {
      var promise = fn();
      if (_.isUndefined(promise)) {
        onComplete();
        return;
      }

      promise.then(function(page) {
        _.each(page.instances, function(instance) {
          if (done) {
            return false;
          }

          opts.callback(instance, onComplete);
        });

        if ((limits.pageLimit && limits.pageLimit <= currentPage)) {
          onComplete();
        } else if (!done) {
          currentPage++;
          fetchNextPage(_.bind(page.nextPage, page));
        }
      });

      promise.catch(onComplete);
    }

    fetchNextPage(_.bind(this.page, this, opts));
  };

  /* jshint ignore:start */
  /**
   * @description Lists RatePlanInstance records from the API as a list.
   *
   * If a function is passed as the first argument, it will be used as the callback function.
   *
   * @function list
   * @memberof Twilio.Preview.Wireless.RatePlanList
   * @instance
   *
   * @param {object|function} opts - ...
   * @param {number} [opts.limit] -
   *         Upper limit for the number of records to return.
   *         list() guarantees never to return more than limit.
   *         Default is no limit
   * @param {number} [opts.pageSize] -
   *         Number of records to fetch per request,
   *         when not set will use the default value of 50 records.
   *         If no page_size is defined but a limit is defined,
   *         list() will attempt to read the limit with the most
   *         efficient page size, i.e. min(limit, 1000)
   * @param {function} [callback] - Callback to handle list of records
   *
   * @returns {Promise} Resolves to a list of records
   */
  /* jshint ignore:end */
  RatePlanListInstance.list = function list(opts, callback) {
    if (_.isFunction(opts)) {
      callback = opts;
      opts = {};
    }
    opts = opts || {};
    var deferred = Q.defer();
    var allResources = [];
    opts.callback = function(resource, done) {
      allResources.push(resource);

      if (!_.isUndefined(opts.limit) && allResources.length === opts.limit) {
        done();
      }
    };

    opts.done = function(error) {
      if (_.isUndefined(error)) {
        deferred.resolve(allResources);
      } else {
        deferred.reject(error);
      }
    };

    if (_.isFunction(callback)) {
      deferred.promise.nodeify(callback);
    }

    this.each(opts);
    return deferred.promise;
  };

  /* jshint ignore:start */
  /**
   * Retrieve a single page of RatePlanInstance records from the API.
   * Request is executed immediately
   *
   * If a function is passed as the first argument, it will be used as the callback function.
   *
   * @function page
   * @memberof Twilio.Preview.Wireless.RatePlanList
   * @instance
   *
   * @param {object|function} opts - ...
   * @param {string} [opts.pageToken] - PageToken provided by the API
   * @param {number} [opts.pageNumber] -
   *          Page Number, this value is simply for client state
   * @param {number} [opts.pageSize] - Number of records to return, defaults to 50
   * @param {function} [callback] - Callback to handle list of records
   *
   * @returns {Promise} Resolves to a list of records
   */
  /* jshint ignore:end */
  RatePlanListInstance.page = function page(opts, callback) {
    opts = opts || {};

    var deferred = Q.defer();
    var data = values.of({
      'PageToken': opts.pageToken,
      'Page': opts.pageNumber,
      'PageSize': opts.pageSize
    });

    var promise = this._version.page({
      uri: this._uri,
      method: 'GET',
      params: data
    });

    promise = promise.then(function(payload) {
      deferred.resolve(new RatePlanPage(
        this._version,
        payload,
        this._solution
      ));
    }.bind(this));

    promise.catch(function(error) {
      deferred.reject(error);
    });

    if (_.isFunction(callback)) {
      deferred.promise.nodeify(callback);
    }

    return deferred.promise;
  };

  /* jshint ignore:start */
  /**
   * Constructs a rate_plan
   *
   * @function get
   * @memberof Twilio.Preview.Wireless.RatePlanList
   * @instance
   *
   * @param {string} sid - The sid
   *
   * @returns {Twilio.Preview.Wireless.RatePlanContext}
   */
  /* jshint ignore:end */
  RatePlanListInstance.get = function get(sid) {
    return new RatePlanContext(
      this._version,
      sid
    );
  };

  return RatePlanListInstance;
}

/* jshint ignore:start */
/**
 * @constructor Twilio.Preview.Wireless.RatePlanInstance
 * @description Initialize the RatePlanContext
 *
 * @property {string} sid - The sid
 * @property {string} alias - The alias
 * @property {string} accountSid - The account_sid
 * @property {string} friendlyName - The friendly_name
 * @property {string} dataMetering - The data_metering
 * @property {string} capabilities - The capabilities
 * @property {number} voiceCap - The voice_cap
 * @property {number} messagingCap - The messaging_cap
 * @property {number} commandsCap - The commands_cap
 * @property {number} dataCap - The data_cap
 * @property {number} capPeriod - The cap_period
 * @property {string} capUnit - The cap_unit
 * @property {Date} dateCreated - The date_created
 * @property {Date} dateUpdated - The date_updated
 * @property {string} url - The url
 *
 * @param {Twilio.Preview.Wireless} version - Version of the resource
 * @param {object} payload - The instance payload
 * @param {string} sid - The sid
 */
/* jshint ignore:end */
function RatePlanInstance(version, payload, sid) {
  this._version = version;

  // Marshaled Properties
  this.sid = payload.sid; // jshint ignore:line
  this.alias = payload.alias; // jshint ignore:line
  this.accountSid = payload.account_sid; // jshint ignore:line
  this.friendlyName = payload.friendly_name; // jshint ignore:line
  this.dataMetering = payload.data_metering; // jshint ignore:line
  this.capabilities = payload.capabilities; // jshint ignore:line
  this.voiceCap = deserialize.integer(payload.voice_cap); // jshint ignore:line
  this.messagingCap = deserialize.integer(payload.messaging_cap); // jshint ignore:line
  this.commandsCap = deserialize.integer(payload.commands_cap); // jshint ignore:line
  this.dataCap = deserialize.integer(payload.data_cap); // jshint ignore:line
  this.capPeriod = deserialize.integer(payload.cap_period); // jshint ignore:line
  this.capUnit = payload.cap_unit; // jshint ignore:line
  this.dateCreated = deserialize.iso8601DateTime(payload.date_created); // jshint ignore:line
  this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); // jshint ignore:line
  this.url = payload.url; // jshint ignore:line

  // Context
  this._context = undefined;
  this._solution = {
    sid: sid || this.sid,
  };
}

Object.defineProperty(RatePlanInstance.prototype,
  '_proxy', {
  get: function() {
    if (!this._context) {
      this._context = new RatePlanContext(
        this._version,
        this._solution.sid
      );
    }

    return this._context;
  },
});

/* jshint ignore:start */
/**
 * fetch a RatePlanInstance
 *
 * @function fetch
 * @memberof Twilio.Preview.Wireless.RatePlanInstance
 * @instance
 *
 * @param {function} [callback] - Callback to handle processed record
 *
 * @returns {Promise} Resolves to processed RatePlanInstance
 */
/* jshint ignore:end */
RatePlanInstance.prototype.fetch = function fetch(callback) {
  return this._proxy.fetch(callback);
};

/* jshint ignore:start */
/**
 * @constructor Twilio.Preview.Wireless.RatePlanContext
 * @description Initialize the RatePlanContext
 *
 * @param {Twilio.Preview.Wireless} version - Version of the resource
 * @param {string} sid - The sid
 */
/* jshint ignore:end */
function RatePlanContext(version, sid) {
  this._version = version;

  // Path Solution
  this._solution = {
    sid: sid,
  };
  this._uri = _.template(
    '/RatePlans/<%= sid %>' // jshint ignore:line
  )(this._solution);
}

/* jshint ignore:start */
/**
 * fetch a RatePlanInstance
 *
 * @function fetch
 * @memberof Twilio.Preview.Wireless.RatePlanContext
 * @instance
 *
 * @param {function} [callback] - Callback to handle processed record
 *
 * @returns {Promise} Resolves to processed RatePlanInstance
 */
/* jshint ignore:end */
RatePlanContext.prototype.fetch = function fetch(callback) {
  var deferred = Q.defer();
  var promise = this._version.fetch({
    uri: this._uri,
    method: 'GET'
  });

  promise = promise.then(function(payload) {
    deferred.resolve(new RatePlanInstance(
      this._version,
      payload,
      this._solution.sid
    ));
  }.bind(this));

  promise.catch(function(error) {
    deferred.reject(error);
  });

  if (_.isFunction(callback)) {
    deferred.promise.nodeify(callback);
  }

  return deferred.promise;
};

module.exports = {
  RatePlanPage: RatePlanPage,
  RatePlanList: RatePlanList,
  RatePlanInstance: RatePlanInstance,
  RatePlanContext: RatePlanContext
};


text:
require 'spec_helper'

describe Bigcommerce::CustomerAddress do
  before(:each) { @address = Bigcommerce::CustomerAddress }

  let(:params) { 1 }

  describe '.count' do
    it 'should hit the correct path' do
      expect(@address).to receive(:get).with('customers/1/addresses/count')
      @address.count params
    end
  end

  describe '.count_all' do
    it 'should hit the correct path' do
      expect(@address).to receive(:get).with('customers/addresses/count')
      @address.count_all
    end
  end
end


text:
.highcharts-tooltip span {
    background-color:white;
    border:1px solid black;
    border-radius: 6px;
    padding: 5px;
    opacity:1;
    z-index:9999!important;
}

.label {
 z-index: 1!important;
}

.tooltip {
    padding: 5px;
}


text:
go-wrk - an HTTP benchmarking tool
==================================

go-wrk is a modern HTTP benchmarking tool capable of generating significant load when run on a single multi-core CPU. It builds on go language go routines and scheduler for behind the scenes async IO and concurrency.

It was created mostly to examine go language (http://golang.org) performance and verbosity compared to C (the language wrk was written in. See - <https://github.com/wg/wrk>).
It turns out that it is just as good in terms of throughput! And with a lot less code.

The majority of go-wrk is the product of one afternoon, and its quality is comparable to wrk.

Building
--------

    go install github.com/tsliwowicz/go-wrk@latest

This will download and compile go-wrk.

Command line parameters (./go-wrk -help)

       Usage: go-wrk <options> <url>
       Options:
        -H       Header to add to each request (you can define multiple -H flags) (Default )
        -M       HTTP method (Default GET)
        -T       Socket/request timeout in ms (Default 1000)
        -body    request body string or @filename (Default )
        -c       Number of goroutines to use (concurrent connections) (Default 10)
        -ca      CA file to verify peer against (SSL/TLS) (Default )
        -cert    CA certificate file to verify peer against (SSL/TLS) (Default )
        -d       Duration of test in seconds (Default 10)
        -f       Playback file name (Default <empty>)
        -help    Print help (Default false)
        -host    Host Header (Default )
        -http    Use HTTP/2 (Default true)
        -key     Private key file name (SSL/TLS (Default )
        -no-c    Disable Compression - Prevents sending the "Accept-Encoding: gzip" header (Default false)
        -no-ka   Disable KeepAlive - prevents re-use of TCP connections between different HTTP requests (Default false)
        -no-vr   Skip verifying SSL certificate of the server (Default false)
        -redir   Allow Redirects (Default false)
        -v       Print version details (Default false)

Basic Usage
-----------

    ./go-wrk -c 80 -d 5  http://192.168.1.118:8080/json

This runs a benchmark for 5 seconds, using 80 go routines (connections)

Output:

    Running 10s test @ http://192.168.1.118:8080/json
      80 goroutine(s) running concurrently
       142470 requests in 4.949028953s, 19.57MB read
         Requests/sec:		28787.47
         Transfer/sec:		3.95MB
         Avg Req Time:		0.0347ms
         Fastest Request:	0.0340ms
         Slowest Request:	0.0421ms
         Number of Errors:	0

Benchmarking Tips
-----------------

  The machine running go-wrk must have a sufficient number of ephemeral ports
  available and closed sockets should be recycled quickly. To handle the
  initial connection burst the server's listen(2) backlog should be greater
  than the number of concurrent connections being tested.

Acknowledgements
----------------

  golang is awesome. I did not need anything but this to create go-wrk.
  I fully credit the wrk project (https://github.com/wg/wrk) for the inspiration and even parts of this text.
  I also used similar command line arguments format and output format.


text:
from model.ddpg_model import Model
from agent.ddpg import Agent
from mechanism.replay_buffer import Replay_Buffer
from mechanism.ou_process import OU_Process
from gym import wrappers
import gym
import numpy as np

ENV_NAME = 'Pendulum-v0'
EPISODES = 100000
MAX_EXPLORE_EPS = 100
TEST_EPS = 1
BATCH_SIZE = 64
BUFFER_SIZE = 1e6
WARM_UP_MEN = 5 * BATCH_SIZE
DISCOUNT_FACTOR = 0.99
ACTOR_LEARNING_RATE = 1e-4
CRITIC_LEARNING_RATE = 1e-3
TAU = 0.001

def main():
    env = gym.make(ENV_NAME)
    env = wrappers.Monitor(env, ENV_NAME+"experiment-1", force=True)
    state_dim = env.observation_space.shape[0]
    action_dim = env.action_space.shape[0]
    model = Model(state_dim,
                  action_dim,
                  actor_learning_rate=ACTOR_LEARNING_RATE,
                  critic_learning_rate=CRITIC_LEARNING_RATE,
                  tau=TAU)
    replay_buffer = Replay_Buffer(buffer_size=int(BUFFER_SIZE) ,batch_size=BATCH_SIZE)
    exploration_noise = OU_Process(action_dim)
    agent = Agent(model, replay_buffer, exploration_noise, discout_factor=DISCOUNT_FACTOR)

    action_mean = 0
    i = 0
    for episode in range(EPISODES):
        state = env.reset()
        agent.init_process()
        # Training:
        for step in range(env.spec.timestep_limit):
            # env.render()
            state = np.reshape(state, (1, -1))
            if episode < MAX_EXPLORE_EPS:
                p = episode / MAX_EXPLORE_EPS
                action = np.clip(agent.select_action(state, p), -1.0, 1.0)
            else:
                action = agent.predict_action(state)
            action_ = action * 2
            next_state, reward, done, _ = env.step(action_)
            next_state = np.reshape(next_state, (1, -1))
            agent.store_transition([state, action, reward, next_state, done])
            if agent.replay_buffer.memory_state()["current_size"] > WARM_UP_MEN:
                agent.train_model()
            else:
                i += 1
                action_mean = action_mean + (action - action_mean) / i
                print("running action mean: {}".format(action_mean))
            state = next_state
            if done:
                break

        # Testing:
        if episode % 2 == 0 and episode > 10:
            total_reward = 0
            for i in range(TEST_EPS):
                state = env.reset()
                for j in range(env.spec.timestep_limit):
                    # env.render()
                    state = np.reshape(state, (1, 3))
                    action = agent.predict_action(state)
                    action_ = action * 2
                    state, reward, done, _ = env.step(action_)
                    total_reward += reward
                    if done:
                        break
            avg_reward = total_reward/TEST_EPS
            print("episode: {}, Evaluation Average Reward: {}".format(episode, avg_reward))

if __name__ == '__main__':
    main()


text:
package org.artifactory.storage.db.fs.session;

import org.artifactory.repo.RepoPath;
import org.artifactory.storage.fs.lock.FsItemLockEntry;
import org.artifactory.storage.fs.lock.LockEntryId;
import org.artifactory.storage.fs.lock.SessionLockEntry;
import org.artifactory.storage.fs.session.StorageSession;
import org.artifactory.storage.tx.SessionResource;
import org.artifactory.storage.tx.SessionResourceManager;
import org.artifactory.storage.tx.SessionResourceManagerImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Nullable;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Represents a thread bound storage session in a context of a transaction.
 *
 * @author Yossi Shaul
 */
public class SqlStorageSession implements StorageSession {
    private static final Logger log = LoggerFactory.getLogger(SqlStorageSession.class);

    private final Map<RepoPath, SessionLockEntry> locks = new LinkedHashMap<>();
    private SessionResourceManager sessionResourceManager;

    @Override
    public void save() {
        if (sessionResourceManager != null) {
            sessionResourceManager.onSessionSave();
        }

        if (locks.size() == 0) {
            log.trace("Save called on session with no locked items");
            return;
        }

        log.debug("Save called on session with {} locked items", locks.size());

        Iterator<Map.Entry<RepoPath, SessionLockEntry>> locksIter = locks.entrySet().iterator();
        while (locksIter.hasNext()) {
            SessionLockEntry lockEntry = locksIter.next().getValue();
            if (lockEntry.isWriteLockedByMe()) {
                lockEntry.save();
                if (lockEntry.isDeleted()) {
                    // deleted items are removed immediately from the session to support simpler override during move/copy
                    lockEntry.unlock();
                    locksIter.remove();
                }
            }
        }

    }

    @Override
    public void releaseResources() {
        log.trace("Release all locks of lm={}", this.hashCode());
        try {
            Collection<SessionLockEntry> lockEntries = locks.values();
            for (SessionLockEntry lockEntry : lockEntries) {
                lockEntry.unlock();
            }
        } finally {
            locks.clear();
        }
    }

    @Override
    public FsItemLockEntry writeLock(LockEntryId lockEntryId) {
        SessionLockEntry sessionLockEntry = getOrCreateSessionLockEntry(lockEntryId);
        sessionLockEntry.acquireWriteLock();
        return sessionLockEntry;
    }

    @Override
    public boolean removeLockEntry(RepoPath repoPath) {
        SessionLockEntry lockEntry = locks.remove(repoPath);
        if (lockEntry == null) {
            log.debug("Removing lock entry {} but not locked by me!", repoPath);
            return false;
        } else {
            log.trace("Removed lock entry {} for lm={}", repoPath, this.hashCode());
            lockEntry.unlock();
            return true;
        }
    }

    @Override
    @Nullable
    public SessionLockEntry getLockEntry(RepoPath repoPath) {
        return locks.get(repoPath);
    }

    private SessionLockEntry getOrCreateSessionLockEntry(LockEntryId lockEntryId) {
        RepoPath repoPath = lockEntryId.getRepoPath();
        SessionLockEntry sessionLockEntry = getLockEntry(repoPath);
        if (sessionLockEntry == null) {
            log.trace("Creating new SLE for {} in lm={}", repoPath, this.hashCode());
            sessionLockEntry = new SessionLockEntry(lockEntryId);
            locks.put(repoPath, sessionLockEntry);
        } else {
            log.trace("Reusing existing SLE for {} in lm={}", repoPath, this.hashCode());
        }
        return sessionLockEntry;
    }

    @Override
    public <T extends SessionResource> T getOrCreateResource(Class<T> resourceClass) {
        return getSessionResourceManager().getOrCreateResource(resourceClass);
    }

    @Override
    public void afterCompletion(boolean success) {
        if (sessionResourceManager != null) {
            sessionResourceManager.afterCompletion(success);
        }
    }

    public SessionResourceManager getSessionResourceManager() {
        if (sessionResourceManager == null) {
            sessionResourceManager = new SessionResourceManagerImpl();
        }
        return sessionResourceManager;
    }
}


text:
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using Microsoft.Owin.Security.Authorization;
using Microsoft.Owin.Security.Authorization.Infrastructure;
using Microsoft.Owin.Security.Infrastructure;
using Microsoft.Owin.Security.Jwt;
using Microsoft.Owin.Security.OAuth;
using Owin;
using umbraco;
using umbraco.BusinessLogic.Actions;
using Umbraco.Core;
using Umbraco.Core.Configuration;
using Umbraco.Core.Models.Identity;
using Umbraco.Core.Security;
using Umbraco.Core.Services;
using Umbraco.RestApi.Security;
using Umbraco.Web.Security.Identity;

namespace Umbraco.RestApi
{
    public static class AppBuilderExtensions
    {

        //TODO: Need to follow more of this for http://bitoftech.net/2014/10/27/json-web-token-asp-net-web-api-2-jwt-owin-authorization-server/ dealing with AudienceStores

        //another interesting one https://blog.jayway.com/2014/09/25/securing-asp-net-web-api-endpoints-using-owin-oauth-2-0-and-claims/

        /// <summary>
        /// Configures Umbraco to issue and process authentication tokens
        /// </summary>
        /// <param name="app"></param>
        /// <param name="authServerProviderOptions"></param>
        /// <remarks>
        /// This is a very simple implementation of token authentication, the expiry below is for a single day and with
        /// this implementation there is no way to force expire tokens on the server however given the code below and the additional
        /// callbacks that can be registered for the BackOfficeAuthServerProvider these types of things could be implemented. Additionally the
        /// BackOfficeAuthServerProvider could be overridden to include this functionality instead of coding the logic into the callbacks.
        /// </remarks>
        /// <example>
        ///
        /// An example of using this implementation is to use the UmbracoStandardOwinSetup and execute this extension method as follows:
        ///
        /// <![CDATA[
        ///
        ///   public override void Configuration(IAppBuilder app)
        ///   {
        ///       //ensure the default options are configured
        ///       base.Configuration(app);
        ///
        ///       //configure token auth
        ///       app.UseUmbracoBackOfficeTokenAuth();
        ///   }
        ///
        /// ]]>
        ///
        /// Then be sure to read the details in UmbracoStandardOwinSetup on how to configure Owin to startup using it.
        /// </example>
        public static void UseUmbracoTokenAuthentication(this IAppBuilder app, UmbracoAuthorizationServerProviderOptions authServerProviderOptions = null)
        {
            authServerProviderOptions = authServerProviderOptions ?? new UmbracoAuthorizationServerProviderOptions();

            //if a secret is supplied then
            var base64Key = Convert.ToBase64String(
                Encoding.UTF8.GetBytes(
                    authServerProviderOptions.Secret));

            var tokenProvider = new SymmetricKeyIssuerSecurityTokenProvider(
                AuthorizationPolicies.UmbracoRestApiIssuer,
                base64Key);

            var oAuthServerOptions = new OAuthAuthorizationServerOptions()
            {
                //generally you wouldn't allow this unless on SSL!
                AllowInsecureHttp = authServerProviderOptions.AllowInsecureHttp,
                TokenEndpointPath = new PathString(authServerProviderOptions.AuthEndpoint),
                AuthenticationType = AuthorizationPolicies.UmbracoRestApiTokenAuthenticationType,
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                Provider = new UmbracoAuthorizationServerProvider(authServerProviderOptions)
            };

            oAuthServerOptions.AccessTokenFormat = new JwtFormatWriter(
                oAuthServerOptions,
                tokenProvider.Issuer,
                authServerProviderOptions.Audience,
                base64Key);

            // Token Generation
            app.UseOAuthAuthorizationServer(oAuthServerOptions);
            app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
            {
                AllowedAudiences = new[] { authServerProviderOptions.Audience },
                IssuerSecurityTokenProviders = new[] { tokenProvider },

                Provider = new OAuthBearerAuthenticationProvider
                {
                    OnApplyChallenge = context => { return Task.FromResult(0); },
                    OnRequestToken = context => { return Task.FromResult(0); },
                    OnValidateIdentity = context =>
                    {
                        //ensure that the rest api claim is added to the ticket if everything is validated
                        if (context.IsValidated)
                        {
                            context.Ticket.Identity.AddClaim(new Claim(AuthorizationPolicies.UmbracoRestApiClaimType, "true", ClaimValueTypes.Boolean, AuthorizationPolicies.UmbracoRestApiIssuer));
                        }
                        return Task.FromResult(0);
                    }
                }
            });
        }

        /// <summary>
        /// Required call to enable the REST API
        /// </summary>
        /// <param name="app"></param>
        /// <param name="applicationContext"></param>
        /// <param name="options">
        /// Options to configure the rest api including CORS and Authorization policies
        /// </param>
        public static void UseUmbracoRestApi(this IAppBuilder app,
            ApplicationContext applicationContext,
            UmbracoRestApiOptions options = null)
        {
            if (applicationContext == null) throw new ArgumentNullException(nameof(applicationContext));
            UmbracoRestApiOptionsInstance.Options = options ?? new UmbracoRestApiOptions();

            app.UseUmbracoRestApiAuthorizationPolicies(applicationContext, UmbracoRestApiOptionsInstance.Options.CustomAuthorizationPolicyCallback);
        }

        /// <summary>
        /// Authorization for the rest API uses authorization schemes, see https://docs.microsoft.com/en-us/aspnet/core/security/authorization/policies
        /// </summary>
        /// <param name="app"></param>
        /// <param name="applicationContext"></param>
        /// <param name="customPolicyCallback"></param>
        /// <remarks>
        /// This is a .NET Core approach to authorization but we have a package that has backported all of this for us for .NET 452
        /// </remarks>
        internal static void UseUmbracoRestApiAuthorizationPolicies(
            this IAppBuilder app,
            ApplicationContext applicationContext,
            Func<string, AuthorizationPolicy, Action<AuthorizationPolicyBuilder>> customPolicyCallback = null)
        {
            app.UseAuthorization(options =>
            {
                //A policy that is used at a top level controller - this is more or less to ensure that any actions that
                //don't have an explicit authz policy assigned will defer to this default one

                AddAuthorizationPolicy(options,
                    AuthorizationPolicies.DefaultRestApi,
                    policy => policy.RequireSessionIdOrRestApiClaim(),
                    customPolicyCallback);

                //Published Content READ

                AddAuthorizationPolicy(options,
                    AuthorizationPolicies.PublishedContentRead,
                    policy => policy.RequireSessionIdOrRestApiClaim(),
                    customPolicyCallback);

                //Content CRUD

                AddAuthorizationPolicy(options,
                    AuthorizationPolicies.ContentRead,
                    policy =>
                    {
                        policy.RequireSessionIdOrRestApiClaim();
                        policy.Requirements.Add(new UmbracoSectionAccessRequirement(Core.Constants.Applications.Content));
                        policy.Requirements.Add(new ContentPermissionRequirement(ActionBrowse.Instance.Letter.ToString()));
                    },
                    customPolicyCallback);
                AddAuthorizationPolicy(options,
                    AuthorizationPolicies.ContentCreate,
                    policy =>
                    {
                        policy.RequireSessionIdOrRestApiClaim();
                        policy.Requirements.Add(new UmbracoSectionAccessRequirement(Core.Constants.Applications.Content));
                        policy.Requirements.Add(new ContentPermissionRequirement(ActionNew.Instance.Letter.ToString(), ActionUpdate.Instance.Letter.ToString()));
                    },
                    customPolicyCallback);
                AddAuthorizationPolicy(options,
                    AuthorizationPolicies.ContentUpdate,
                    policy =>
                    {
                        policy.RequireSessionIdOrRestApiClaim();
                        policy.Requirements.Add(new UmbracoSectionAccessRequirement(Core.Constants.Applications.Content));
                        policy.Requirements.Add(new ContentPermissionRequirement(ActionUpdate.Instance.Letter.ToString(), ActionPublish.Instance.Letter.ToString()));
                    },
                    customPolicyCallback);
                AddAuthorizationPolicy(options,
                    AuthorizationPolicies.ContentDelete,
                    policy =>
                    {
                        policy.RequireSessionIdOrRestApiClaim();
                        policy.Requirements.Add(new UmbracoSectionAccessRequirement(Core.Constants.Applications.Content));
                        policy.Requirements.Add(new ContentPermissionRequirement(ActionDelete.Instance.Letter.ToString()));
                    },
                    customPolicyCallback);

                //Media CRUD

                AddAuthorizationPolicy(options,
                    AuthorizationPolicies.MediaRead,
                    policy =>
                    {
                        policy.RequireSessionIdOrRestApiClaim();
                        policy.Requirements.Add(new UmbracoSectionAccessRequirement(Core.Constants.Applications.Media));
                        policy.Requirements.Add(new MediaPermissionRequirement());
                    },
                    customPolicyCallback);
                AddAuthorizationPolicy(options,
                    AuthorizationPolicies.MediaCreate,
                    policy =>
                    {
                        policy.RequireSessionIdOrRestApiClaim();
                        policy.Requirements.Add(new UmbracoSectionAccessRequirement(Core.Constants.Applications.Media));
                        policy.Requirements.Add(new MediaPermissionRequirement());
                    },
                    customPolicyCallback);
                AddAuthorizationPolicy(options,
                    AuthorizationPolicies.MediaUpdate,
                    policy =>
                    {
                        policy.RequireSessionIdOrRestApiClaim();
                        policy.Requirements.Add(new UmbracoSectionAccessRequirement(Core.Constants.Applications.Media));
                        policy.Requirements.Add(new MediaPermissionRequirement());
                    },
                    customPolicyCallback);
                AddAuthorizationPolicy(options,
                    AuthorizationPolicies.MediaDelete,
                    policy =>
                    {
                        policy.RequireSessionIdOrRestApiClaim();
                        policy.Requirements.Add(new UmbracoSectionAccessRequirement(Core.Constants.Applications.Media));
                        policy.Requirements.Add(new MediaPermissionRequirement());
                    },
                    customPolicyCallback);

                //Members CRUD

                AddAuthorizationPolicy(options,
                    AuthorizationPolicies.MemberRead,
                    policy =>
                    {
                        policy.RequireSessionIdOrRestApiClaim();
                        policy.Requirements.Add(new UmbracoSectionAccessRequirement(Core.Constants.Applications.Members));
                    },
                    customPolicyCallback);
                AddAuthorizationPolicy(options,
                    AuthorizationPolicies.MemberCreate,
                    policy =>
                    {
                        policy.RequireSessionIdOrRestApiClaim();
                        policy.Requirements.Add(new UmbracoSectionAccessRequirement(Core.Constants.Applications.Members));
                    },
                    customPolicyCallback);
                AddAuthorizationPolicy(options,
                    AuthorizationPolicies.MemberUpdate,
                    policy =>
                    {
                        policy.RequireSessionIdOrRestApiClaim();
                        policy.Requirements.Add(new UmbracoSectionAccessRequirement(Core.Constants.Applications.Members));
                    },
                    customPolicyCallback);
                AddAuthorizationPolicy(options,
                    AuthorizationPolicies.MemberDelete,
                    policy =>
                    {
                        policy.RequireSessionIdOrRestApiClaim();
                        policy.Requirements.Add(new UmbracoSectionAccessRequirement(Core.Constants.Applications.Members));
                    },
                    customPolicyCallback);

                var handlers = new IAuthorizationHandler[]
                {
                    new UmbracoSectionAccessHandler(),
                    new ContentPermissionHandler(applicationContext.Services),
                    new MediaPermissionHandler(applicationContext.Services)
                };
                options.Dependencies.Service = new DefaultAuthorizationService(new DefaultAuthorizationPolicyProvider(options), handlers);

                app.CreatePerOwinContext(() => new AuthorizationServiceWrapper(options.Dependencies.Service));
            });
        }

        /// <summary>
        /// Used to enable back office cookie authentication for the REST API calls
        /// </summary>
        /// <param name="app"></param>
        /// <param name="appContext"></param>
        /// <returns></returns>
        public static IAppBuilder UseUmbracoCookieAuthenticationForRestApi(this IAppBuilder app, ApplicationContext appContext)
        {
            //Don't proceed if the app is not ready
            if (appContext.IsUpgrading == false && appContext.IsConfigured == false) return app;

            var authOptions = new UmbracoBackOfficeCookieAuthOptions(
                UmbracoConfig.For.UmbracoSettings().Security,
                GlobalSettings.TimeOutInMinutes,
                GlobalSettings.UseSSL)
            {
                Provider = new BackOfficeCookieAuthenticationProvider
                {
                    // Enables the application to validate the security stamp when the user
                    // logs in. This is a security feature which is used when you
                    // change a password or add an external login to your account.
                    OnValidateIdentity = SecurityStampValidator
                        .OnValidateIdentity<BackOfficeUserManager, BackOfficeIdentityUser, int>(
                            TimeSpan.FromMinutes(30),
                            (manager, user) => user.GenerateUserIdentityAsync(manager),
                            identity => identity.GetUserId<int>()),
                }
            };

            //This is what will ensure that the rest api calls are auth'd
            authOptions.CookieManager = new RestApiCookieManager();

            app.UseCookieAuthentication(authOptions);

            return app;
        }

        /// <summary>
        /// This will allow a custom callback to specify a custom policy if required, otherwise it will use the default policy
        /// </summary>
        /// <param name="options"></param>
        /// <param name="name"></param>
        /// <param name="configurePolicy"></param>
        /// <param name="customPolicyCallback"></param>
        public static void AddAuthorizationPolicy(
            AuthorizationOptions options,
            string name,
            Action<AuthorizationPolicyBuilder> configurePolicy,
            Func<string, AuthorizationPolicy, Action<AuthorizationPolicyBuilder>> customPolicyCallback)
        {
            //get the default policy
            var defaultPolicy = GetPolicy(configurePolicy);

            //check if there's a callback and use it
            if (customPolicyCallback != null)
            {
                var result = customPolicyCallback(name, defaultPolicy);
                if (result != null)
                {
                    options.AddPolicy(name, result);
                    return;
                }
            }

            //no custom callback or it didn't return a custom policy so use the default
            options.AddPolicy(name, defaultPolicy);
        }

        /// <summary>
        /// Returns a concrete policy from a builder
        /// </summary>
        /// <param name="configurePolicy"></param>
        /// <returns></returns>
        private static AuthorizationPolicy GetPolicy(Action<AuthorizationPolicyBuilder> configurePolicy)
        {
            if (configurePolicy == null) throw new ArgumentNullException(nameof(configurePolicy));
            var authorizationPolicyBuilder = new AuthorizationPolicyBuilder();
            configurePolicy(authorizationPolicyBuilder);
            return authorizationPolicyBuilder.Build();
        }
    }
}


text:
import { ACTION_TYPES } from '../actions';
import initial from '../state';

const initialState = initial.data;

export const data = (state = initialState, action) => {
  switch (action.type) {
    case ACTION_TYPES.SET_DATA:
      return Object.assign({}, state, {
        categories: action.data.categories,
        info: {
          commit: action.data.info
        },
        labels: action.data.labels,
        stats: {
          newly: action.data.newly,
          trend: action.data.trend,
          updated: action.data.updated
        }
      });
    default:
      return state;
  }
};


text:
import { Routes } from '@angular/router';

import { UrlPath, UrlPathId } from 'app/shared/models';
import { TransactionViewTopContentsContainerComponent } from 'app/core/components/transaction-view-top-contents/transaction-view-top-contents-container.component';
import { TransactionViewPageComponent } from './transaction-view-page.component';

const TO_MAIN = `/${UrlPath.MAIN}`;

export const routing: Routes = [
    {
        path: '',
        component: TransactionViewPageComponent,
        children: [
            {
                path: ':' + UrlPathId.AGENT_ID + '/:' + UrlPathId.TRACE_ID + '/:' + UrlPathId.FOCUS_TIMESTAMP + '/:' + UrlPathId.SPAN_ID,
                component: TransactionViewTopContentsContainerComponent
            },
            {
                path: ':' + UrlPathId.AGENT_ID + '/:' + UrlPathId.TRACE_ID + '/:' + UrlPathId.FOCUS_TIMESTAMP,
                redirectTo: TO_MAIN,
                pathMatch: 'full'
            },
            {
                path: ':' + UrlPathId.AGENT_ID + '/:' + UrlPathId.TRACE_ID,
                redirectTo: TO_MAIN,
                pathMatch: 'full'
            },
            {
                path: ':' + UrlPathId.AGENT_ID,
                redirectTo: TO_MAIN,
                pathMatch: 'full'
            },
            {
                path: '',
                redirectTo: TO_MAIN,
                pathMatch: 'full'
            }
        ]
    }
];


text:
<!doctype html>

        <meta charset="UTF-8"/>
        <meta property="og:locale" content="pt_BR">
        <meta property="og:url" content="http://computacao.uea.edu.br/ludus/posueagames/johnsilva/CanoeiroBare">
        <meta property="og:title" content="Canoeiro Baré">
        <meta property="og:site_name" content="Especialização em Desenvolvimento de Jogos Eletrônicos da UEA">
        <meta property="og:description" content="Em um rio muito perigoso, um grande canoeiro sofre um acidente e perde sua
            consciência. Ao acordar percebe que esse rio é cheio de bichos e armadilhas e para piorar sua situação, o seu filho mais novo está perdido. Ele deve nadar contra a correnteza em uma busca desenfreada de reencontrá-lo.">

        <meta property="og:image" content="http://computacao.uea.edu.br/ludus/posueagames/johnsilva/CanoeiroBare/assets/adgame_800-600.jpg">
        <meta property="og:image:type" content="image/jpeg">
        <meta property="og:image:width" content="800">
        <meta property="og:image:height" content="600">
        <meta property="og:type" content="website">

        <title>Canoeiro Baré</title>

        <link href="css/style.css" rel="stylesheet" />

Time:
                        José Maria DVD

                        ,
                        Bruno OiPapai

                        ,
                        John Silva

Professor Dr.: Jucimar Junior

Pós-graduação em Desenvolvimento de Jogos Eletrônicos

UEA - Universidade do Estado do Amazonas


text:
package synchttp
import (
  "context"
  "net/http"
)

func (t CtxDoneHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
  if ch := req.Context().Done(); ch != nil {
    <- ch
    t.H.ServeHTTP(w, req)
  }
}

func (t *TimedContextHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
  ctx, cancel := context.WithTimeout(req.Context(), t.Dt)
  defer cancel()
  req = req.WithContext(ctx)
  t.H.ServeHTTP(w, req)
}


text:
/*
	* Pager Control
*/

#ifndef _DCXPAGER_H_
#define _DCXPAGER_H_

#include "defines.h"
#include "Classes/dcxcontrol.h"
#include "Classes/layout/layoutmanager.h"

class DcxDialog;

/*!
 * \brief blah
 *
 * blah
 */

class DcxPager : public DcxControl {

public:

  DcxPager( UINT ID, DcxDialog * p_Dialog, HWND mParentHwnd, RECT * rc, TString & styles );
  virtual ~DcxPager( );

  LRESULT PostMessage( UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL & bParsed );
  LRESULT ParentMessage( UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL & bParsed );

  void parseInfoRequest( TString & input, char * szReturnValue );
  void parseCommandRequest( TString & input );
  void parseControlStyles( TString & styles, LONG * Styles, LONG * ExStyles, BOOL * bNoTheme );

  inline TString getType( ) { return TString( "pager" ); };
  TString getStyles(void);
  void toXml(TiXmlElement * xml);

	void setChild(const HWND child);
	void setBkColor(const COLORREF c);
	void setBorderSize(const int bSize);
	void setButtonSize(const int bSize);
	void reCalcSize(void) const;

protected:
	HWND m_ChildHWND;

};

#endif // _DCXPAGER_H_


text:
cask :v1 => 'glo-bible' do
  version :latest
  sha256 :no_check

  url 'http://immersion.vo.llnwd.net/o42/pub/glo/mac/en-us/Glo.dmg'
  homepage 'http://globible.com/gloformac/'
  license :unknown

  app 'Glo Bible.app'
end