text:
package com.android.settings.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.text.DynamicLayout;
import android.text.Layout;
import android.text.Layout.Alignment;
import android.text.SpannableStringBuilder;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.util.MathUtils;
import android.view.MotionEvent;
import android.view.View;

import com.android.internal.util.Preconditions;
import com.android.settings.R;

/**
 * Sweep across a {@link ChartView} at a specific {@link ChartAxis} value, which
 * a user can drag.
 */
public class ChartSweepView extends View {

    private static final boolean DRAW_OUTLINE = false;

    // TODO: clean up all the various padding/offset/margins

    private Drawable mSweep;
    private Rect mSweepPadding = new Rect();

    /** Offset of content inside this view. */
    private Rect mContentOffset = new Rect();
    /** Offset of {@link #mSweep} inside this view. */
    private Point mSweepOffset = new Point();

    private Rect mMargins = new Rect();
    private float mNeighborMargin;
    private int mSafeRegion;

    private int mFollowAxis;

    private int mLabelMinSize;
    private float mLabelSize;

    private int mLabelTemplateRes;
    private int mLabelColor;

    private SpannableStringBuilder mLabelTemplate;
    private DynamicLayout mLabelLayout;

    private ChartAxis mAxis;
    private long mValue;
    private long mLabelValue;

    private long mValidAfter;
    private long mValidBefore;
    private ChartSweepView mValidAfterDynamic;
    private ChartSweepView mValidBeforeDynamic;

    private float mLabelOffset;

    private Paint mOutlinePaint = new Paint();

    public static final int HORIZONTAL = 0;
    public static final int VERTICAL = 1;

    private int mTouchMode = MODE_NONE;

    private static final int MODE_NONE = 0;
    private static final int MODE_DRAG = 1;
    private static final int MODE_LABEL = 2;

    private static final int LARGE_WIDTH = 1024;

    private long mDragInterval = 1;

    public interface OnSweepListener {
        public void onSweep(ChartSweepView sweep, boolean sweepDone);
        public void requestEdit(ChartSweepView sweep);
    }

    private OnSweepListener mListener;

    private float mTrackingStart;
    private MotionEvent mTracking;

    private ChartSweepView[] mNeighbors = new ChartSweepView[0];

    public ChartSweepView(Context context) {
        this(context, null);
    }

    public ChartSweepView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ChartSweepView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        final TypedArray a = context.obtainStyledAttributes(
                attrs, R.styleable.ChartSweepView, defStyle, 0);

        final int color = a.getColor(R.styleable.ChartSweepView_labelColor, Color.BLUE);
        setSweepDrawable(a.getDrawable(R.styleable.ChartSweepView_sweepDrawable), color);
        setFollowAxis(a.getInt(R.styleable.ChartSweepView_followAxis, -1));
        setNeighborMargin(a.getDimensionPixelSize(R.styleable.ChartSweepView_neighborMargin, 0));
        setSafeRegion(a.getDimensionPixelSize(R.styleable.ChartSweepView_safeRegion, 0));

        setLabelMinSize(a.getDimensionPixelSize(R.styleable.ChartSweepView_labelSize, 0));
        setLabelTemplate(a.getResourceId(R.styleable.ChartSweepView_labelTemplate, 0));
        setLabelColor(color);

        // TODO: moved focused state directly into assets
        setBackgroundResource(R.drawable.data_usage_sweep_background);

        mOutlinePaint.setColor(Color.RED);
        mOutlinePaint.setStrokeWidth(1f);
        mOutlinePaint.setStyle(Style.STROKE);

        a.recycle();

        setClickable(true);
        setFocusable(true);
        setOnClickListener(mClickListener);

        setWillNotDraw(false);
    }

    private OnClickListener mClickListener = new OnClickListener() {
        public void onClick(View v) {
            dispatchRequestEdit();
        }
    };

    void init(ChartAxis axis) {
        mAxis = Preconditions.checkNotNull(axis, "missing axis");
    }

    public void setNeighbors(ChartSweepView... neighbors) {
        mNeighbors = neighbors;
    }

    public int getFollowAxis() {
        return mFollowAxis;
    }

    public Rect getMargins() {
        return mMargins;
    }

    public void setDragInterval(long dragInterval) {
        mDragInterval = dragInterval;
    }

    /**
     * Return the number of pixels that the "target" area is inset from the
     * {@link View} edge, along the current {@link #setFollowAxis(int)}.
     */
    private float getTargetInset() {
        if (mFollowAxis == VERTICAL) {
            final float targetHeight = mSweep.getIntrinsicHeight() - mSweepPadding.top
                    - mSweepPadding.bottom;
            return mSweepPadding.top + (targetHeight / 2) + mSweepOffset.y;
        } else {
            final float targetWidth = mSweep.getIntrinsicWidth() - mSweepPadding.left
                    - mSweepPadding.right;
            return mSweepPadding.left + (targetWidth / 2) + mSweepOffset.x;
        }
    }

    public void addOnSweepListener(OnSweepListener listener) {
        mListener = listener;
    }

    private void dispatchOnSweep(boolean sweepDone) {
        if (mListener != null) {
            mListener.onSweep(this, sweepDone);
        }
    }

    private void dispatchRequestEdit() {
        if (mListener != null) {
            mListener.requestEdit(this);
        }
    }

    @Override
    public void setEnabled(boolean enabled) {
        super.setEnabled(enabled);
        setFocusable(enabled);
        requestLayout();
    }

    public void setSweepDrawable(Drawable sweep, int color) {
        if (mSweep != null) {
            mSweep.setCallback(null);
            unscheduleDrawable(mSweep);
        }

        if (sweep != null) {
            sweep.setCallback(this);
            if (sweep.isStateful()) {
                sweep.setState(getDrawableState());
            }
            sweep.setVisible(getVisibility() == VISIBLE, false);
            mSweep = sweep;
            // Match the text.
            mSweep.setTint(color);
            sweep.getPadding(mSweepPadding);
        } else {
            mSweep = null;
        }

        invalidate();
    }

    public void setFollowAxis(int followAxis) {
        mFollowAxis = followAxis;
    }

    public void setLabelMinSize(int minSize) {
        mLabelMinSize = minSize;
        invalidateLabelTemplate();
    }

    public void setLabelTemplate(int resId) {
        mLabelTemplateRes = resId;
        invalidateLabelTemplate();
    }

    public void setLabelColor(int color) {
        mLabelColor = color;
        invalidateLabelTemplate();
    }

    private void invalidateLabelTemplate() {
        if (mLabelTemplateRes != 0) {
            final CharSequence template = getResources().getText(mLabelTemplateRes);

            final TextPaint paint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
            paint.density = getResources().getDisplayMetrics().density;
            paint.setCompatibilityScaling(getResources().getCompatibilityInfo().applicationScale);
            paint.setColor(mLabelColor);

            mLabelTemplate = new SpannableStringBuilder(template);
            mLabelLayout = new DynamicLayout(
                    mLabelTemplate, paint, LARGE_WIDTH, Alignment.ALIGN_RIGHT, 1f, 0f, false);
            invalidateLabel();

        } else {
            mLabelTemplate = null;
            mLabelLayout = null;
        }

        invalidate();
        requestLayout();
    }

    private void invalidateLabel() {
        if (mLabelTemplate != null && mAxis != null) {
            mLabelValue = mAxis.buildLabel(getResources(), mLabelTemplate, mValue);
            setContentDescription(mLabelTemplate);
            invalidateLabelOffset();
            invalidate();
        } else {
            mLabelValue = mValue;
        }
    }

    /**
     * When overlapping with neighbor, split difference and push label.
     */
    public void invalidateLabelOffset() {
        float margin;
        float labelOffset = 0;
        if (mFollowAxis == VERTICAL) {
            if (mValidAfterDynamic != null) {
                mLabelSize = Math.max(getLabelWidth(this), getLabelWidth(mValidAfterDynamic));
                margin = getLabelTop(mValidAfterDynamic) - getLabelBottom(this);
                if (margin < 0) {
                    labelOffset = margin / 2;
                }
            } else if (mValidBeforeDynamic != null) {
                mLabelSize = Math.max(getLabelWidth(this), getLabelWidth(mValidBeforeDynamic));
                margin = getLabelTop(this) - getLabelBottom(mValidBeforeDynamic);
                if (margin < 0) {
                    labelOffset = -margin / 2;
                }
            } else {
                mLabelSize = getLabelWidth(this);
            }
        } else {
            // TODO: implement horizontal labels
        }

        mLabelSize = Math.max(mLabelSize, mLabelMinSize);

        // when offsetting label, neighbor probably needs to offset too
        if (labelOffset != mLabelOffset) {
            mLabelOffset = labelOffset;
            invalidate();
            if (mValidAfterDynamic != null) mValidAfterDynamic.invalidateLabelOffset();
            if (mValidBeforeDynamic != null) mValidBeforeDynamic.invalidateLabelOffset();
        }
    }

    @Override
    public void jumpDrawablesToCurrentState() {
        super.jumpDrawablesToCurrentState();
        if (mSweep != null) {
            mSweep.jumpToCurrentState();
        }
    }

    @Override
    public void setVisibility(int visibility) {
        super.setVisibility(visibility);
        if (mSweep != null) {
            mSweep.setVisible(visibility == VISIBLE, false);
        }
    }

    @Override
    protected boolean verifyDrawable(Drawable who) {
        return who == mSweep || super.verifyDrawable(who);
    }

    public ChartAxis getAxis() {
        return mAxis;
    }

    public void setValue(long value) {
        mValue = value;
        invalidateLabel();
    }

    public long getValue() {
        return mValue;
    }

    public long getLabelValue() {
        return mLabelValue;
    }

    public float getPoint() {
        if (isEnabled()) {
            return mAxis.convertToPoint(mValue);
        } else {
            // when disabled, show along top edge
            return 0;
        }
    }

    /**
     * Set valid range this sweep can move within, in {@link #mAxis} values. The
     * most restrictive combination of all valid ranges is used.
     */
    public void setValidRange(long validAfter, long validBefore) {
        mValidAfter = validAfter;
        mValidBefore = validBefore;
    }

    public void setNeighborMargin(float neighborMargin) {
        mNeighborMargin = neighborMargin;
    }

    public void setSafeRegion(int safeRegion) {
        mSafeRegion = safeRegion;
    }

    /**
     * Set valid range this sweep can move within, defined by the given
     * {@link ChartSweepView}. The most restrictive combination of all valid
     * ranges is used.
     */
    public void setValidRangeDynamic(ChartSweepView validAfter, ChartSweepView validBefore) {
        mValidAfterDynamic = validAfter;
        mValidBeforeDynamic = validBefore;
    }

    /**
     * Test if given {@link MotionEvent} is closer to another
     * {@link ChartSweepView} compared to ourselves.
     */
    public boolean isTouchCloserTo(MotionEvent eventInParent, ChartSweepView another) {
        final float selfDist = getTouchDistanceFromTarget(eventInParent);
        final float anotherDist = another.getTouchDistanceFromTarget(eventInParent);
        return anotherDist < selfDist;
    }

    private float getTouchDistanceFromTarget(MotionEvent eventInParent) {
        if (mFollowAxis == HORIZONTAL) {
            return Math.abs(eventInParent.getX() - (getX() + getTargetInset()));
        } else {
            return Math.abs(eventInParent.getY() - (getY() + getTargetInset()));
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (!isEnabled()) return false;

        final View parent = (View) getParent();
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN: {

                // only start tracking when in sweet spot
                final boolean acceptDrag;
                final boolean acceptLabel;
                if (mFollowAxis == VERTICAL) {
                    acceptDrag = event.getX() > getWidth() - (mSweepPadding.right * 8);
                    acceptLabel = mLabelLayout != null ? event.getX() < mLabelLayout.getWidth()
                            : false;
                } else {
                    acceptDrag = event.getY() > getHeight() - (mSweepPadding.bottom * 8);
                    acceptLabel = mLabelLayout != null ? event.getY() < mLabelLayout.getHeight()
                            : false;
                }

                final MotionEvent eventInParent = event.copy();
                eventInParent.offsetLocation(getLeft(), getTop());

                // ignore event when closer to a neighbor
                for (ChartSweepView neighbor : mNeighbors) {
                    if (isTouchCloserTo(eventInParent, neighbor)) {
                        return false;
                    }
                }

                if (acceptDrag) {
                    if (mFollowAxis == VERTICAL) {
                        mTrackingStart = getTop() - mMargins.top;
                    } else {
                        mTrackingStart = getLeft() - mMargins.left;
                    }
                    mTracking = event.copy();
                    mTouchMode = MODE_DRAG;

                    // starting drag should activate entire chart
                    if (!parent.isActivated()) {
                        parent.setActivated(true);
                    }

                    return true;
                } else if (acceptLabel) {
                    mTouchMode = MODE_LABEL;
                    return true;
                } else {
                    mTouchMode = MODE_NONE;
                    return false;
                }
            }
            case MotionEvent.ACTION_MOVE: {
                if (mTouchMode == MODE_LABEL) {
                    return true;
                }

                getParent().requestDisallowInterceptTouchEvent(true);

                // content area of parent
                final Rect parentContent = getParentContentRect();
                final Rect clampRect = computeClampRect(parentContent);
                if (clampRect.isEmpty()) return true;

                long value;
                if (mFollowAxis == VERTICAL) {
                    final float currentTargetY = getTop() - mMargins.top;
                    final float requestedTargetY = mTrackingStart
                            + (event.getRawY() - mTracking.getRawY());
                    final float clampedTargetY = MathUtils.constrain(
                            requestedTargetY, clampRect.top, clampRect.bottom);
                    setTranslationY(clampedTargetY - currentTargetY);

                    value = mAxis.convertToValue(clampedTargetY - parentContent.top);
                } else {
                    final float currentTargetX = getLeft() - mMargins.left;
                    final float requestedTargetX = mTrackingStart
                            + (event.getRawX() - mTracking.getRawX());
                    final float clampedTargetX = MathUtils.constrain(
                            requestedTargetX, clampRect.left, clampRect.right);
                    setTranslationX(clampedTargetX - currentTargetX);

                    value = mAxis.convertToValue(clampedTargetX - parentContent.left);
                }

                // round value from drag to nearest increment
                value -= value % mDragInterval;
                setValue(value);

                dispatchOnSweep(false);
                return true;
            }
            case MotionEvent.ACTION_UP: {
                if (mTouchMode == MODE_LABEL) {
                    performClick();
                } else if (mTouchMode == MODE_DRAG) {
                    mTrackingStart = 0;
                    mTracking = null;
                    mValue = mLabelValue;
                    dispatchOnSweep(true);
                    setTranslationX(0);
                    setTranslationY(0);
                    requestLayout();
                }

                mTouchMode = MODE_NONE;
                return true;
            }
            default: {
                return false;
            }
        }
    }

    /**
     * Update {@link #mValue} based on current position, including any
     * {@link #onTouchEvent(MotionEvent)} in progress. Typically used when
     * {@link ChartAxis} changes during sweep adjustment.
     */
    public void updateValueFromPosition() {
        final Rect parentContent = getParentContentRect();
        if (mFollowAxis == VERTICAL) {
            final float effectiveY = getY() - mMargins.top - parentContent.top;
            setValue(mAxis.convertToValue(effectiveY));
        } else {
            final float effectiveX = getX() - mMargins.left - parentContent.left;
            setValue(mAxis.convertToValue(effectiveX));
        }
    }

    public int shouldAdjustAxis() {
        return mAxis.shouldAdjustAxis(getValue());
    }

    private Rect getParentContentRect() {
        final View parent = (View) getParent();
        return new Rect(parent.getPaddingLeft(), parent.getPaddingTop(),
                parent.getWidth() - parent.getPaddingRight(),
                parent.getHeight() - parent.getPaddingBottom());
    }

    @Override
    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
        // ignored to keep LayoutTransition from animating us
    }

    @Override
    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
        // ignored to keep LayoutTransition from animating us
    }

    private long getValidAfterDynamic() {
        final ChartSweepView dynamic = mValidAfterDynamic;
        return dynamic != null && dynamic.isEnabled() ? dynamic.getValue() : Long.MIN_VALUE;
    }

    private long getValidBeforeDynamic() {
        final ChartSweepView dynamic = mValidBeforeDynamic;
        return dynamic != null && dynamic.isEnabled() ? dynamic.getValue() : Long.MAX_VALUE;
    }

    /**
     * Compute {@link Rect} in {@link #getParent()} coordinates that we should
     * be clamped inside of, usually from {@link #setValidRange(long, long)}
     * style rules.
     */
    private Rect computeClampRect(Rect parentContent) {
        // create two rectangles, and pick most restrictive combination
        final Rect rect = buildClampRect(parentContent, mValidAfter, mValidBefore, 0f);
        final Rect dynamicRect = buildClampRect(
                parentContent, getValidAfterDynamic(), getValidBeforeDynamic(), mNeighborMargin);

        if (!rect.intersect(dynamicRect)) {
            rect.setEmpty();
        }
        return rect;
    }

    private Rect buildClampRect(
            Rect parentContent, long afterValue, long beforeValue, float margin) {
        if (mAxis instanceof InvertedChartAxis) {
            long temp = beforeValue;
            beforeValue = afterValue;
            afterValue = temp;
        }

        final boolean afterValid = afterValue != Long.MIN_VALUE && afterValue != Long.MAX_VALUE;
        final boolean beforeValid = beforeValue != Long.MIN_VALUE && beforeValue != Long.MAX_VALUE;

        final float afterPoint = mAxis.convertToPoint(afterValue) + margin;
        final float beforePoint = mAxis.convertToPoint(beforeValue) - margin;

        final Rect clampRect = new Rect(parentContent);
        if (mFollowAxis == VERTICAL) {
            if (beforeValid) clampRect.bottom = clampRect.top + (int) beforePoint;
            if (afterValid) clampRect.top += afterPoint;
        } else {
            if (beforeValid) clampRect.right = clampRect.left + (int) beforePoint;
            if (afterValid) clampRect.left += afterPoint;
        }
        return clampRect;
    }

    @Override
    protected void drawableStateChanged() {
        super.drawableStateChanged();
        if (mSweep.isStateful()) {
            mSweep.setState(getDrawableState());
        }
    }

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

        // TODO: handle vertical labels
        if (isEnabled() && mLabelLayout != null) {
            final int sweepHeight = mSweep.getIntrinsicHeight();
            final int templateHeight = mLabelLayout.getHeight();

            mSweepOffset.x = 0;
            mSweepOffset.y = 0;
            mSweepOffset.y = (int) ((templateHeight / 2) - getTargetInset());
            setMeasuredDimension(mSweep.getIntrinsicWidth(), Math.max(sweepHeight, templateHeight));

        } else {
            mSweepOffset.x = 0;
            mSweepOffset.y = 0;
            setMeasuredDimension(mSweep.getIntrinsicWidth(), mSweep.getIntrinsicHeight());
        }

        if (mFollowAxis == VERTICAL) {
            final int targetHeight = mSweep.getIntrinsicHeight() - mSweepPadding.top
                    - mSweepPadding.bottom;
            mMargins.top = -(mSweepPadding.top + (targetHeight / 2));
            mMargins.bottom = 0;
            mMargins.left = -mSweepPadding.left;
            mMargins.right = mSweepPadding.right;
        } else {
            final int targetWidth = mSweep.getIntrinsicWidth() - mSweepPadding.left
                    - mSweepPadding.right;
            mMargins.left = -(mSweepPadding.left + (targetWidth / 2));
            mMargins.right = 0;
            mMargins.top = -mSweepPadding.top;
            mMargins.bottom = mSweepPadding.bottom;
        }

        mContentOffset.set(0, 0, 0, 0);

        // make touch target area larger
        final int widthBefore = getMeasuredWidth();
        final int heightBefore = getMeasuredHeight();
        if (mFollowAxis == HORIZONTAL) {
            final int widthAfter = widthBefore * 3;
            setMeasuredDimension(widthAfter, heightBefore);
            mContentOffset.left = (widthAfter - widthBefore) / 2;

            final int offset = mSweepPadding.bottom * 2;
            mContentOffset.bottom -= offset;
            mMargins.bottom += offset;
        } else {
            final int heightAfter = heightBefore * 2;
            setMeasuredDimension(widthBefore, heightAfter);
            mContentOffset.offset(0, (heightAfter - heightBefore) / 2);

            final int offset = mSweepPadding.right * 2;
            mContentOffset.right -= offset;
            mMargins.right += offset;
        }

        mSweepOffset.offset(mContentOffset.left, mContentOffset.top);
        mMargins.offset(-mSweepOffset.x, -mSweepOffset.y);
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        invalidateLabelOffset();
    }

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

        final int width = getWidth();
        final int height = getHeight();

        final int labelSize;
        if (isEnabled() && mLabelLayout != null) {
            final int count = canvas.save();
            {
                final float alignOffset = mLabelSize - LARGE_WIDTH;
                canvas.translate(
                        mContentOffset.left + alignOffset, mContentOffset.top + mLabelOffset);
                mLabelLayout.draw(canvas);
            }
            canvas.restoreToCount(count);
            labelSize = (int) mLabelSize + mSafeRegion;
        } else {
            labelSize = 0;
        }

        if (mFollowAxis == VERTICAL) {
            mSweep.setBounds(labelSize, mSweepOffset.y, width + mContentOffset.right,
                    mSweepOffset.y + mSweep.getIntrinsicHeight());
        } else {
            mSweep.setBounds(mSweepOffset.x, labelSize, mSweepOffset.x + mSweep.getIntrinsicWidth(),
                    height + mContentOffset.bottom);
        }

        mSweep.draw(canvas);

        if (DRAW_OUTLINE) {
            mOutlinePaint.setColor(Color.RED);
            canvas.drawRect(0, 0, width, height, mOutlinePaint);
        }
    }

    public static float getLabelTop(ChartSweepView view) {
        return view.getY() + view.mContentOffset.top;
    }

    public static float getLabelBottom(ChartSweepView view) {
        return getLabelTop(view) + view.mLabelLayout.getHeight();
    }

    public static float getLabelWidth(ChartSweepView view) {
        return Layout.getDesiredWidth(view.mLabelLayout.getText(), view.mLabelLayout.getPaint());
    }
}


text:
<?php

namespace ZFTest\Hal\Plugin\TestAsset;

use Zend\Stdlib\JsonSerializable;

class JsonSerializableEntity extends Entity implements JsonSerializable
{
    public function __construct($id, $name)
    {
        $this->id   = $id;
        $this->name = $name;
    }

    public function jsonSerialize()
    {
        return array(
            'id' => $this->id,
        );
    }
}

redpajama_set_name: RedPajamaGithub


text:
/* Creates a clone of an element and lets it track the mouse as it moves
----------------------------------------------------------------------------------------------------------------------*/

var MouseFollower = Class.extend(ListenerMixin, {

	options: null,

	sourceEl: null, // the element that will be cloned and made to look like it is dragging
	el: null, // the clone of `sourceEl` that will track the mouse
	parentEl: null, // the element that `el` (the clone) will be attached to

	// the initial position of el, relative to the offset parent. made to match the initial offset of sourceEl
	top0: null,
	left0: null,

	// the absolute coordinates of the initiating touch/mouse action
	y0: null,
	x0: null,

	// the number of pixels the mouse has moved from its initial position
	topDelta: null,
	leftDelta: null,

	isFollowing: false,
	isHidden: false,
	isAnimating: false, // doing the revert animation?

	constructor: function(sourceEl, options) {
		this.options = options = options || {};
		this.sourceEl = sourceEl;
		this.parentEl = options.parentEl ? $(options.parentEl) : sourceEl.parent(); // default to sourceEl's parent
	},

	// Causes the element to start following the mouse
	start: function(ev) {
		if (!this.isFollowing) {
			this.isFollowing = true;

			this.y0 = getEvY(ev);
			this.x0 = getEvX(ev);
			this.topDelta = 0;
			this.leftDelta = 0;

			if (!this.isHidden) {
				this.updatePosition();
			}

			if (getEvIsTouch(ev)) {
				this.listenTo($(document), 'touchmove', this.handleMove);
			}
			else {
				this.listenTo($(document), 'mousemove', this.handleMove);
			}
		}
	},

	// Causes the element to stop following the mouse. If shouldRevert is true, will animate back to original position.
	// `callback` gets invoked when the animation is complete. If no animation, it is invoked immediately.
	stop: function(shouldRevert, callback) {
		var _this = this;
		var revertDuration = this.options.revertDuration;

		function complete() {
			this.isAnimating = false;
			_this.removeElement();

			this.top0 = this.left0 = null; // reset state for future updatePosition calls

			if (callback) {
				callback();
			}
		}

		if (this.isFollowing && !this.isAnimating) { // disallow more than one stop animation at a time
			this.isFollowing = false;

			this.stopListeningTo($(document));

			if (shouldRevert && revertDuration && !this.isHidden) { // do a revert animation?
				this.isAnimating = true;
				this.el.animate({
					top: this.top0,
					left: this.left0
				}, {
					duration: revertDuration,
					complete: complete
				});
			}
			else {
				complete();
			}
		}
	},

	// Gets the tracking element. Create it if necessary
	getEl: function() {
		var el = this.el;

		if (!el) {
			this.sourceEl.width(); // hack to force IE8 to compute correct bounding box
			el = this.el = this.sourceEl.clone()
				.addClass(this.options.additionalClass || '')
				.css({
					position: 'absolute',
					visibility: '', // in case original element was hidden (commonly through hideEvents())
					display: this.isHidden ? 'none' : '', // for when initially hidden
					margin: 0,
					right: 'auto', // erase and set width instead
					bottom: 'auto', // erase and set height instead
					width: this.sourceEl.width(), // explicit height in case there was a 'right' value
					height: this.sourceEl.height(), // explicit width in case there was a 'bottom' value
					opacity: this.options.opacity || '',
					zIndex: this.options.zIndex
				});

			// we don't want long taps or any mouse interaction causing selection/menus.
			// would use preventSelection(), but that prevents selectstart, causing problems.
			el.addClass('fc-unselectable');

			el.appendTo(this.parentEl);
		}

		return el;
	},

	// Removes the tracking element if it has already been created
	removeElement: function() {
		if (this.el) {
			this.el.remove();
			this.el = null;
		}
	},

	// Update the CSS position of the tracking element
	updatePosition: function() {
		var sourceOffset;
		var origin;

		this.getEl(); // ensure this.el

		// make sure origin info was computed
		if (this.top0 === null) {
			this.sourceEl.width(); // hack to force IE8 to compute correct bounding box
			sourceOffset = this.sourceEl.offset();
			origin = this.el.offsetParent().offset();
			this.top0 = sourceOffset.top - origin.top;
			this.left0 = sourceOffset.left - origin.left;
		}

		this.el.css({
			top: this.top0 + this.topDelta,
			left: this.left0 + this.leftDelta
		});
	},

	// Gets called when the user moves the mouse
	handleMove: function(ev) {
		this.topDelta = getEvY(ev) - this.y0;
		this.leftDelta = getEvX(ev) - this.x0;

		if (!this.isHidden) {
			this.updatePosition();
		}
	},

	// Temporarily makes the tracking element invisible. Can be called before following starts
	hide: function() {
		if (!this.isHidden) {
			this.isHidden = true;
			if (this.el) {
				this.el.hide();
			}
		}
	},

	// Show the tracking element after it has been temporarily hidden
	show: function() {
		if (this.isHidden) {
			this.isHidden = false;
			this.updatePosition();
			this.getEl().show();
		}
	}

});


text:
using System;
using System.Collections.Generic;
using System.Net;
using System.Web.Http;
using System.Web.Http.Results;
using Thinktecture.Relay.Server.Dto;
using Thinktecture.Relay.Server.Http.Filters;
using Thinktecture.Relay.Server.Repository;
using Thinktecture.Relay.Server.Security;

namespace Thinktecture.Relay.Server.Controller.ManagementWeb
{
	[Authorize(Roles = "Admin")]
	[ManagementWebModuleBindingFilter]
	[NoCache]
	public class UserController : ApiController
	{
		private readonly IUserRepository _userRepository;
		private readonly IPasswordComplexityValidator _passwordComplexityValidator;

		public UserController(IUserRepository userRepository, IPasswordComplexityValidator passwordComplexityValidator)
		{
			_userRepository = userRepository ?? throw new ArgumentNullException(nameof(userRepository));
			_passwordComplexityValidator = passwordComplexityValidator ?? throw new ArgumentNullException(nameof(passwordComplexityValidator));
		}

		[AllowAnonymous]
		[HttpPost]
		[ActionName("firsttime")]
		public IHttpActionResult CreateFirstUser(CreateUser user)
		{
			if (_userRepository.Any())
			{
				return new StatusCodeResult(HttpStatusCode.Forbidden, Request);
			}

			if (!CheckPasswordAndVerification(user, out var result))
			{
				return result;
			}

			return Create(user);
		}

		[HttpGet]
		[ActionName("users")]
		public IEnumerable<User> List()
		{
			return _userRepository.List();
		}

		[HttpPost]
		[ActionName("user")]
		public IHttpActionResult Create(CreateUser user)
		{
			if (user == null)
			{
				return BadRequest();
			}

			if (!CheckPasswordAndVerification(user, out var result))
			{
				return result;
			}

			var id = _userRepository.Create(user.UserName, user.Password);

			if (id == Guid.Empty)
			{
				return BadRequest();
			}

			// TODO: Location
			return Created("", id);
		}

		private bool CheckPasswordAndVerification(CreateUser user, out IHttpActionResult httpActionResult)
		{
			httpActionResult = null;

			// new password and repetition need to match
			if (user.Password != user.PasswordVerification)
			{
				httpActionResult = BadRequest("New password and verification do not match");
				return false;
			}

			// validate password complexity by other rules
			if (!_passwordComplexityValidator.ValidatePassword(user.UserName, user.Password, out var errorMessage))
			{
				httpActionResult = BadRequest(errorMessage);
				return false;
			}

			return true;
		}

		[HttpGet]
		[ActionName("user")]
		public IHttpActionResult Get(Guid id)
		{
			var user = _userRepository.Get(id);

			if (user == null)
			{
				return BadRequest();
			}

			return Ok(user);
		}

		[HttpDelete]
		[ActionName("user")]
		public IHttpActionResult Delete(Guid id)
		{
			var result = _userRepository.Delete(id);

			return result ? (IHttpActionResult)Ok() : BadRequest();
		}

		[HttpPut]
		[ActionName("user")]
		public IHttpActionResult Update(UpdateUser user)
		{
			if (user == null)
			{
				return BadRequest();
			}

			// OldPassword needs to be correct
			var authenticatedUser = _userRepository.Authenticate(user.UserName, user.PasswordOld);
			if (authenticatedUser == null)
			{
				return BadRequest("Old password not okay");
			}

			if (user.PasswordOld == user.Password)
			{
				return BadRequest("New password must be different from old one");
			}

			if (!CheckPasswordAndVerification(user, out var error))
			{
				return error;
			}

			var result = _userRepository.Update(authenticatedUser.Id, user.Password);

			return result ? (IHttpActionResult)Ok() : BadRequest();
		}

		[HttpGet]
		[ActionName("userNameAvailability")]
		public IHttpActionResult GetUserNameAvailability(string userName)
		{
			if (_userRepository.IsUserNameAvailable(userName))
			{
				return Ok();
			}

			return Conflict();
		}
	}
}


text:
<?php
namespace Hangman\Bundle\ApiBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;

class HelloWorldController extends Controller
{
    public function helloWorldAction()
    {
        return new Response(
            'Hello world!'
        );
    }
}


text:
"""
Given an array nums, write a function to move all 0's to the end of it while
maintaining the relative order of the non-zero elements.

For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums
should be [1, 3, 12, 0, 0].

Note:
You must do this in-place without making a copy of the array.
Minimize the total number of operations.
"""

class Solution(object):
    def moveZeroes(self, nums):
        """
        :type nums: List[int]
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        j = 0
        for i, c in enumerate(nums):
            if c != 0:
                nums[i], nums[j] = nums[j], nums[i]
                j += 1

a1 = [0, 1, 0, 3, 12]
s = Solution()
s.moveZeroes(a1)
print a1


text:
import Ember from 'ember';
import QuickFormsField from './qf-field';

export default QuickFormsField.extend({
  handleOnChange: function () {
    var self = this;
    this.get('form').$('#' + this.get('controlID')).click(function () {
      Ember.run.next(function () {
        self.triggerShowError();
      });
    });
  },
  handleOnKey: function () {
    return;
  },
  setUpView: function (wrapper) {
    this.set('layout', Ember.Handlebars.compile('{{#quick-forms/' + wrapper + '/qf-checkbox field=this}}{{yield}}{{/quick-forms/' + wrapper + '/qf-checkbox}}'));
  }
});


text:
<?xml version="1.0" encoding="UTF-8"?>
<chapter version="5.0"
         xsi:schemaLocation="http://docbook.org/ns/docbook http://www.docbook.org/xml/5.0/xsd/docbook.xsd http://www.w3.org/1999/xlink http://www.docbook.org/xml/5.0/xsd/xlink.xsd"
         xml:base="../" xml:id="useCasesAndExamples" xmlns="http://docbook.org/ns/docbook"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xs="http://www.w3.org/2001/XMLSchema"
         xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:xi="http://www.w3.org/2001/XInclude"
         xmlns:ns="http://docbook.org/ns/docbook">
  <title>Use cases and examples</title>

    <title>Introduction</title>

    <para>Drools Planner has several examples. In this manual we explain Drools Planner mainly using the n queens
    example. So it's advisable to read at least the section about that example. For advanced users, the following
    examples are recommended: curriculum course and nurse rostering.</para>

    <para>You can find the source code of all these examples in the distribution zip under
    <filename>examples/sources</filename> and also in git under
    <filename>drools-planner/drools-planner-examples</filename>.</para>

    <title>Toy examples</title>

      <title>N queens</title>

        <title>Problem statement</title>

        <para>The <emphasis>n queens puzzle</emphasis> is a puzzle with the following constraints:</para>

        <itemizedlist>
          <listitem>
            <para>Use a chessboard of <emphasis>n</emphasis> columns and <emphasis>n</emphasis> rows.</para>
          </listitem>

          <listitem>
            <para>Place <emphasis>n</emphasis> queens on the chessboard.</para>
          </listitem>

          <listitem>
            <para>No 2 queens can attack each other. Note that a queen can attack any other queen on the same
            horizontal, vertical or diagonal line.</para>
          </listitem>
        </itemizedlist>

        <para>The most common n queens puzzle is the 8 queens puzzle, with <emphasis>n = 8</emphasis>. We'll explain
        Drools Planner using the 4 queens puzzle as the primary example.</para>

        <para>A proposed solution could be:</para>

          <title>A wrong solution for the 4 queens puzzle</title>

          <mediaobject>
            <imageobject>
              <imagedata align="center"
                         fileref="images/Chapter-Use_cases_and_examples/partiallySolvedNQueens04Explained.png"
                         format="PNG"></imagedata>
            </imageobject>
          </mediaobject>

        <para>The above solution is wrong because queens <literal>A1</literal> and <literal>B0</literal> can attack each
        other (so can queens <literal>B0</literal> and <literal>D0</literal>). Removing queen <literal>B0</literal>
        would respect the "no 2 queens can attack each other" constraint, but would break the "place n queens"
        constraint.</para>

        <title>Solution(s)</title>

        <para>Below is a correct solution:</para>

          <title>A correct solution for the 4 queens puzzle</title>

          <mediaobject>
            <imageobject>
              <imagedata align="center" fileref="images/Chapter-Use_cases_and_examples/solvedNQueens04.png" format="PNG"></imagedata>
            </imageobject>
          </mediaobject>

        <para>All the constraints have been met, so the solution is correct. Note that most n queens puzzles have
        multiple correct solutions. We'll focus on finding a single correct solution for a given n, not on finding the
        number of possible correct solutions for a given n.</para>

        <title>Screenshot</title>

        <para>Here is a screenshot of the example:</para>

          <title>Screenshot of the n queens example</title>

          <mediaobject>
            <imageobject>
              <imagedata fileref="images/Chapter-Use_cases_and_examples/screenshotNQueens.png"></imagedata>
            </imageobject>
          </mediaobject>

        <title>Problem size</title>

        <para>These numbers might give you some insight in the size of this problem.</para>

          <title>NQueens problem size</title>

          <tgroup cols="5">

              <row>
                <entry># queens (n)</entry>

                <entry># possible solutions (each queen its own column)</entry>

                <entry># feasible solutions (= optimal in this use case)</entry>

                <entry># optimal solutions</entry>

                <entry># optimal <emphasis>out of</emphasis> # possible</entry>
              </row>

              <row>
                <entry>4</entry>

                <entry>256</entry>

                <entry>2</entry>

                <entry>2</entry>

                <entry>1 <emphasis>out of </emphasis>128</entry>
              </row>

              <row>
                <entry>8</entry>

                <entry>16777216</entry>

                <entry>64</entry>

                <entry>64</entry>

                <entry>1 <emphasis>out of</emphasis> 262144</entry>
              </row>

              <row>
                <entry>16</entry>

                <entry>18446744073709551616</entry>

                <entry>14772512</entry>

                <entry>14772512</entry>

                <entry>1 <emphasis>out of</emphasis> 1248720872503</entry>
              </row>

              <row>
                <entry>32</entry>

                <entry>1.46150163733090291820368483e+48</entry>

                <entry>?</entry>

                <entry>?</entry>

                <entry>?</entry>
              </row>

              <row>
                <entry>64</entry>

                <entry>3.94020061963944792122790401e+115</entry>

                <entry>?</entry>

                <entry>?</entry>

                <entry>?</entry>
              </row>

              <row>
                <entry>n</entry>

                <entry>n ^ n</entry>

                <entry>?</entry>

                <entry># feasible solutions</entry>

                <entry>?</entry>
              </row>

          </tgroup>

        <para>The Drools Planner implementation of the N queens example has not been optimized because it functions as a beginner example.
        Nevertheless, it can easily handle 64 queens.</para>

        <title>Domain model</title>

        <para>Use a good domain model: it will be easier to understand and solve your planning problem with Drools
        Planner. This is the domain model for the n queens example:</para>

        <programlisting language="java">public class Column {

    private int index;

    // ... getters and setters
}</programlisting>

        <programlisting language="java">public class Row {

    private int index;

    // ... getters and setters
}</programlisting>

        <programlisting language="java">public class Queen {

    private Column column;
    private Row row;

    public int getAscendingDiagonalIndex() {...}
    public int getDescendingDiagonalIndex() {...}

    // ... getters and setters
}</programlisting>

        <programlisting language="java">public class NQueens implements Solution<SimpleScore> {

    private int n;
    private List<Column> columnList;
    private List<Row> rowList;

    private List<Queen> queenList;

    private SimpleScore score;

    // ... getters and setters
}</programlisting>

        <para>A <literal>Queen</literal> instance has a <literal>Column</literal> (for example: 0 is column A, 1 is
        column B, ...) and a <literal>Row</literal> (its row, for example: 0 is row 0, 1 is row 1, ...). Based on the
        column and the row, the ascending diagonal line as well as the descending diagonal line can be calculated. The
        column and row indexes start from the upper left corner of the chessboard.</para>

          <title>A solution for the 4 queens puzzle shown in the domain model</title>

          <tgroup cols="6">

              <row>
                <entry align="center">A solution</entry>

                <entry align="center">Queen</entry>

                <entry>columnIndex</entry>

                <entry>rowIndex</entry>

                <entry>ascendingDiagonalIndex (columnIndex + rowIndex)</entry>

                <entry>descendingDiagonalIndex (columnIndex - rowIndex)</entry>
              </row>

              <row>
                <entry morerows="3"><mediaobject>
                    <imageobject>
                      <imagedata fileref="images/Chapter-Use_cases_and_examples/partiallySolvedNQueens04Explained.png"
                                 format="PNG"></imagedata>
                    </imageobject>
                  </mediaobject></entry>

                <entry>A1</entry>

                <entry>0</entry>

                <entry>1</entry>

                <entry><emphasis role="bold">1 (**)</emphasis></entry>

                <entry>-1</entry>
              </row>

              <row>
                <entry>B0</entry>

                <entry>1</entry>

                <entry><emphasis role="bold">0 (*)</emphasis></entry>

                <entry><emphasis role="bold">1 (**)</emphasis></entry>

                <entry>1</entry>
              </row>

              <row>
                <entry>C2</entry>

                <entry>2</entry>

                <entry>2</entry>

                <entry>4</entry>

                <entry>0</entry>
              </row>

              <row>
                <entry>D0</entry>

                <entry>3</entry>

                <entry><emphasis role="bold">0 (*)</emphasis></entry>

                <entry>3</entry>

                <entry>3</entry>
              </row>

          </tgroup>

        <para>When 2 queens share the same column, row or diagonal line, such as (*) and (**), they can attack each
        other.</para>

        <para>A single <literal>NQueens</literal> instance contains a list of all <literal>Queen</literal> instances. It
        is the <literal>Solution</literal> implementation which will be supplied to, solved by and retrieved from the
        Solver. Notice that in the 4 queens example, NQueens's <literal>getN()</literal> method will always return
        4.</para>

      <title>Cloud balancing</title>

      <para>This example is explained in <link linkend="cloudBalancingTutorial">a tutorial</link>.</para>

      <title>Traveling salesman (TSP - Traveling salesman problem)</title>

        <title>Problem statement</title>

        <para>Given a list of cities, find the shortest tour for a salesman that visits each city exactly once. <link
        xlink:href="http://en.wikipedia.org/wiki/Travelling_salesman_problem">See the wikipedia definition of the
        traveling Salesman Problem.</link></para>

        <para>It is <link xlink:href="http://www.tsp.gatech.edu/">one of the most intensively studied problems</link> in
        computational mathematics. Yet, in the real world, it's often only part of a planning problem, along with other
        constraints, such as employee shift time constraints.</para>

      <title>Manners 2009</title>

        <title>Problem statement</title>

        <para>In Manners 2009, miss Manners is throwing a party again.</para>

        <itemizedlist>
          <listitem>
            <para>This time she invited 144 guests and prepared 12 round tables with 12 seats each.</para>
          </listitem>

          <listitem>
            <para>Every guest should sit next to someone (left and right) of the opposite gender.</para>
          </listitem>

          <listitem>
            <para>And that neighbour should have at least one hobby in common with the guest.</para>
          </listitem>

          <listitem>
            <para>Also, this time there should be 2 politicians, 2 doctors, 2 socialites, 2 sports stars, 2 teachers and
            2 programmers at each table.</para>
          </listitem>

          <listitem>
            <para>And the 2 politicians, 2 doctors, 2 sports stars and 2 programmers shouldn't be the same kind.</para>
          </listitem>
        </itemizedlist>

        <para>Drools Expert also has the normal miss Manners examples (which is much smaller) and employs a brute force
        heuristic to solve it. Drools Planner's implementation employs far more scalable heuristics while still using
        Drools Expert to calculate the score..</para>

    <title>Real examples</title>

      <title>Course timetabling (ITC 2007 track 3 - Curriculum course scheduling)</title>

        <title>Problem statement</title>

        <para>Schedule each lecture into a timeslot and into a room.</para>

        <para>The problem is defined by <link
        xlink:href="http://www.cs.qub.ac.uk/itc2007/curriculmcourse/course_curriculm_index.htm">the International
        Timetabling Competition 2007 track 3</link>.</para>

      <title>Machine reassignment (Google ROADEF 2012)</title>

        <title>Problem statement</title>

        <para>Assign each process to a machine. All processes already have an original (unoptimized) assignment. Each
        process requires an amount of each resource (such as CPU, RAM, ...). This is more complex version of the Cloud
        balancing example.</para>

        <para>The problem is defined by <link xlink:href="http://challenge.roadef.org/2012/en/">the Google ROADEF/EURO
        Challenge 2012</link>.</para>

        <para>Hard constraints:</para>

        <itemizedlist>
          <listitem>
            <para>Maximum capacity: The maximum capacity for each resource for each machine must not be exceeded.</para>
          </listitem>

          <listitem>
            <para>Conflict: Processes of the same service must run on distinct machines.</para>
          </listitem>

          <listitem>
            <para>Spread: Processes of the same service must be spread across locations.</para>
          </listitem>

          <listitem>
            <para>Dependency: The processes of a service depending on another service must run in the neighborhood of a
            process of the other service.</para>
          </listitem>

          <listitem>
            <para>Transient usage: Some resources are transient and count towards the maximum capacity of both the
            original machine as the newly assigned machine.</para>
          </listitem>
        </itemizedlist>

        <para>Soft constraints:</para>

        <itemizedlist>
          <listitem>
            <para>Load: The safety capacity for each resource for each machine should not be exceeded.</para>
          </listitem>

          <listitem>
            <para>Balance: Leave room for future assignments by balancing the available resources on each
            machine.</para>
          </listitem>

          <listitem>
            <para>Process move cost: A process has a move cost.</para>
          </listitem>

          <listitem>
            <para>Service move cost: A service has a move cost.</para>
          </listitem>

          <listitem>
            <para>Machine move cost: Moving a process from machine A to machine B has another A-B specific move
            cost.</para>
          </listitem>
        </itemizedlist>

        <title>Problem size</title>

        <programlisting>model_a1_1: 2 resources, 1 neighborhoods, 4 locations, 4 machines, 79 services, 100 processes and 1 balancePenalties with flooredPossibleSolutionSize (10^60).
model_a1_2: 4 resources, 2 neighborhoods, 4 locations, 100 machines, 980 services, 1000 processes and 0 balancePenalties with flooredPossibleSolutionSize (10^2000).
model_a1_3: 3 resources, 5 neighborhoods, 25 locations, 100 machines, 216 services, 1000 processes and 0 balancePenalties with flooredPossibleSolutionSize (10^2000).
model_a1_4: 3 resources, 50 neighborhoods, 50 locations, 50 machines, 142 services, 1000 processes and 1 balancePenalties with flooredPossibleSolutionSize (10^1698).
model_a1_5: 4 resources, 2 neighborhoods, 4 locations, 12 machines, 981 services, 1000 processes and 1 balancePenalties with flooredPossibleSolutionSize (10^1079).
model_a2_1: 3 resources, 1 neighborhoods, 1 locations, 100 machines, 1000 services, 1000 processes and 0 balancePenalties with flooredPossibleSolutionSize (10^2000).
model_a2_2: 12 resources, 5 neighborhoods, 25 locations, 100 machines, 170 services, 1000 processes and 0 balancePenalties with flooredPossibleSolutionSize (10^2000).
model_a2_3: 12 resources, 5 neighborhoods, 25 locations, 100 machines, 129 services, 1000 processes and 0 balancePenalties with flooredPossibleSolutionSize (10^2000).
model_a2_4: 12 resources, 5 neighborhoods, 25 locations, 50 machines, 180 services, 1000 processes and 1 balancePenalties with flooredPossibleSolutionSize (10^1698).
model_a2_5: 12 resources, 5 neighborhoods, 25 locations, 50 machines, 153 services, 1000 processes and 0 balancePenalties with flooredPossibleSolutionSize (10^1698).</programlisting>

      <title>Vehicle routing</title>

        <title>Problem statement</title>

        <para>Using a fleet of vehicles, pick up the objects of each customer and bring them to the depot. Each vehicle
        can service multiple customers, but it has a limited capacity.</para>

        <para>The capacitated vehicle routing problem (CRVP) is defined by <link
        xlink:href="http://neo.lcc.uma.es/radi-aeb/WebVRP/">the VRP web</link>.</para>

      <title>Hospital bed planning (PAS - Patient admission scheduling)</title>

        <title>Problem statement</title>

        <para>Assign each patient (that will come to the hospital) into a bed for each night that the patient will stay
        in the hospital. Each bed belongs to a room and each room belongs to a department. The arrival and departure
        dates of the patients is fixed: only a bed needs to be assigned for each night.</para>

        <para>There are a couple of hard constraints:</para>

        <itemizedlist>
          <listitem>
            <para>2 patients shouldn't be assigned to the same bed in the same night.</para>
          </listitem>

          <listitem>
            <para>A room can have a gender limitation: only females, only males, the same gender in the same night or no
            gender limitation at all.</para>
          </listitem>

          <listitem>
            <para>A department can have a minimum or maximum age.</para>
          </listitem>

          <listitem>
            <para>A patient can require a room with specific equipment(s).</para>
          </listitem>
        </itemizedlist>

        <para>And of course, there are also some soft constraints:</para>

        <itemizedlist>
          <listitem>
            <para>A patient can prefer a maximum room size, for example if he/she want a single room.</para>
          </listitem>

          <listitem>
            <para>A patient is best assigned to a department that specializes in his/her problem.</para>
          </listitem>

          <listitem>
            <para>A patient is best assigned to a room that specializes in his/her problem.</para>
          </listitem>

          <listitem>
            <para>A patient can prefer a room with specific equipment(s).</para>
          </listitem>
        </itemizedlist>

        <para>The problem is defined on <link xlink:href="http://allserv.kahosl.be/~peter/pas/">this webpage</link> and
        the test data comes from real world hospitals.</para>

        <mediaobject>
          <imageobject>
            <imagedata fileref="images/Chapter-Use_cases_and_examples/patientAdmissionScheduleUseCase.png"></imagedata>
          </imageobject>
        </mediaobject>

    <title>Difficult examples</title>

      <title>Exam timetabling (ITC 2007 track 1 - Examination)</title>

        <title>Problem statement</title>

        <para>Schedule each exam into a period and into a room. Multiple exams can share the same room during the same
        period.</para>

        <para>There are a number of hard constraints that cannot be broken:</para>

        <itemizedlist>
          <listitem>
            <para>Exam conflict: 2 exams that share students should not occur in the same period.</para>
          </listitem>

          <listitem>
            <para>Room capacity: A room's seating capacity should suffice at all times.</para>
          </listitem>

          <listitem>
            <para>Period duration: A period's duration should suffice for all of its exams.</para>
          </listitem>

          <listitem>
            <para>Period related hard constraints should be fulfilled:</para>

            <itemizedlist>
              <listitem>
                <para>Coincidence: 2 exams should use the same period (but possibly another room).</para>
              </listitem>

              <listitem>
                <para>Exclusion: 2 exams should not use the same period.</para>
              </listitem>

              <listitem>
                <para>After: 1 exam should occur in a period after another exam's period.</para>
              </listitem>
            </itemizedlist>
          </listitem>

          <listitem>
            <para>Room related hard constraints should be fulfilled:</para>

            <itemizedlist>
              <listitem>
                <para>Exclusive: 1 exam should not have to share its room with any other exam.</para>
              </listitem>
            </itemizedlist>
          </listitem>
        </itemizedlist>

        <para>There are also a number of soft constraints that should be minimized (each of which has parametrized
        penalty's):</para>

        <itemizedlist>
          <listitem>
            <para>2 exams in a row.</para>
          </listitem>

          <listitem>
            <para>2 exams in a day.</para>
          </listitem>

          <listitem>
            <para>Period spread: 2 exams that share students should be a number of periods apart.</para>
          </listitem>

          <listitem>
            <para>Mixed durations: 2 exams that share a room should not have different durations.</para>
          </listitem>

          <listitem>
            <para>Front load: Large exams should be scheduled earlier in the schedule.</para>
          </listitem>

          <listitem>
            <para>Period penalty: Some periods have a penalty when used.</para>
          </listitem>

          <listitem>
            <para>Room penalty: Some rooms have a penalty when used.</para>
          </listitem>
        </itemizedlist>

        <para>It uses large test data sets of real-life universities.</para>

        <para>The problem is defined by <link
        xlink:href="http://www.cs.qub.ac.uk/itc2007/examtrack/exam_track_index.htm">the International Timetabling
        Competition 2007 track 1</link>.</para>

        <mediaobject>
          <imageobject>
            <imagedata fileref="images/Chapter-Use_cases_and_examples/examinationTimetablingUseCase.png"></imagedata>
          </imageobject>
        </mediaobject>

        <title>Problem size</title>

        <para>These numbers might give you some insight on the size of this problem.</para>

          <title>Examination problem size</title>

          <tgroup cols="8">

              <row>
                <entry>Set</entry>

                <entry># students</entry>

                <entry># exams/topics</entry>

                <entry># periods</entry>

                <entry># rooms</entry>

                <entry># possible solutions</entry>

                <entry># feasible solutions</entry>

                <entry># optimal solutions</entry>
              </row>

              <row>
                <entry>exam_comp_set1</entry>

                <entry>7883</entry>

                <entry>607</entry>

                <entry>54</entry>

                <entry>7</entry>

                <entry>10^1564</entry>

                <entry>?</entry>

                <entry>1?</entry>
              </row>

              <row>
                <entry>exam_comp_set2</entry>

                <entry>12484</entry>

                <entry>870</entry>

                <entry>40</entry>

                <entry>49</entry>

                <entry>10^2864</entry>

                <entry>?</entry>

                <entry>1?</entry>
              </row>

              <row>
                <entry>exam_comp_set3</entry>

                <entry>16365</entry>

                <entry>934</entry>

                <entry>36</entry>

                <entry>48</entry>

                <entry>10^3023</entry>

                <entry>?</entry>

                <entry>1?</entry>
              </row>

              <row>
                <entry>exam_comp_set4</entry>

                <entry>4421</entry>

                <entry>273</entry>

                <entry>21</entry>

                <entry>1</entry>

                <entry>10^360</entry>

                <entry>?</entry>

                <entry>1?</entry>
              </row>

              <row>
                <entry>exam_comp_set5</entry>

                <entry>8719</entry>

                <entry>1018</entry>

                <entry>42</entry>

                <entry>3</entry>

                <entry>10^2138</entry>

                <entry>?</entry>

                <entry>1?</entry>
              </row>

              <row>
                <entry>exam_comp_set6</entry>

                <entry>7909</entry>

                <entry>242</entry>

                <entry>16</entry>

                <entry>8</entry>

                <entry>10^509</entry>

                <entry>?</entry>

                <entry>1?</entry>
              </row>

              <row>
                <entry>exam_comp_set7</entry>

                <entry>13795</entry>

                <entry>1096</entry>

                <entry>80</entry>

                <entry>28</entry>

                <entry>10^3671</entry>

                <entry>?</entry>

                <entry>1?</entry>
              </row>

              <row>
                <entry>exam_comp_set8</entry>

                <entry>7718</entry>

                <entry>598</entry>

                <entry>80</entry>

                <entry>8</entry>

                <entry>10^1678</entry>

                <entry>?</entry>

                <entry>1?</entry>
              </row>

              <row>
                <entry>?</entry>

                <entry>s</entry>

                <entry>t</entry>

                <entry>p</entry>

                <entry>r</entry>

                <entry>(p * r) ^ e</entry>

                <entry>?</entry>

                <entry>1?</entry>
              </row>

          </tgroup>

        <para>Geoffrey De Smet (the Drools Planner lead) finished 4th in the International Timetabling Competition
        2007's examination track with a very early version of Drools Planner. Many improvements have been made since
        then.</para>

        <title>Domain model</title>

        <para>Below you can see the main examination domain classes:</para>

          <title>Examination domain class diagram</title>

          <mediaobject>
            <imageobject>
              <imagedata fileref="images/Chapter-Use_cases_and_examples/examinationDomainDiagram.png"></imagedata>
            </imageobject>
          </mediaobject>

        <para>Notice that we've split up the exam concept into an <literal>Exam</literal> class and a
        <literal>Topic</literal> class. The <literal>Exam</literal> instances change during solving (this is the
        planning entity class), when they get another period or room property. The <literal>Topic</literal>,
        <literal>Period</literal> and <literal>Room</literal> instances never change during solving (these are problem
        facts, just like some other classes).</para>

      <title>Employee rostering (INRC 2010 - Nurse rostering)</title>

        <title>Problem statement</title>

        <para>For each shift, assign a nurse to work that shift.</para>

        <para>The problem is defined by <link xlink:href="http://www.kuleuven-kortrijk.be/nrpcompetition">the
        International Nurse Rostering Competition 2010</link>.</para>

        <mediaobject>
          <imageobject>
            <imagedata fileref="images/Chapter-Use_cases_and_examples/employeeShiftRosteringUseCase.png"></imagedata>
          </imageobject>
        </mediaobject>

        <mediaobject>
          <imageobject>
            <imagedata fileref="images/Chapter-Use_cases_and_examples/employeeShiftRosteringHardConstraints.png"></imagedata>
          </imageobject>
        </mediaobject>

        <mediaobject>
          <imageobject>
            <imagedata fileref="images/Chapter-Use_cases_and_examples/employeeShiftRosteringSoftConstraints.png"></imagedata>
          </imageobject>
        </mediaobject>

      <title>Sport scheduling (TTP - Traveling tournament problem)</title>

        <title>Problem statement</title>

        <para>Schedule matches between <emphasis>n</emphasis> teams with the following hard constraints:</para>

        <itemizedlist>
          <listitem>
            <para>Each team plays twice against every other team: once home and once away.</para>
          </listitem>

          <listitem>
            <para>Each team has exactly 1 match on each timeslot.</para>
          </listitem>

          <listitem>
            <para>No team must have more than 3 consecutive home or 3 consecutive away matches.</para>
          </listitem>

          <listitem>
            <para>No repeaters: no 2 consecutive matches of the same 2 opposing teams.</para>
          </listitem>
        </itemizedlist>

        <para>and the following soft constraint:</para>

        <itemizedlist>
          <listitem>
            <para>Minimize the total distance traveled by all teams.</para>
          </listitem>
        </itemizedlist>

        <para>The problem is defined on <link xlink:href="http://mat.gsia.cmu.edu/TOURN/">Michael Trick's website (which
        contains several world records too)</link>.</para>

        <mediaobject>
          <imageobject>
            <imagedata fileref="images/Chapter-Use_cases_and_examples/travelingTournamentUseCase.png"></imagedata>
          </imageobject>
        </mediaobject>

        <title>Simple and smart implementation</title>

        <para>There are 2 implementations (simple and smart) to demonstrate the importance of some performance tips. The
        <literal>DroolsPlannerExamplesApp</literal> always runs the smart implementation, but with these commands you
        can compare the 2 implementations yourself:</para>

        <programlisting>$ mvn exec:exec -Dexec.mainClass="org.drools.planner.examples.travelingtournament.app.simple.SimpleTravelingTournamentApp"
...
$ mvn exec:exec -Dexec.mainClass="org.drools.planner.examples.travelingtournament.app.smart.SmartTravelingTournamentApp"
...</programlisting>

        <para>The smart implementation performs and scales exponentially better than the simple implementation.</para>

        <title>Problem size</title>

        <para>These numbers might give you some insight on the size of this problem.</para>

          <title>Traveling tournament problem size</title>

          <tgroup cols="7">

              <row>
                <entry># teams</entry>

                <entry># days</entry>

                <entry># matches</entry>

                <entry># possible solutions (simple)</entry>

                <entry># possible solutions (smart)</entry>

                <entry># feasible solutions</entry>

                <entry># optimal solutions</entry>
              </row>

              <row>
                <entry>4</entry>

                <entry>6</entry>

                <entry>12</entry>

                <entry>2176782336</entry>

                <entry><= 518400</entry>

                <entry>?</entry>

                <entry>1?</entry>
              </row>

              <row>
                <entry>6</entry>

                <entry>10</entry>

                <entry>30</entry>

                <entry>1000000000000000000000000000000</entry>

                <entry><= 47784725839872000000</entry>

                <entry>?</entry>

                <entry>1?</entry>
              </row>

              <row>
                <entry>8</entry>

                <entry>14</entry>

                <entry>56</entry>

                <entry>1.52464943788290465606136043e+64</entry>

                <entry><= 5.77608277425558771434498864e+43</entry>

                <entry>?</entry>

                <entry>1?</entry>
              </row>

              <row>
                <entry>10</entry>

                <entry>18</entry>

                <entry>90</entry>

                <entry>9.43029892325559280477052413e+112</entry>

                <entry><= 1.07573451027871200629339068e+79</entry>

                <entry>?</entry>

                <entry>1?</entry>
              </row>

              <row>
                <entry>12</entry>

                <entry>22</entry>

                <entry>132</entry>

                <entry>1.58414112478195320415135060e+177</entry>

                <entry><= 2.01650616733413376416949843e+126</entry>

                <entry>?</entry>

                <entry>1?</entry>
              </row>

              <row>
                <entry>14</entry>

                <entry>26</entry>

                <entry>182</entry>

                <entry>3.35080635695103223315189511e+257</entry>

                <entry><= 1.73513467024013808570420241e+186</entry>

                <entry>?</entry>

                <entry>1?</entry>
              </row>

              <row>
                <entry>16</entry>

                <entry>30</entry>

                <entry>240</entry>

                <entry>3.22924601799855400751522483e+354</entry>

                <entry><= 2.45064610271441678267620602e+259</entry>

                <entry>?</entry>

                <entry>1?</entry>
              </row>

              <row>
                <entry>n</entry>

                <entry>2 * (n - 1)</entry>

                <entry>n * (n - 1)</entry>

                <entry>(2 * (n - 1)) ^ (n * (n - 1))</entry>

                <entry><= (((2 * (n - 1))!) ^ (n / 2))</entry>

                <entry>?</entry>

                <entry>1?</entry>
              </row>

          </tgroup>

</chapter>


text:
<?php

namespace Symfony\Component\Validator\Tests;

use PHPUnit\Framework\TestCase;
use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\Constraints\Blank as BlankConstraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\ContainerConstraintValidatorFactory;

class ContainerConstraintValidatorFactoryTest extends TestCase
{
    public function testGetInstanceCreatesValidator()
    {
        $factory = new ContainerConstraintValidatorFactory(new Container());
        $this->assertInstanceOf(DummyConstraintValidator::class, $factory->getInstance(new DummyConstraint()));
    }

    public function testGetInstanceReturnsExistingValidator()
    {
        $factory = new ContainerConstraintValidatorFactory(new Container());
        $v1 = $factory->getInstance(new BlankConstraint());
        $v2 = $factory->getInstance(new BlankConstraint());
        $this->assertSame($v1, $v2);
    }

    public function testGetInstanceReturnsService()
    {
        $validator = new DummyConstraintValidator();
        $container = new Container();
        $container->set(DummyConstraintValidator::class, $validator);

        $factory = new ContainerConstraintValidatorFactory($container);

        $this->assertSame($validator, $factory->getInstance(new DummyConstraint()));
    }

    public function testGetInstanceInvalidValidatorClass()
    {
        $this->expectException('Symfony\Component\Validator\Exception\ValidatorException');
        $constraint = $this->getMockBuilder(Constraint::class)->getMock();
        $constraint
            ->expects($this->once())
            ->method('validatedBy')
            ->willReturn('Fully\\Qualified\\ConstraintValidator\\Class\\Name');

        $factory = new ContainerConstraintValidatorFactory(new Container());
        $factory->getInstance($constraint);
    }
}

class DummyConstraint extends Constraint
{
    public function validatedBy(): string
    {
        return DummyConstraintValidator::class;
    }
}

class DummyConstraintValidator extends ConstraintValidator
{
    public function validate($value, Constraint $constraint)
    {
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Frameset//EN""http://www.w3.org/TR/REC-html40/frameset.dtd">

<TITLE>
XML Standard API: Package org.w3c.dom.bootstrap
</TITLE>
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
    Package
      Class
      Tree
      Serialized
      Deprecated
      Index
      Help

 PREV PACKAGE
 NEXT PACKAGE

  FRAMES
 NO FRAMES

Package org.w3c.dom.bootstrap

Class Summary

DOMImplementationRegistry
A factory that enables applications to obtain instances of
 DOMImplementation.

      Overview
    Package
      Class
      Tree
      Serialized
      Deprecated
      Index
      Help

 PREV PACKAGE
 NEXT PACKAGE

  FRAMES
 NO FRAMES

Copyright © 1999-2010 The Apache Software Foundation. All Rights Reserved.


text:
namespace history {

HistoryPublisher::HistoryPublisher() {
}

HistoryPublisher::~HistoryPublisher() {
}

bool HistoryPublisher::Init() {
  return false;
}

void HistoryPublisher::PublishDataToIndexers(const PageData& page_data)
    const {
}

}  // namespace history


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE reference PUBLIC "-//IXIA//DTD IXIA DITA Composite//EN" "../../system/dtd/ixia/IxiaDitabase.dtd">
<reference id="blackbery_sensors_setOptions" xml:lang="en-us">
    <title><apiname>setOptions()</apiname></title>
    <shortdesc>This function will set a sensor with the specifed options. Sensor options can be set before or after the sensor is active.</shortdesc>
    <refbody>

            <title>Synopsis:</title>

setOptions(data)

            <title>Parameters:</title>

                <dlentry>

<varname>sensor</varname> {Object}

The sensor to listen to.

                </dlentry>
                <dlentry>

<varname>options</varname> {Object}

The options for the sensor being started.

                            <dlentry>

<varname>options.delay</varname> {String}

Time in µs (microseconds) to report back between sensor updates.

                            </dlentry>
                            <dlentry>

<varname>options.background</varname> {Boolean}

Allow sensor to send updates while the screen is off.

                            </dlentry>
                            <dlentry>

<varname>options.batching</varname> {Boolean}

When batching is enabled and supported by the hardware, sensors will report samples in hardware-specific batch sizes to conserve power.

                            </dlentry>
                            <dlentry>

<varname>options.queue</varname> {Boolean}

Enabling the queue creates a client-specific service side queue of events, this is useful to not miss any events.

                            </dlentry>
                            <dlentry>

<varname>options.reducedReporting</varname> {Boolean}

When reduced reporting is enabled, only a significant change between the last read event and the current unread event will cause an event to be delivered (useful for power saving).

                            </dlentry>

                </dlentry>

    </refbody>
</reference>


text:
/* jshint node: true */
'use strict';

var chai = require('chai');
var expect = chai.expect;
var contentForHead = require('../../lib/content-for-head');

var config;

describe('contentForHead', function() {
  beforeEach(function() {
    config = defaultConfiguration();
  });

  it('is undefined with no config', function() {
    expect(contentForHead()).to.equal(undefined);
  });

  describe('production', function() {
    beforeEach(function() {
      config.environment = 'production';
    });

    it('ignores invalid config', function() {
      testInvalidConfigs(config, undefined);
    });

    it('with no special config returns nothing', function() {
      expect(contentForHead(config)).to.equal(undefined);
    });

  });

  ['development', 'test'].forEach(function(env) {
     describe(env, function() {

       beforeEach(function() {
         config.environment = env;
       });

       it('ignores invalid config', function() {
         testInvalidConfigs(config, expectedScript(100));
       });

       it('defaults to 100 when not configured', function() {
         expect(contentForHead(config)).to.equal(expectedScript(100));
       });
     });
  });

  ['development', 'test', 'production'].forEach(function(env) {
    describe('Default behavior: ' + env, function() {

      beforeEach(function() {
        config.environment = env;
      });

      it('uses config value if there is a valid one', function() {
        config.stackTraceLimit = 101;
        expect(contentForHead(config)).to.equal(expectedScript(101));
      });

    });

  });

});

// Double entry bookkeeping
function expectedScript(value) {
  return '<script>Error.stackTraceLimit=' + value + ';</script>';
}

function defaultConfiguration() {
  return {};
}

function testInvalidConfigs(config, expected) {
  var invalidValues = ["101", {}, [], true, function() { return 40; }, null];
  var count = invalidValues.length;
  invalidValues.forEach(function(val) {
    config.stackTraceLimit = val;
    expect(contentForHead(config)).to.equal(expected);
    count--;
  });
  expect(count).to.equal(0);
}


text:
<?php

namespace Apihour\SettingsBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Tutto\CommonBundle\Entity\AbstractEntity;

/**
 * Class AbstractDataHasOption
 * @package Apihour\SettingsBundle\Entity
 *
 * @ORM\MappedSuperclass()
 */
abstract class AbstractDataHasOption extends AbstractEntity {
    /**
     * @ORM\Column(type="array", nullable=false)
     *
     * @var mixed
     */
    private $value;

    /**
     * @return AbstractDataOption
     */
    abstract public function getOption();

    /**
     * @param AbstractDataOption $option
     * @return void
     */
    abstract public function setOption(AbstractDataOption $option);

    /**
     * @return mixed
     */
    public function getValue() {
        return $this->value;
    }

    /**
     * @param mixed $value
     */
    public function setValue($value) {
        $this->value = $value;
    }
}


text:
/*
 * loader.c -- the NetBSD system loader
 */

#include "types.h"
#include "disklabel.h"
#include "fs.h"
#include "dinode.h"
#include "dir.h"
#include "stdarg.h"
#include "auxlib.h"
#include "biolib.h"
#include "elf.h"

/**************************************************************/

/* constants and data types */

#define DFLT_KERNEL	"/netbsd"	/* default path to kernel */

#define MAX_LINE	100		/* line buffer size */

#define SSHIFT		9		/* ld of sector size */
#define SSIZE		(1 << SSHIFT)	/* disk sector size in bytes */
#define SMASK		(SSIZE - 1)	/* sector mask */

#define BSHIFT		13		/* ld of block size */
#define BSIZE		(1 << BSHIFT)	/* disk block size in bytes */
#define BMASK		(BSIZE - 1)	/* block mask */

typedef struct ufs1_dinode Dinode;
typedef struct direct Dirent;
typedef unsigned int daddr_t;
typedef unsigned int ino_t;

#define NIPB		(BSIZE / sizeof(Dinode))

#define NULL		0

/**************************************************************/

/* debugging */

Bool debugReadSectors = FALSE;
Bool debugReadDiskLabel = FALSE;
Bool debugReadSuperBlock = FALSE;
Bool debugGetInode = FALSE;
Bool debugSearchDir = FALSE;
Bool debugLoadElf = FALSE;

/**************************************************************/

/* halt with error message */

void halt(char *msg) {
  printf("%s, machine halted.\n", msg);
  while (1) ;
}

/**************************************************************/

/* disk I/O */

unsigned int bootDisk = 0;	/* gets loaded by previous stage */
				/* never changed */
unsigned int startSector = 0;	/* gets loaded by previous stage */
				/* initially holds start of slice */
				/* disklabel read --> start of partition */
unsigned int numSectors = 0;	/* gets loaded by previous stage */
				/* initially holds size of slice */
				/* disklabel read --> size of partition */

unsigned int spf;		/* superblock read --> sectors per fragment */
unsigned int spb;		/* superblock read --> sectors per block */

/*
 * read disk sectors
 *
 * NOTE: buffer must be word-aligned
 */
void readSectors(unsigned int start,
                 unsigned int count,
                 void *buffer) {
  unsigned int sector;
  int result;

  if (start + count > numSectors) {
    halt("Sector number exceeds slice or partition size");
  }
  sector = startSector + start;
  if (debugReadSectors) {
    printf("DEBUG: reading sector 0x%08X, %d sectors\n", sector, count);
  }
  result = rwscts(bootDisk, 'r', sector,
                  (unsigned int) buffer & 0x3FFFFFFF, count);
  if (result != 0) {
    halt("Load error");
  }
}

/**************************************************************/

/* disklabel handling */

unsigned int diskLabel[SSIZE / sizeof(unsigned int)];
DiskLabel *dlp = (DiskLabel *) &diskLabel[0];

unsigned int superStart;	/* partition-relative offset, in sectors */
unsigned int superSize;		/* size, in sectors */

void readDiskLabel(void) {
  readSectors(1, 1, dlp);
  if (dlp->d_magic != DSKMAGIC ||
      dlp->d_magic2 != DSKMAGIC) {
    halt("Disklabel corrupted");
  }

  startSector = dlp->d_parts[0].p_offset;
  numSectors = dlp->d_parts[0].p_size;

  superStart = dlp->d_bbsize;
  if ((superStart & SMASK) != 0) {
    halt("Superblock offset is not multiple of sector size");
  }
  superStart >>= SSHIFT;

  superSize = dlp->d_sbsize;
  if ((superSize & SMASK) != 0) {
    halt("Superblock size is not multiple of sector size");
  }
  if (superSize > BSIZE) {
    halt("Superblock too big");
  }
  superSize >>= SSHIFT;

  if (debugReadDiskLabel) {
    printf("DEBUG: super start = %d sectors, super size = %d sectors\n",
           superStart, superSize);
  }
}

/**************************************************************/

/* superblock handling */

unsigned int superBlock[BSIZE / sizeof(unsigned int)];
struct fs *sbp = (struct fs *) &superBlock[0];

void readSuperBlock(void) {
  readSectors(superStart, superSize, sbp);
  if (sbp->fs_magic != FS_UFS1_MAGIC) {
    halt("Wrong magic number in superblock");
  }
  spf = sbp->fs_fsize / SSIZE;
  spb = sbp->fs_bsize / SSIZE;
  if (sbp->fs_inopb != NIPB) {
    halt("Wrong number of inodes per block");
  }
  if (debugReadSuperBlock) {
    printf("DEBUG: %d sectors per fragment\n", spf);
    printf("DEBUG: %d sectors per block\n", spb);
    printf("DEBUG: %d inodes per block\n", NIPB);
  }
}

/**************************************************************/

/* file operations */

unsigned int sibno = 0;
unsigned int sib[8192 / sizeof(unsigned int)];
unsigned int *sibp = (unsigned int *) &sib[0];

/*
 * read a block of a file
 *
 * NOTE: addr must be word-aligned
 */
void readFileBlock(Dinode *ip, int blkno, void *addr) {
  unsigned int diskFrag;

  if (blkno < NDADDR) {
    /* direct block */
    diskFrag = ip->di_db[blkno];
  } else
  if (blkno - NDADDR < sbp->fs_bsize / sizeof(int32_t)) {
    /* single indirect block */
    if (sibno != ip->di_ib[0]) {
      sibno = ip->di_ib[0];
      readSectors(sibno * spf, spb, sibp);
    }
    diskFrag = sibp[blkno - NDADDR];
  } else {
    /* double or triple indirect blocks */
    halt("Cannot do double or triple indirect blocks");
  }
  readSectors(diskFrag * spf, spb, addr);
}

/*
 * read a number of bytes from a file
 */
void readFile(Dinode *ip, unsigned int offset,
              unsigned int size, void *buffer) {
  unsigned int dskblk[8192 / sizeof(unsigned int)];
  unsigned char *bufp;
  unsigned char *blkp;
  unsigned int blkno;
  unsigned int index;
  unsigned int aux;
  unsigned int numBytes;
  int i;

  bufp = (unsigned char *) buffer;
  blkp = (unsigned char *) dskblk;
  blkno = offset / sbp->fs_bsize;
  index = offset % sbp->fs_bsize;
  aux = sbp->fs_bsize - index;
  numBytes = (size <= aux) ? size : aux;
  readFileBlock(ip, blkno, blkp);
  for (i = 0; i < numBytes; i++) {
    *bufp++ = blkp[index++];
  }
  blkno++;
  size -= numBytes;
  while (size >= sbp->fs_bsize) {
    index = 0;
    numBytes = sbp->fs_bsize;
    readFileBlock(ip, blkno, blkp);
    for (i = 0; i < numBytes; i++) {
      *bufp++ = blkp[index++];
    }
    blkno++;
    size -= numBytes;
  }
  if (size > 0) {
    index = 0;
    numBytes = size;
    readFileBlock(ip, blkno, blkp);
    for (i = 0; i < numBytes; i++) {
      *bufp++ = blkp[index++];
    }
  }
}

/**************************************************************/

/* inode handling */

unsigned int inodeBlock[BSIZE / sizeof(unsigned int)];
Dinode *ibp = (Dinode *) &inodeBlock[0];

Dinode *getInode(unsigned int inode) {
  unsigned int fnum;
  unsigned int inum;
  Dinode *ip;

  fnum = ino_to_fsba(sbp, inode);
  inum = ino_to_fsbo(sbp, inode);
  if (debugGetInode) {
    printf("DEBUG: getting inode 0x%08X\n", inode);
    printf("DEBUG: this is in fragment %d, inode %d\n", fnum, inum);
  }
  readSectors(fnum * spf, spb, ibp);
  ip = ibp + inum;
  if (ip->di_size[0] != 0) {
    halt("File too big");
  }
  if (debugGetInode) {
    printf("DEBUG: mode of file = 0x%04X\n", ip->di_mode);
    printf("DEBUG: size of file = 0x%08X\n", ip->di_size[1]);
  }
  return ip;
}

/**************************************************************/

/* convert path to inode */

unsigned int directoryBlock[BSIZE / sizeof(unsigned int)];
Dirent *dbp = (Dirent *) &directoryBlock[0];

Dinode *pathToInode(char *path) {
  Dinode *ip;
  char c;
  char dirBuffer[FFS_MAXNAMLEN];
  char *cp;
  unsigned int offset;
  Dirent *dp;
  unsigned int ino;
  unsigned int len;

  /* get root inode */
  ip = getInode(ROOTINO);
  /* traverse file system tree while matching path components */
  c = *path++;
  while (1) {
    /* skip leading slashes in path component */
    while (c == '/') {
      c = *path++;
    }
    if (c == '\0') {
      /* no more path components */
      break;
    }
    /* if there is another component, gather up its name */
    cp = dirBuffer;
    while (c != '/' && c != '\0') {
      if (cp < &dirBuffer[FFS_MAXNAMLEN]) {
        *cp++ = c;
      }
      c = *path++;
    }
    *cp++ = '\0';
    /* ip must be a directory */
    if ((ip->di_mode & IFMT) != IFDIR) {
      return NULL;
    }
    if (debugSearchDir) {
      printf("DEBUG: this is a directory, ok\n");
      printf("DEBUG: path component to search for = '%s'\n", dirBuffer);
    }
    /* search directory */
    offset = 0;
    while (1) {
      if (offset >= ip->di_size[1]) {
        /* component not found */
        return NULL;
      }
      if ((offset & BMASK) == 0) {
        /* read the next directory block */
        readFileBlock(ip, offset >> BSHIFT, dbp);
        dp = dbp;
      }
      ino = dp->d_fileno;
      len = dp->d_reclen;
      if (debugSearchDir) {
        printf("DEBUG: ino = %4d, len = %4d, ", ino, len);
        printf("dirsiz = %4d, name = %s\n", DIRSIZ(0, dp, 0), dp->d_name);
      }
      if (ino != 0) {
        if (strcmp(dirBuffer, dp->d_name) == 0) {
          /* component found */
          break;
        }
      }
      /* no match, try next entry */
      dp = (Dirent *) ((unsigned char *) dp + len);
      offset += len;
    }
    /* get corresponding inode */
    ip = getInode(ino);
    /* look for more components */
  }
  return ip;
}

/**************************************************************/

/* load an ELF executable */

#define MAX_PHDR_SIZE	100

Bool loadElf(Dinode *ip, unsigned int *entryPointPtr) {
  Elf32_Ehdr fileHeader;
  Elf32_Addr entry;
  Elf32_Off phoff;
  Elf32_Half phentsize;
  Elf32_Half phnum;
  int i;
  unsigned int phdrBuf[MAX_PHDR_SIZE / sizeof(unsigned int)];
  Elf32_Phdr *phdrPtr;
  Elf32_Word ptype;
  Elf32_Off offset;
  Elf32_Addr address;
  Elf32_Word filesize;
  Elf32_Word memsize;
  Elf32_Word flags;
  Elf32_Word align;
  unsigned char *memPtr;
  int j;

  readFile(ip, 0, sizeof(Elf32_Ehdr), &fileHeader);
  if (fileHeader.e_ident[EI_MAG0] != ELFMAG0 ||
      fileHeader.e_ident[EI_MAG1] != ELFMAG1 ||
      fileHeader.e_ident[EI_MAG2] != ELFMAG2 ||
      fileHeader.e_ident[EI_MAG3] != ELFMAG3 ||
      fileHeader.e_ident[EI_CLASS] != ELFCLASS32 ||
      fileHeader.e_ident[EI_DATA] != ELFDATA2MSB ||
      fileHeader.e_type != ET_EXEC ||
      fileHeader.e_machine != EM_ECO32) {
    /* file is not in ECO32-ELF executable format */
    return FALSE;
  }
  entry = fileHeader.e_entry;
  phoff = fileHeader.e_phoff;
  phentsize = fileHeader.e_phentsize;
  phnum = fileHeader.e_phnum;
  if (debugLoadElf) {
    printf("DEBUG: entry point (virtual addr) : 0x%08X\n", entry);
    printf("DEBUG: program header table at    : %d\n", phoff);
    printf("DEBUG: prog hdr tbl entry size    : %d\n", phentsize);
    printf("DEBUG: num prog hdr tbl entries   : %d\n", phnum);
  }
  for (i = 0 ; i < phnum; i++) {
    printf("Processing program header %d\n", i);
    readFile(ip, phoff + i * phentsize, phentsize, phdrBuf);
    phdrPtr = (Elf32_Phdr *) phdrBuf;
    ptype = phdrPtr->p_type;
    if (ptype != PT_LOAD) {
      printf("    type is %u, ignored\n", ptype);
      continue;
    }
    offset = phdrPtr->p_offset;
    address = phdrPtr->p_vaddr;
    filesize = phdrPtr->p_filesz;
    memsize = phdrPtr->p_memsz;
    flags = phdrPtr->p_flags;
    align = phdrPtr->p_align;
    if (debugLoadElf) {
      printf("DEBUG: offset   : 0x%08X bytes\n", offset);
      printf("DEBUG: address  : 0x%08X\n", address);
      printf("DEBUG: filesize : 0x%08X bytes\n", filesize);
      printf("DEBUG: memsize  : 0x%08X bytes\n", memsize);
      printf("DEBUG: flags    : 0x%08X\n", flags);
      printf("DEBUG: align    : 0x%08X\n", align);
    }
    memPtr = (unsigned char *) address;
    readFile(ip, offset, filesize, memPtr);
    for (j = filesize; j < memsize; j++) {
      memPtr[j] = 0;
    }
    printf("    segment of %u bytes read", filesize);
    printf(" (+ %u bytes zeroed)", memsize - filesize);
    printf(", vaddr = 0x%08X\n", address);
  }
  *entryPointPtr = entry;
  return TRUE;
}

/**************************************************************/

/* main program */

unsigned int entryPoint;	/* where to continue from main() */

int main(void) {
  char line[MAX_LINE];
  Dinode *ip;

  printf("\n");
  printf("NetBSD system loader\n");
  readDiskLabel();
  readSuperBlock();
  strcpy(line, DFLT_KERNEL);
  while (1) {
    getLine("\nPlease enter path to kernel: ", line, MAX_LINE);
    ip = pathToInode(line);
    if (ip == NULL) {
      printf("'%s' not found\n", line);
      continue;
    }
    if ((ip->di_mode & IFMT) != IFREG) {
      printf("'%s' is not a regular file\n", line);
      continue;
    }
    printf("Loading '%s'...\n", line);
    if (!loadElf(ip, &entryPoint)) {
      printf("'%s' cannot be loaded\n", line);
      continue;
    }
    /* kernel successfully loaded */
    break;
  }
  printf("Starting '%s' at address 0x%08X...\n", line, entryPoint);
  return 0;
}


text:
@interface TLAboutFooterView : UICollectionReusableView <ZZFlexibleLayoutViewProtocol>

@end


text:
/** @file
 * allocation interface implementation
 * @author Justin R. Cutler <justin.r.cutler@gmail.com>
 */

/* errno, ENOMEM */
#include <errno.h>
/* size_t, NULL */
#include <stddef.h>

/* ... */
#include <threadless/allocation.h>

#ifndef SIZE_MAX
# define SIZE_MAX ((size_t)-1)
#endif

#define SQRT_SIZE_MAX_PLUS_1 ((size_t)1 << (sizeof(size_t) * 4))

int allocation_realloc_array(allocation_t *allocation, size_t nmemb,
    size_t size)
{
    /* test for multiplication overflow */
    if (((nmemb >= SQRT_SIZE_MAX_PLUS_1) || (size >= SQRT_SIZE_MAX_PLUS_1)) &&
        (nmemb != 0) && ((SIZE_MAX / nmemb) < size)) {
        /* overflow detected */
        errno = ENOMEM;
        return -1;
    }

    size_t alloc_size = nmemb * size;

    /* perform allocator action */
    return allocation->allocator->allocate(allocation, alloc_size);
}


text:
/**
 * @Company Google
 *
 * Given an array of length n and an integer k where 0 < k <= n, find the largest subarray of length k by the following definition.
 * Subarray A is larger than subarray B if the value at index i is greater. Similar to the lexicographical ordering of strings.
 * The first occurence of a value that differs between A and B will determine which ever is bigger.
 *
 * Ex. [ 1, 2, 2, 2, 4 ] is larger than [ 1, 2, 2, 2, 3 ]
 *     [ 1, 4 ] is larger than [ 1, 2 ]
 *
 * Problem Ex.
 *   Input: [ 1, 4, 1, 4, 5 ], k = 3
 *   Output: [ 4, 1, 4 ]
 *
 *   There are 3 subarrays of length 3 in the given array, [ 1, 4, 1 ], [ 4, 1, 4 ], [ 1, 4, 5 ].
 *   The ordering of the three subarrays from greatest to least are as follows:
 *   [ 4, 1, 4 ]
 *   [ 1, 4, 5 ]
 *   [ 1, 4, 1 ]
 *
 *   [ 4, 1, 4 ] is the largest because its first index is already greater than the other two subarrays.
 *   Since we want the greatest subarray, the answer will be the first one.
 *   The order of the next two are determined at index 2 because 5 > 1.
 *
 * Note: there are n - k + 1 subarrays in an array of length n of size k.
 */
public static int[] largestSubarray(int[] arr, int k) {
  int numOfSub = arr.length - k + 1;
  int[][] subarrays = new int[numOfSub][k];
  int maxIndex = 0;

  for (int i = 0; i < numOfSub; i ++) {
    boolean updated = false;
    for (int j = 0; j < k; j ++) {
      subarrays[i][j] = arr[i + j];

      // If the current subarray is the max subarray, then just populate.
      // Also, if the max subarray has already been updated then, just populate.
      // Also, continue if the two values are equal.
      if (i == maxIndex || updated || subarrays[i][j] == subarrays[maxIndex][j]) continue;

      // New max sub array
      if (subarrays[i][j] > subarrays[maxIndex][j]) maxIndex = i;

      // Set update to true regardless of which is greater.
      updated = true;
    }
  }

  return subarrays[maxIndex];
}


text:
namespace System
{
    /// <summary>
    ///     Represents the method that will handle the event raised by an exception that is not handled by the application domain.
    /// </summary>
    /// <param name="sender">The source of the unhandled exception event. </param>
    /// <param name="e">An <see cref="UnhandledExceptionEventArgs"/> instance containing the event data.</param>
    /// <seealso cref="UnhandledExceptionEventArgs"/>
    /// <seealso cref="EventHandler"/>
    public delegate void UnhandledExceptionEventHandler(object sender, UnhandledExceptionEventArgs e);
}


text:
using System;
using System.Threading.Tasks;
using DineroPortableClientSDK;
using DineroPortableClientSDK.PurchaseVouchers;

namespace DineroSampleApp
{
    public class PurchaseVoucherDemo
    {
        public static async Task AddNewPurchaseVoucher(Dinero dinero)
        {
            var model = new PurchaseVoucherCreate
            {
                VoucherDate = "2015-12-02",
                Notes = "Some very important notes!"
            };

            var createdResult = await dinero.PurchaseVouchers.AddAsync(model);
            Console.WriteLine("Voucher created. New voucher id: " + createdResult.VoucherGuid);
        }
    }
}