text:
/**
* If you need more fine-grained control over the handling of specific keys you can create and use Phaser.Key objects.
*
* @class Phaser.Key
* @constructor
* @param {Phaser.Game} game - Current game instance.
* @param {integer} keycode - The key code this Key is responsible for. See {@link Phaser.KeyCode}.
*/
Phaser.Key = function (game, keycode) {

    /**
    * @property {Phaser.Game} game - A reference to the currently running game.
    */
    this.game = game;

    /**
    * The enabled state of the key - see `enabled`.
    * @property {boolean} _enabled
    * @private
    */
    this._enabled = true;

    /**
    * @property {object} event - Stores the most recent DOM event.
    * @readonly
    */
    this.event = null;

    /**
    * @property {boolean} isDown - The "down" state of the key. This will remain `true` for as long as the keyboard thinks this key is held down.
    * @default
    */
    this.isDown = false;

    /**
    * @property {boolean} isUp - The "up" state of the key. This will remain `true` for as long as the keyboard thinks this key is up.
    * @default
    */
    this.isUp = true;

    /**
    * @property {boolean} altKey - The down state of the ALT key, if pressed at the same time as this key.
    * @default
    */
    this.altKey = false;

    /**
    * @property {boolean} ctrlKey - The down state of the CTRL key, if pressed at the same time as this key.
    * @default
    */
    this.ctrlKey = false;

    /**
    * @property {boolean} shiftKey - The down state of the SHIFT key, if pressed at the same time as this key.
    * @default
    */
    this.shiftKey = false;

    /**
    * @property {number} timeDown - The timestamp when the key was last pressed down. This is based on Game.time.now.
    */
    this.timeDown = 0;

    /**
    * If the key is down this value holds the duration of that key press and is constantly updated.
    * If the key is up it holds the duration of the previous down session.
    * @property {number} duration - The number of milliseconds this key has been held down for.
    * @default
    */
    this.duration = 0;

    /**
    * @property {number} timeUp - The timestamp when the key was last released. This is based on Game.time.now.
    * @default
    */
    this.timeUp = -2500;

    /**
    * @property {number} repeats - If a key is held down this holds down the number of times the key has 'repeated'.
    * @default
    */
    this.repeats = 0;

    /**
    * @property {number} keyCode - The keycode of this key.
    */
    this.keyCode = keycode;

    /**
    * @property {Phaser.Signal} onDown - This Signal is dispatched every time this Key is pressed down. It is only dispatched once (until the key is released again).
    */
    this.onDown = new Phaser.Signal();

    /**
    * @property {function} onHoldCallback - A callback that is called while this Key is held down. Warning: Depending on refresh rate that could be 60+ times per second.
    */
    this.onHoldCallback = null;

    /**
    * @property {object} onHoldContext - The context under which the onHoldCallback will be called.
    */
    this.onHoldContext = null;

    /**
    * @property {Phaser.Signal} onUp - This Signal is dispatched every time this Key is released. It is only dispatched once (until the key is pressed and released again).
    */
    this.onUp = new Phaser.Signal();

    /**
     * @property {boolean} _justDown - True if the key has just been pressed (NOTE: requires to be reset, see justDown getter)
     * @private
     */
    this._justDown = false;

    /**
     * @property {boolean} _justUp - True if the key has just been pressed (NOTE: requires to be reset, see justDown getter)
     * @private
     */
    this._justUp = false;

};

Phaser.Key.prototype = {

    /**
    * Called automatically by Phaser.Keyboard.
    *
    * @method Phaser.Key#update
    * @protected
    */
    update: function () {

        if (!this._enabled) { return; }

        if (this.isDown)
        {
            this.duration = this.game.time.time - this.timeDown;
            this.repeats++;

            if (this.onHoldCallback)
            {
                this.onHoldCallback.call(this.onHoldContext, this);
            }
        }

    },

    /**
    * Called automatically by Phaser.Keyboard.
    *
    * @method Phaser.Key#processKeyDown
    * @param {KeyboardEvent} event - The DOM event that triggered this.
    * @protected
    */
    processKeyDown: function (event) {

        if (!this._enabled) { return; }

        this.event = event;

        // exit if this key down is from auto-repeat
        if (this.isDown)
        {
            return;
        }

        this.altKey = event.altKey;
        this.ctrlKey = event.ctrlKey;
        this.shiftKey = event.shiftKey;

        this.isDown = true;
        this.isUp = false;
        this.timeDown = this.game.time.time;
        this.duration = 0;
        this.repeats = 0;

        // _justDown will remain true until it is read via the justDown Getter
        // this enables the game to poll for past presses, or reset it at the start of a new game state
        this._justDown = true;

        this.onDown.dispatch(this);

    },

    /**
    * Called automatically by Phaser.Keyboard.
    *
    * @method Phaser.Key#processKeyUp
    * @param {KeyboardEvent} event - The DOM event that triggered this.
    * @protected
    */
    processKeyUp: function (event) {

        if (!this._enabled) { return; }

        this.event = event;

        if (this.isUp)
        {
            return;
        }

        this.isDown = false;
        this.isUp = true;
        this.timeUp = this.game.time.time;
        this.duration = this.game.time.time - this.timeDown;

        // _justUp will remain true until it is read via the justUp Getter
        // this enables the game to poll for past presses, or reset it at the start of a new game state
        this._justUp = true;

        this.onUp.dispatch(this);

    },

    /**
    * Resets the state of this Key.
    *
    * This sets isDown to false, isUp to true, resets the time to be the current time, and _enables_ the key.
    * In addition, if it is a "hard reset", it clears clears any callbacks associated with the onDown and onUp events and removes the onHoldCallback.
    *
    * @method Phaser.Key#reset
    * @param {boolean} [hard=true] - A soft reset won't reset any events or callbacks; a hard reset will.
    */
    reset: function (hard) {

        if (hard === undefined) { hard = true; }

        this.isDown = false;
        this.isUp = true;
        this.timeUp = this.game.time.time;
        this.duration = 0;
        this._enabled = true; // .enabled causes reset(false)
        this._justDown = false;
        this._justUp = false;

        if (hard)
        {
            this.onDown.removeAll();
            this.onUp.removeAll();
            this.onHoldCallback = null;
            this.onHoldContext = null;
        }

    },

    /**
    * Returns `true` if the Key was pressed down within the `duration` value given, or `false` if it either isn't down,
    * or was pressed down longer ago than then given duration.
    *
    * @method Phaser.Key#downDuration
    * @param {number} [duration=50] - The duration within which the key is considered as being just pressed. Given in ms.
    * @return {boolean} True if the key was pressed down within the given duration.
    */
    downDuration: function (duration) {

        if (duration === undefined) { duration = 50; }

        return (this.isDown && this.duration < duration);

    },

    /**
    * Returns `true` if the Key was pressed down within the `duration` value given, or `false` if it either isn't down,
    * or was pressed down longer ago than then given duration.
    *
    * @method Phaser.Key#upDuration
    * @param {number} [duration=50] - The duration within which the key is considered as being just released. Given in ms.
    * @return {boolean} True if the key was released within the given duration.
    */
    upDuration: function (duration) {

        if (duration === undefined) { duration = 50; }

        return (!this.isDown && ((this.game.time.time - this.timeUp) < duration));

    }

};

/**
* The justDown value allows you to test if this Key has just been pressed down or not.
* When you check this value it will return `true` if the Key is down, otherwise `false`.
* You can only call justDown once per key press. It will only return `true` once, until the Key is released and pressed down again.
* This allows you to use it in situations where you want to check if this key is down without using a Signal, such as in a core game loop.
*
* @property {boolean} justDown
* @memberof Phaser.Key
* @default false
*/
Object.defineProperty(Phaser.Key.prototype, "justDown", {

    get: function () {

        var current = this._justDown;
        this._justDown = false;
        return current;

    }

});

/**
* The justUp value allows you to test if this Key has just been released or not.
* When you check this value it will return `true` if the Key is up, otherwise `false`.
* You can only call justUp once per key release. It will only return `true` once, until the Key is pressed down and released again.
* This allows you to use it in situations where you want to check if this key is up without using a Signal, such as in a core game loop.
*
* @property {boolean} justUp
* @memberof Phaser.Key
* @default false
*/
Object.defineProperty(Phaser.Key.prototype, "justUp", {

    get: function () {

        var current = this._justUp;
        this._justUp = false;
        return current;

    }

});

/**
* An enabled key processes its update and dispatches events.
* A key can be disabled momentarily at runtime instead of deleting it.
*
* @property {boolean} enabled
* @memberof Phaser.Key
* @default true
*/
Object.defineProperty(Phaser.Key.prototype, "enabled", {

    get: function () {

        return this._enabled;

    },

    set: function (value) {

        value = !!value;

        if (value !== this._enabled)
        {
            if (!value)
            {
                this.reset(false);
            }

            this._enabled = value;
        }
    }

});

Phaser.Key.prototype.constructor = Phaser.Key;

/**
* @author       Richard Davey <rich@photonstorm.com>
* @copyright    2016 Photon Storm Ltd.
* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/

/**
* The Keyboard class monitors keyboard input and dispatches keyboard events.
*
* _Note_: many keyboards are unable to process certain combinations of keys due to hardware limitations known as ghosting.
* See http://www.html5gamedevs.com/topic/4876-impossible-to-use-more-than-2-keyboard-input-buttons-at-the-same-time/ for more details.
*
* Also please be aware that certain browser extensions can disable or override Phaser keyboard handling.
* For example the Chrome extension vimium is known to disable Phaser from using the D key. And there are others.
* So please check your extensions before opening Phaser issues.
*
* @class Phaser.Keyboard
* @constructor
* @param {Phaser.Game} game - A reference to the currently running game.
*/
Phaser.Keyboard = function (game) {

    /**
    * @property {Phaser.Game} game - Local reference to game.
    */
    this.game = game;

    /**
    * Keyboard input will only be processed if enabled.
    * @property {boolean} enabled
    * @default
    */
    this.enabled = true;

    /**
    * @property {object} event - The most recent DOM event from keydown or keyup. This is updated every time a new key is pressed or released.
    */
    this.event = null;

    /**
    * @property {object} pressEvent - The most recent DOM event from keypress.
    */
    this.pressEvent = null;

    /**
    * @property {object} callbackContext - The context under which the callbacks are run.
    */
    this.callbackContext = this;

    /**
    * @property {function} onDownCallback - This callback is invoked every time a key is pressed down, including key repeats when a key is held down.
    */
    this.onDownCallback = null;

    /**
    * @property {function} onPressCallback - This callback is invoked every time a DOM onkeypress event is raised, which is only for printable keys.
    */
    this.onPressCallback = null;

    /**
    * @property {function} onUpCallback - This callback is invoked every time a key is released.
    */
    this.onUpCallback = null;

    /**
    * @property {array<Phaser.Key>} _keys - The array the Phaser.Key objects are stored in.
    * @private
    */
    this._keys = [];

    /**
    * @property {array} _capture - The array the key capture values are stored in.
    * @private
    */
    this._capture = [];

    /**
    * @property {function} _onKeyDown
    * @private
    * @default
    */
    this._onKeyDown = null;

    /**
    * @property {function} _onKeyPress
    * @private
    * @default
    */
    this._onKeyPress = null;

    /**
    * @property {function} _onKeyUp
    * @private
    * @default
    */
    this._onKeyUp = null;

    /**
    * @property {number} _i - Internal cache var
    * @private
    */
    this._i = 0;

    /**
    * @property {number} _k - Internal cache var
    * @private
    */
    this._k = 0;

};

Phaser.Keyboard.prototype = {

    /**
    * Add callbacks to the Keyboard handler so that each time a key is pressed down or released the callbacks are activated.
    *
    * @method Phaser.Keyboard#addCallbacks
    * @param {object} context - The context under which the callbacks are run.
    * @param {function} [onDown=null] - This callback is invoked every time a key is pressed down.
    * @param {function} [onUp=null] - This callback is invoked every time a key is released.
    * @param {function} [onPress=null] - This callback is invoked every time the onkeypress event is raised.
    */
    addCallbacks: function (context, onDown, onUp, onPress) {

        this.callbackContext = context;

        if (onDown !== undefined && onDown !== null)
        {
            this.onDownCallback = onDown;
        }

        if (onUp !== undefined && onUp !== null)
        {
            this.onUpCallback = onUp;
        }

        if (onPress !== undefined && onPress !== null)
        {
            this.onPressCallback = onPress;
        }

    },

    /**
    * If you need more fine-grained control over a Key you can create a new Phaser.Key object via this method.
    * The Key object can then be polled, have events attached to it, etc.
    *
    * @method Phaser.Keyboard#addKey
    * @param {integer} keycode - The {@link Phaser.KeyCode keycode} of the key.
    * @return {Phaser.Key} The Key object which you can store locally and reference directly.
    */
    addKey: function (keycode) {

        if (!this._keys[keycode])
        {
            this._keys[keycode] = new Phaser.Key(this.game, keycode);

            this.addKeyCapture(keycode);
        }

        return this._keys[keycode];

    },

    /**
    * A practical way to create an object containing user selected hotkeys.
    *
    * For example,
    *
    *     addKeys( { 'up': Phaser.KeyCode.W, 'down': Phaser.KeyCode.S, 'left': Phaser.KeyCode.A, 'right': Phaser.KeyCode.D } );
    *
    * would return an object containing properties (`up`, `down`, `left` and `right`) referring to {@link Phaser.Key} object.
    *
    * @method Phaser.Keyboard#addKeys
    * @param {object} keys - A key mapping object, i.e. `{ 'up': Phaser.KeyCode.W, 'down': Phaser.KeyCode.S }` or `{ 'up': 52, 'down': 53 }`.
    * @return {object} An object containing the properties mapped to {@link Phaser.Key} values.
    */
    addKeys: function (keys) {

        var output = {};

        for (var key in keys)
        {
            output[key] = this.addKey(keys[key]);
        }

        return output;

    },

    /**
    * Removes a Key object from the Keyboard manager.
    *
    * @method Phaser.Keyboard#removeKey
    * @param {integer} keycode - The {@link Phaser.KeyCode keycode} of the key to remove.
    */
    removeKey: function (keycode) {

        if (this._keys[keycode])
        {
            this._keys[keycode] = null;

            this.removeKeyCapture(keycode);
        }

    },

    /**
    * Creates and returns an object containing 4 hotkeys for Up, Down, Left and Right.
    *
    * @method Phaser.Keyboard#createCursorKeys
    * @return {object} An object containing properties: `up`, `down`, `left` and `right` of {@link Phaser.Key} objects.
    */
    createCursorKeys: function () {

        return this.addKeys({ 'up': Phaser.KeyCode.UP, 'down': Phaser.KeyCode.DOWN, 'left': Phaser.KeyCode.LEFT, 'right': Phaser.KeyCode.RIGHT });

    },

    /**
    * Starts the Keyboard event listeners running (keydown and keyup). They are attached to the window.
    * This is called automatically by Phaser.Input and should not normally be invoked directly.
    *
    * @method Phaser.Keyboard#start
    * @protected
    */
    start: function () {

        if (this.game.device.cocoonJS)
        {
            return;
        }

        if (this._onKeyDown !== null)
        {
            //  Avoid setting multiple listeners
            return;
        }

        var _this = this;

        this._onKeyDown = function (event) {
            return _this.processKeyDown(event);
        };

        this._onKeyUp = function (event) {
            return _this.processKeyUp(event);
        };

        this._onKeyPress = function (event) {
            return _this.processKeyPress(event);
        };

        window.addEventListener('keydown', this._onKeyDown, false);
        window.addEventListener('keyup', this._onKeyUp, false);
        window.addEventListener('keypress', this._onKeyPress, false);

    },

    /**
    * Stops the Keyboard event listeners from running (keydown, keyup and keypress). They are removed from the window.
    *
    * @method Phaser.Keyboard#stop
    */
    stop: function () {

        window.removeEventListener('keydown', this._onKeyDown);
        window.removeEventListener('keyup', this._onKeyUp);
        window.removeEventListener('keypress', this._onKeyPress);

        this._onKeyDown = null;
        this._onKeyUp = null;
        this._onKeyPress = null;

    },

    /**
    * Stops the Keyboard event listeners from running (keydown and keyup). They are removed from the window.
    * Also clears all key captures and currently created Key objects.
    *
    * @method Phaser.Keyboard#destroy
    */
    destroy: function () {

        this.stop();

        this.clearCaptures();

        this._keys.length = 0;
        this._i = 0;

    },

    /**
    * By default when a key is pressed Phaser will not stop the event from propagating up to the browser.
    * There are some keys this can be annoying for, like the arrow keys or space bar, which make the browser window scroll.
    *
    * The `addKeyCapture` method enables consuming keyboard event for specific keys so it doesn't bubble up to the the browser
    * and cause the default browser behavior.
    *
    * Pass in either a single keycode or an array/hash of keycodes.
    *
    * @method Phaser.Keyboard#addKeyCapture
    * @param {integer|integer[]|object} keycode - Either a single {@link Phaser.KeyCode keycode} or an array/hash of keycodes such as `[65, 67, 68]`.
    */
    addKeyCapture: function (keycode) {

        if (typeof keycode === 'object')
        {
            for (var key in keycode)
            {
                this._capture[keycode[key]] = true;
            }
        }
        else
        {
            this._capture[keycode] = true;
        }
    },

    /**
    * Removes an existing key capture.
    *
    * @method Phaser.Keyboard#removeKeyCapture
    * @param {integer} keycode - The {@link Phaser.KeyCode keycode} to remove capturing of.
    */
    removeKeyCapture: function (keycode) {

        delete this._capture[keycode];

    },

    /**
    * Clear all set key captures.
    *
    * @method Phaser.Keyboard#clearCaptures
    */
    clearCaptures: function () {

        this._capture = {};

    },

    /**
    * Updates all currently defined keys.
    *
    * @method Phaser.Keyboard#update
    */
    update: function () {

        this._i = this._keys.length;

        while (this._i--)
        {
            if (this._keys[this._i])
            {
                this._keys[this._i].update();
            }
        }

    },

    /**
    * Process the keydown event.
    *
    * @method Phaser.Keyboard#processKeyDown
    * @param {KeyboardEvent} event
    * @protected
    */
    processKeyDown: function (event) {

        this.event = event;

        if (!this.game.input.enabled || !this.enabled)
        {
            return;
        }

        var key = event.keyCode;

        //   The event is being captured but another hotkey may need it
        if (this._capture[key])
        {
            event.preventDefault();
        }

        if (!this._keys[key])
        {
            this._keys[key] = new Phaser.Key(this.game, key);
        }

        this._keys[key].processKeyDown(event);

        this._k = key;

        if (this.onDownCallback)
        {
            this.onDownCallback.call(this.callbackContext, event);
        }

    },

    /**
    * Process the keypress event.
    *
    * @method Phaser.Keyboard#processKeyPress
    * @param {KeyboardEvent} event
    * @protected
    */
    processKeyPress: function (event) {

        this.pressEvent = event;

        if (!this.game.input.enabled || !this.enabled)
        {
            return;
        }

        if (this.onPressCallback)
        {
            this.onPressCallback.call(this.callbackContext, String.fromCharCode(event.charCode), event);
        }

    },

    /**
    * Process the keyup event.
    *
    * @method Phaser.Keyboard#processKeyUp
    * @param {KeyboardEvent} event
    * @protected
    */
    processKeyUp: function (event) {

        this.event = event;

        if (!this.game.input.enabled || !this.enabled)
        {
            return;
        }

        var key = event.keyCode;

        if (this._capture[key])
        {
            event.preventDefault();
        }

        if (!this._keys[key])
        {
            this._keys[key] = new Phaser.Key(this.game, key);
        }

        this._keys[key].processKeyUp(event);

        if (this.onUpCallback)
        {
            this.onUpCallback.call(this.callbackContext, event);
        }

    },

    /**
    * Resets all Keys.
    *
    * @method Phaser.Keyboard#reset
    * @param {boolean} [hard=true] - A soft reset won't reset any events or callbacks that are bound to the Keys. A hard reset will.
    */
    reset: function (hard) {

        if (hard === undefined) { hard = true; }

        this.event = null;

        var i = this._keys.length;

        while (i--)
        {
            if (this._keys[i])
            {
                this._keys[i].reset(hard);
            }
        }

    },

    /**
    * Returns `true` if the Key was pressed down within the `duration` value given, or `false` if it either isn't down,
    * or was pressed down longer ago than then given duration.
    *
    * @method Phaser.Keyboard#downDuration
    * @param {integer} keycode - The {@link Phaser.KeyCode keycode} of the key to check: i.e. Phaser.KeyCode.UP or Phaser.KeyCode.SPACEBAR.
    * @param {number} [duration=50] - The duration within which the key is considered as being just pressed. Given in ms.
    * @return {boolean} True if the key was pressed down within the given duration, false if not or null if the Key wasn't found.
    */
    downDuration: function (keycode, duration) {

        if (this._keys[keycode])
        {
            return this._keys[keycode].downDuration(duration);
        }
        else
        {
            return null;
        }

    },

    /**
    * Returns `true` if the Key was pressed down within the `duration` value given, or `false` if it either isn't down,
    * or was pressed down longer ago than then given duration.
    *
    * @method Phaser.Keyboard#upDuration
    * @param {Phaser.KeyCode|integer} keycode - The keycode of the key to check, i.e. Phaser.KeyCode.UP or Phaser.KeyCode.SPACEBAR.
    * @param {number} [duration=50] - The duration within which the key is considered as being just released. Given in ms.
    * @return {boolean} True if the key was released within the given duration, false if not or null if the Key wasn't found.
    */
    upDuration: function (keycode, duration) {

        if (this._keys[keycode])
        {
            return this._keys[keycode].upDuration(duration);
        }
        else
        {
            return null;
        }

    },

    /**
    * Returns true of the key is currently pressed down. Note that it can only detect key presses on the web browser.
    *
    * @method Phaser.Keyboard#isDown
    * @param {integer} keycode - The {@link Phaser.KeyCode keycode} of the key to check: i.e. Phaser.KeyCode.UP or Phaser.KeyCode.SPACEBAR.
    * @return {boolean} True if the key is currently down, false if not or null if the Key wasn't found.
    */
    isDown: function (keycode) {

        if (this._keys[keycode])
        {
            return this._keys[keycode].isDown;
        }
        else
        {
            return null;
        }

    }

};

/**
* Returns the string value of the most recently pressed key.
* @name Phaser.Keyboard#lastChar
* @property {string} lastChar - The string value of the most recently pressed key.
* @readonly
*/
Object.defineProperty(Phaser.Keyboard.prototype, "lastChar", {

    get: function () {

        if (this.event.charCode === 32)
        {
            return '';
        }
        else
        {
            return String.fromCharCode(this.pressEvent.charCode);
        }

    }

});

/**
* Returns the most recently pressed Key. This is a Phaser.Key object and it changes every time a key is pressed.
* @name Phaser.Keyboard#lastKey
* @property {Phaser.Key} lastKey - The most recently pressed Key.
* @readonly
*/
Object.defineProperty(Phaser.Keyboard.prototype, "lastKey", {

    get: function () {

        return this._keys[this._k];

    }

});

Phaser.Keyboard.prototype.constructor = Phaser.Keyboard;

/**
* A key code represents a physical key on a keyboard.
*
* The KeyCode class contains commonly supported keyboard key codes which can be used
* as keycode`-parameters in several {@link Phaser.Keyboard} and {@link Phaser.Key} methods.
*
* _Note_: These values should only be used indirectly, eg. as `Phaser.KeyCode.KEY`.
* Future versions may replace the actual values, such that they remain compatible with `keycode`-parameters.
* The current implementation maps to the {@link https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode KeyboardEvent.keyCode} property.
*
* _Note_: Use `Phaser.KeyCode.KEY` instead of `Phaser.Keyboard.KEY` to refer to a key code;
* the latter approach is supported for compatibility.
*
* @namespace
*/
Phaser.KeyCode = {
    /** @static */
    A: "A".charCodeAt(0),
    /** @static */
    B: "B".charCodeAt(0),
    /** @static */
    C: "C".charCodeAt(0),
    /** @static */
    D: "D".charCodeAt(0),
    /** @static */
    E: "E".charCodeAt(0),
    /** @static */
    F: "F".charCodeAt(0),
    /** @static */
    G: "G".charCodeAt(0),
    /** @static */
    H: "H".charCodeAt(0),
    /** @static */
    I: "I".charCodeAt(0),
    /** @static */
    J: "J".charCodeAt(0),
    /** @static */
    K: "K".charCodeAt(0),
    /** @static */
    L: "L".charCodeAt(0),
    /** @static */
    M: "M".charCodeAt(0),
    /** @static */
    N: "N".charCodeAt(0),
    /** @static */
    O: "O".charCodeAt(0),
    /** @static */
    P: "P".charCodeAt(0),
    /** @static */
    Q: "Q".charCodeAt(0),
    /** @static */
    R: "R".charCodeAt(0),
    /** @static */
    S: "S".charCodeAt(0),
    /** @static */
    T: "T".charCodeAt(0),
    /** @static */
    U: "U".charCodeAt(0),
    /** @static */
    V: "V".charCodeAt(0),
    /** @static */
    W: "W".charCodeAt(0),
    /** @static */
    X: "X".charCodeAt(0),
    /** @static */
    Y: "Y".charCodeAt(0),
    /** @static */
    Z: "Z".charCodeAt(0),
    /** @static */
    ZERO: "0".charCodeAt(0),
    /** @static */
    ONE: "1".charCodeAt(0),
    /** @static */
    TWO: "2".charCodeAt(0),
    /** @static */
    THREE: "3".charCodeAt(0),
    /** @static */
    FOUR: "4".charCodeAt(0),
    /** @static */
    FIVE: "5".charCodeAt(0),
    /** @static */
    SIX: "6".charCodeAt(0),
    /** @static */
    SEVEN: "7".charCodeAt(0),
    /** @static */
    EIGHT: "8".charCodeAt(0),
    /** @static */
    NINE: "9".charCodeAt(0),
    /** @static */
    NUMPAD_0: 96,
    /** @static */
    NUMPAD_1: 97,
    /** @static */
    NUMPAD_2: 98,
    /** @static */
    NUMPAD_3: 99,
    /** @static */
    NUMPAD_4: 100,
    /** @static */
    NUMPAD_5: 101,
    /** @static */
    NUMPAD_6: 102,
    /** @static */
    NUMPAD_7: 103,
    /** @static */
    NUMPAD_8: 104,
    /** @static */
    NUMPAD_9: 105,
    /** @static */
    NUMPAD_MULTIPLY: 106,
    /** @static */
    NUMPAD_ADD: 107,
    /** @static */
    NUMPAD_ENTER: 108,
    /** @static */
    NUMPAD_SUBTRACT: 109,
    /** @static */
    NUMPAD_DECIMAL: 110,
    /** @static */
    NUMPAD_DIVIDE: 111,
    /** @static */
    F1: 112,
    /** @static */
    F2: 113,
    /** @static */
    F3: 114,
    /** @static */
    F4: 115,
    /** @static */
    F5: 116,
    /** @static */
    F6: 117,
    /** @static */
    F7: 118,
    /** @static */
    F8: 119,
    /** @static */
    F9: 120,
    /** @static */
    F10: 121,
    /** @static */
    F11: 122,
    /** @static */
    F12: 123,
    /** @static */
    F13: 124,
    /** @static */
    F14: 125,
    /** @static */
    F15: 126,
    /** @static */
    COLON: 186,
    /** @static */
    EQUALS: 187,
    /** @static */
    COMMA: 188,
    /** @static */
    UNDERSCORE: 189,
    /** @static */
    PERIOD: 190,
    /** @static */
    QUESTION_MARK: 191,
    /** @static */
    TILDE: 192,
    /** @static */
    OPEN_BRACKET: 219,
    /** @static */
    BACKWARD_SLASH: 220,
    /** @static */
    CLOSED_BRACKET: 221,
    /** @static */
    QUOTES: 222,
    /** @static */
    BACKSPACE: 8,
    /** @static */
    TAB: 9,
    /** @static */
    CLEAR: 12,
    /** @static */
    ENTER: 13,
    /** @static */
    SHIFT: 16,
    /** @static */
    CONTROL: 17,
    /** @static */
    ALT: 18,
    /** @static */
    CAPS_LOCK: 20,
    /** @static */
    ESC: 27,
    /** @static */
    SPACEBAR: 32,
    /** @static */
    PAGE_UP: 33,
    /** @static */
    PAGE_DOWN: 34,
    /** @static */
    END: 35,
    /** @static */
    HOME: 36,
    /** @static */
    LEFT: 37,
    /** @static */
    UP: 38,
    /** @static */
    RIGHT: 39,
    /** @static */
    DOWN: 40,
    /** @static */
    PLUS: 43,
    /** @static */
    MINUS: 44,
    /** @static */
    INSERT: 45,
    /** @static */
    DELETE: 46,
    /** @static */
    HELP: 47,
    /** @static */
    NUM_LOCK: 144
};

// Duplicate Phaser.KeyCode values in Phaser.Keyboard for compatibility
for (var key in Phaser.KeyCode) {
    if (Phaser.KeyCode.hasOwnProperty(key) && !key.match(/[a-z]/)) {
        Phaser.Keyboard[key] = Phaser.KeyCode[key];
    }
}


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.orgama.server;

import org.orgama.shared.action.PutInstanceResponse;
import com.google.inject.Inject;
import com.google.inject.Provider;
import org.orgama.shared.IHasId;
import java.util.ArrayList;

/**
 * Static class that contains the methods for getting and putting instances of
 * classes
 * @author kguthrie
 */
public class SimpleDataServices {

    private static ISimpleDataService dataService;
    private static Object syncLock = new Object();
    private static boolean initialized = false;

    /**
     * creates a new instance of the data provider
     * @param dataService
     */
    @Inject
    public SimpleDataServices(Provider<ISimpleDataService> dataService) {

        if (initialized) {
            return;
        }

        synchronized(syncLock) {

            if (initialized) {
                return;
            }

            SimpleDataServices.dataService = dataService.get();

            initialized = true;
        }
    }

    /**
     * get an instance of the given object
     * @param clazz
     * @param id
     * @return
     */
    public static IHasId<?> get(String className, Object id) {
        return dataService.get(className, id);
    }

    /**
     * get all instances of the given type except the ones in the given set of
     * ids
     * @param clazz
     * @param presentIds
     * @return
     */
    public static ArrayList<IHasId<?>> getAll(String className,
            ArrayList<?> presentIds) {
        return dataService.getAll(className, presentIds);
    }

    public static <T extends IHasId<?>> PutInstanceResponse<T> put(T toPut) {
        return dataService.put(toPut);
    }
}

redpajama_set_name: RedPajamaGithub


text:
#import <UIKit/UIKit.h>

@class TGNavigationController;

@interface TGNavigationBar : UINavigationBar

@property (nonatomic, weak) TGNavigationController *navigationController;

@property (nonatomic, strong) UIView *progressView;

- (id)initWithFrame:(CGRect)frame barStyle:(UIBarStyle)barStyle;

- (void)setHiddenState:(bool)hidden animated:(bool)animated;

- (bool)shouldAddBackdropBackground;
- (unsigned int)indexAboveBackdropBackground;

@end

@interface TGBlackNavigationBar : TGNavigationBar

@end

@interface TGWhiteNavigationBar : TGNavigationBar

@end

@interface TGTransparentNavigationBar : TGNavigationBar

@end


text:
package com.google.template.soy.soytree;

import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.template.soy.exprparse.ExpressionParser;
import com.google.template.soy.exprparse.ParseException;
import com.google.template.soy.exprparse.TokenMgrError;
import com.google.template.soy.exprtree.ExprRootNode;
import com.google.template.soy.soytree.SoyNode.ConditionalBlockNode;
import com.google.template.soy.soytree.SoyNode.ExprHolderNode;

import java.util.List;

/**
 * Node representing a block within an 'if' statement that has a conditional expression (i.e.
 * either the 'if' block or an 'elseif' block).
 *
 * <p> Important: Do not use outside of Soy code (treat as superpackage-private).
 *
 * @author Kai Huang
 */
public class IfCondNode extends AbstractBlockCommandNode
    implements ConditionalBlockNode, ExprHolderNode {

  /** The parsed expression. */
  private final ExprUnion exprUnion;

  /**
   * @param id The id for this node.
   * @param commandName The command name -- either 'if' or 'elseif'.
   * @param commandText The command text.
   */
  public IfCondNode(int id, String commandName, String commandText) {
    super(id, commandName, commandText);
    Preconditions.checkArgument(commandName.equals("if") || commandName.equals("elseif"));

    ExprRootNode<?> expr;
    try {
      expr = (new ExpressionParser(commandText)).parseExpression();
    } catch (TokenMgrError tme) {
      expr = null;
    } catch (ParseException pe) {
      expr = null;
    }

    if (expr != null) {
      exprUnion = new ExprUnion(expr);
    } else {
      maybeSetSyntaxVersion(SyntaxVersion.V1);
      exprUnion = new ExprUnion(commandText);
    }
  }

  /**
   * Copy constructor.
   * @param orig The node to copy.
   */
  protected IfCondNode(IfCondNode orig) {
    super(orig);
    this.exprUnion = (orig.exprUnion != null) ? orig.exprUnion.clone() : null;
  }

  @Override public Kind getKind() {
    return Kind.IF_COND_NODE;
  }

  /** Returns the text of the conditional expression. */
  public String getExprText() {
    return exprUnion.getExprText();
  }

  /** Returns the parsed expression. */
  public ExprUnion getExprUnion() {
    return exprUnion;
  }

  @Override public String getCommandName() {
    return (getParent().getChild(0) == this) ? "if" : "elseif";
  }

  @Override public String getCommandText() {
    return exprUnion.getExprText();
  }

  @Override public String toSourceString() {
    StringBuilder sb = new StringBuilder();
    sb.append(getTagString());
    appendSourceStringForChildren(sb);
    // Note: No end tag.
    return sb.toString();
  }

  @Override public List<ExprUnion> getAllExprUnions() {
    return ImmutableList.of(exprUnion);
  }

  @Override public IfCondNode clone() {
    return new IfCondNode(this);
  }

}


text:
#ifndef _PROCD_COMMON_H
#define _PROCD_COMMON_H

void send_signal(pid_t, int);

#endif


text:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:paddingTop="10dp"
    android:paddingBottom="10dp"
    android:paddingRight="10dp"
    android:paddingLeft="10dp"
    android:textSize="12pt">

</TextView>


text:
var fs = require('fs')
var path = require('path')
var jsdom = require('jsdom')

function svgInjectr(options, cllb) {

    var that = this;

    var srcpath = path.join('', options.source);
    var folderpath = path.dirname(srcpath)

    var selector = (options.selector) ? options.selector : 'svg-inject'

    var jQueryFile = fs.readFileSync(require.resolve("jquery"), "utf8");

    var func = function (window) {
        var $ = window.$;

        var svg_container_tag = $('[' + selector + ']');

        svg_container_tag.each(function(i, e){

            var el = $(e)
            var svg_path = el.attr(selector);

            var svgpath = path.join(folderpath, svg_path);

            var svgSource;
            try {
                svgSource = fs.readFileSync(svgpath, "utf8");

                    // strip comments
                svgSource = svgSource.replace(//g, '')

                var temp = $('

')
                temp.append(svgSource);

                var svg = temp.find('svg')

                // strip away the AI document
                svg.find('#adobe_illustrator_pgf').remove()
                svg.find('foreignobject').remove()
                var svgcontent = svg.find('switch > g').remove()
                svg.find('switch').remove()
                svg.append(svgcontent);

                if(options.removeAttr){
                    el.removeAttr(selector)
                }

                el.append(svg)
            } catch (e) {
                console.log("svg "+svgpath+" failed to load: "+e);
            }

        })

        if(cllb){
            $('.jsdom').remove() // this is fun, remove jsdom with jsdom
            var _out = window.document.documentElement.outerHTML
            cllb(_out)
        }

    }

    jsdom.env({
        file:options.source,
        src:[jQueryFile],
        done:function (err, window) {
            if (err) {
                throw new Error("There were errors: "+err);
            }
            func(window);
        }
    });

};

module.exports = svgInjectr


text:
require 'spec_helper'

module Yy
  describe Comment do
    it "has a valid factory" do
      expect(create :yy_comment).to be_valid
    end

    describe '.associations' do
      it { should belong_to :user }
      it { should belong_to :topic }
    end

    describe '.validations' do
      subject { create :yy_comment }
      it { should validate_presence_of :topic }
      it { should validate_presence_of :user }
      it { should validate_presence_of :content }
    end
  end
end


text:
module CarrierWave
  module Workers
    class Base
      def perform(*args)
        set_args(*args) if args.present?
        constantized_resource[id]
      rescue *not_found_errors
      end

      private
      alias :old_not_found_errors :not_found_errors
      def not_found_errors
        old_not_found_errors.tap do |errors|
          errors << ::Sequel::NoMatchingRow if defined?(::Sequel)
        end
      end

    end
  end
end

module Sequel
  module Plugins
    module CarrierWaveBackgrounder
      def self.apply(model, options = {})
        Rails.logger.warn 'SELF.APPLY'
        model.plugin :hook_class_methods
        model.plugin :dirty
      end

      module ClassMethods
        include CarrierWave::Backgrounder::ORM::Base

        # use base process_in_background and add column to class variable
        def process_in_background(column, worker=::CarrierWave::Workers::ProcessAsset)
          super
          (@@_carrierwave_process_in_background ||= {})[:"#{column}"] = worker
        end

        # use base store_in_background and add column to class variable
        def store_in_background(column, worker=::CarrierWave::Workers::StoreAsset)
          super
          (@@_carrierwave_store_in_background ||= {})[:"#{column}"] = worker
        end
        def _define_shared_backgrounder_methods(mod, column, worker)
          before_save do
            send(:"set_#{column}_processing") if send(:"enqueue_#{column}_background_job?")
          end

          after_commit do
            send(:"enqueue_#{column}_background_job") if send(:"enqueue_#{column}_background_job?")
          end

          super

          class_eval  <<-RUBY, __FILE__, __LINE__ + 1
            def enqueue_#{column}_background_job
              if enqueue_#{column}_background_job?
                super
                @#{column}_changed = false
              end
            end

            def #{column}_updated?
              @#{column}_changed
            end

            def #{column}=(val)
              @#{column}_changed = true
              super
            end
          RUBY
        end
      end # ClassMethods

      module InstanceMethods
        def update_attribute(col, val)
          h = {}
          h[col] = val
          self.set(h)
          self.save(:columns=>[col], :validate=>false)
        end
      end
    end
  end
end

Sequel::Model.plugin :carrier_wave_backgrounder


text:
import { createStore, applyMiddleware, compose} from 'redux';
import thunkMiddleware from 'redux-thunk';
import rootReducer from '../reducers';
import DevTools from '../containers/DevTools';
import createLogger from 'redux-logger';
import { persistState} from 'redux-devtools';
import axios from 'axios';
import axiosMiddleware from 'redux-axios-middleware';
import WSClient from '../middleware/websocket';

const axiosClient = axios.create({
    baseURL: 'api',
    responseType: 'json'
});

const wsclient = new WSClient('ws://localhost:5000');

const debugMiddleware = [
    createLogger({
        collapsed: true
    })
];

    //applyMiddleware(thunkMiddleware,axiosMiddleware(axiosClient), ...debugMiddleware),
const enhancer = compose(
    applyMiddleware(thunkMiddleware,axiosMiddleware(axiosClient),wsclient.middleware),
    DevTools.instrument(),
    persistState(
      window.location.href.match(/[?&]debug_session=([^&]+)\b/)
    )
);

export default function configureStore(initialState) {
    const store = createStore(
        rootReducer,
        initialState,
        enhancer,
    );

    wsclient.setStore(store);

    if (module.hot) {
        // Enable Webpack hot module replacement for reducers
        module.hot.accept('../reducers', () => {
            const nextRootReducer = require('../reducers/index').default;
            store.replaceReducer(nextRootReducer);
        });
    }

    return store;
}


text:
package com.nesscomputing.cache.guava;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;

import java.util.concurrent.Callable;

import com.google.common.base.Function;
import com.google.common.base.Functions;
import com.google.common.cache.Cache;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.name.Named;

import org.junit.Test;
import org.junit.runner.RunWith;

import com.nesscomputing.cache.CacheModule;
import com.nesscomputing.config.Config;
import com.nesscomputing.config.ConfigModule;
import com.nesscomputing.lifecycle.junit.LifecycleRule;
import com.nesscomputing.lifecycle.junit.LifecycleRunner;
import com.nesscomputing.lifecycle.junit.LifecycleStatement;
import com.nesscomputing.testing.lessio.AllowDNSResolution;

@AllowDNSResolution
@RunWith(LifecycleRunner.class)
public class CustomSerializationGuavaCacheTest {

    @LifecycleRule
    public LifecycleStatement lifecycleRule = LifecycleStatement.defaultLifecycle();

    @Inject
    @Named("test-ns")
    Cache<String, Integer> myCache;

    Config config = Config.getFixedConfig("ness.cache.test", "JVM");

    @Test
    public void testConversions() throws Exception {

        Function<Integer, byte[]> intSerializer = new Function<Integer, byte[]>() {
            @Override
            public byte[] apply(Integer input) {
                return new byte[] {input.byteValue()};
            }
        };

        Function<byte[], Integer> intDeserializer = new Function<byte[], Integer>() {
            @Override
            public Integer apply(byte[] input) {
                return (int) input[0];
            }
        };

        Guice.createInjector(
                lifecycleRule.getLifecycleModule(),
                new ConfigModule(config),
                new CacheModule("test"),
                NessGuavaCaches.newModuleBuilder("test", "test-ns", String.class, Integer.class)
                    .withKeySerializer(Functions.toStringFunction())
                    .withValueSerializer(intSerializer, intDeserializer)
                    .build()
            ).injectMembers(this);

        assertNull(myCache.getIfPresent("foo"));

        assertEquals(3, (int) myCache.get("foo", new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                return 3;
            }
        }));

        assertEquals(3, (int) myCache.get("foo", new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                throw new UnsupportedOperationException();
            }
        }));
    }
}


text:
// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Alessandro Tasora, Radu Serban
// =============================================================================

#include "chrono/motion_functions/ChFunction_Matlab.h"

namespace chrono {

// Register into the object factory, to enable run-time dynamic creation and persistence
CH_FACTORY_REGISTER(ChFunction_Matlab)

ChFunction_Matlab::ChFunction_Matlab() {
    strcpy(this->mat_command, "x*2+x^2");
}

ChFunction_Matlab::ChFunction_Matlab(const ChFunction_Matlab& other) {
    strcpy(this->mat_command, other.mat_command);
}

double ChFunction_Matlab::Get_y(double x) const {
    double ret = 0;

#ifdef CH_MATLAB
    char m_eval_command[CHF_MATLAB_STRING_LEN + 20];

    // no function: shortcut!
    if (*this->mat_command == NULL)
        return 0.0;

    // set string as "x=[x];ans=[mat_command]"
    sprintf(m_eval_command, "x=%g;ans=%s;", x, this->mat_command);

    // EVAL string, retrieving y = "ans"
    ret = CHGLOBALS().Mat_Eng_Eval(m_eval_command);
#endif

    return ret;
}

double ChFunction_Matlab::Get_y_dx(double x) const {
    return ((Get_y(x + BDF_STEP_HIGH) - Get_y(x)) / BDF_STEP_HIGH);
}

double ChFunction_Matlab::Get_y_dxdx(double x) const {
    return ((Get_y_dx(x + BDF_STEP_HIGH) - Get_y_dx(x)) / BDF_STEP_HIGH);
}

void ChFunction_Matlab::ArchiveOUT(ChArchiveOut& marchive) {
    // version number
    marchive.VersionWrite<ChFunction_Matlab>();
    // serialize parent class
    ChFunction::ArchiveOUT(marchive);
    // serialize all member data:
    marchive << CHNVP(mat_command);
}

void ChFunction_Matlab::ArchiveIN(ChArchiveIn& marchive) {
    // version number
    /*int version =*/ marchive.VersionRead<ChFunction_Matlab>();
    // deserialize parent class
    ChFunction::ArchiveIN(marchive);
    // stream in all member data:
    marchive >> CHNVP(mat_command);
}

}  // end namespace chrono


text:
<?php defined('APPPATH') or exit('No direct script access allowed');

class TemplateData_ResourcesIterator extends TemplateData_DataIterator {

    public function __construct($data = NULL)
    {
        if ( $data && is_array($data) )
        {
            $this->data = $data;
        }
        elseif ( is_string($data) )
        {
            $this->path = $data;
        }
    }

    protected function filter_under( $data, $path )
    {
        if ( $path )
        {
            $result = array();
            $path = '/'.trim($path,'/');

            foreach( $data as $item_path => $item )
            {
                if ( strpos( $item_path, $path ) === 0 )
                {
                    $result[$item_path] = $item;
                }
            }
            return $result;
        }
        return $data;
    }

    protected function filter_sort( $data, $dir )
    {
        if ( strtolower($dir) == 'desc' ) ksort($data);
        return $data;
    }

    protected function get_data()
    {
        $iterator = new RecursiveDirectoryIterator($this->path);
        $data = $this->arrayize($iterator);
        krsort($data);
        return $this->filter($data);
    }

    protected function arrayize(RecursiveDirectoryIterator $iterator)
    {
        $files = new RecursiveIteratorIterator($iterator);
        $array = array();

        foreach( $files as $file )
        {
            $type = str_replace(RESOURCESPATH, '', $this->path );

            $path = str_replace($this->path, '', $file->getPathname());

            $info = pathinfo($path);
            $segments = explode( DS, $path );

            $current = array(
                'slug'          => $info['filename'],
                'path'          => $type.$info['dirname'],
                'groups'        => $segments,
            );

            $uripath = str_replace('//','/',$info['dirname'].'/'.$info['filename']);

            $array[$uripath] = new Templatedata_Item( 'resource', $type.$uripath, $current );
        }

        return $array;
    }
}

/* End of file classes/templatedata/resourcesiterator.php */


text:
/* Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.flowable.cmmn.engine.impl.delegate;

import java.util.List;

import org.flowable.cmmn.api.delegate.DelegatePlanItemInstance;
import org.flowable.cmmn.api.delegate.PlanItemFutureJavaDelegate;
import org.flowable.cmmn.api.delegate.PlanItemJavaDelegate;
import org.flowable.cmmn.api.delegate.PlanItemVariableAggregator;
import org.flowable.cmmn.api.delegate.PlanItemVariableAggregatorContext;
import org.flowable.cmmn.api.listener.CaseInstanceLifecycleListener;
import org.flowable.cmmn.api.listener.PlanItemInstanceLifecycleListener;
import org.flowable.cmmn.api.runtime.CaseInstance;
import org.flowable.cmmn.engine.impl.behavior.CmmnActivityBehavior;
import org.flowable.cmmn.engine.impl.behavior.CmmnTriggerableActivityBehavior;
import org.flowable.cmmn.engine.impl.behavior.impl.PlanItemFutureJavaDelegateActivityBehavior;
import org.flowable.cmmn.engine.impl.behavior.impl.PlanItemJavaDelegateActivityBehavior;
import org.flowable.cmmn.engine.impl.util.CommandContextUtil;
import org.flowable.cmmn.model.FieldExtension;
import org.flowable.common.engine.api.FlowableIllegalArgumentException;
import org.flowable.common.engine.impl.el.ExpressionManager;
import org.flowable.common.engine.impl.el.FixedValue;
import org.flowable.common.engine.impl.util.ReflectUtil;
import org.flowable.task.service.delegate.DelegateTask;
import org.flowable.task.service.delegate.TaskListener;
import org.flowable.variable.api.persistence.entity.VariableInstance;

/**
 * @author Joram Barrez
 */
public class CmmnClassDelegate implements CmmnTriggerableActivityBehavior, TaskListener, PlanItemInstanceLifecycleListener, CaseInstanceLifecycleListener,
        PlanItemVariableAggregator {

    protected String sourceState;
    protected String targetState;
    protected String className;
    protected List<FieldExtension> fieldExtensions;
    protected CmmnActivityBehavior activityBehaviorInstance;

    public CmmnClassDelegate(String className, List<FieldExtension> fieldExtensions) {
        this.className = className;
        this.fieldExtensions = fieldExtensions;
    }

    @Override
    public void execute(DelegatePlanItemInstance planItemInstance) {
        if (activityBehaviorInstance == null) {
            activityBehaviorInstance = getCmmnActivityBehavior(className);
        }
        activityBehaviorInstance.execute(planItemInstance);
    }

    @Override
    public void trigger(DelegatePlanItemInstance planItemInstance) {
        if (activityBehaviorInstance == null) {
            activityBehaviorInstance = getCmmnActivityBehavior(className);
        }

        if (!(activityBehaviorInstance instanceof CmmnTriggerableActivityBehavior)) {
            throw new FlowableIllegalArgumentException(className + " does not implement the "
                + CmmnTriggerableActivityBehavior.class + " interface");
        }

        ((CmmnTriggerableActivityBehavior) activityBehaviorInstance).trigger(planItemInstance);
    }

    protected CmmnActivityBehavior getCmmnActivityBehavior(String className) {
        Object instance = instantiate(className);
        applyFieldExtensions(fieldExtensions, instance, false);

        if (instance instanceof PlanItemJavaDelegate) {
            return new PlanItemJavaDelegateActivityBehavior((PlanItemJavaDelegate) instance);

        } else if (instance instanceof PlanItemFutureJavaDelegate) {
            return new PlanItemFutureJavaDelegateActivityBehavior((PlanItemFutureJavaDelegate) instance);

        } else if (instance instanceof CmmnTriggerableActivityBehavior) {
            return (CmmnTriggerableActivityBehavior) instance;

        } else if (instance instanceof CmmnActivityBehavior) {
            return (CmmnActivityBehavior) instance;

        } else {
            throw new FlowableIllegalArgumentException(className + " does not implement the "
                    + CmmnActivityBehavior.class + " nor the " + PlanItemJavaDelegate.class + " interface");

        }
    }

    @Override
    public void notify(DelegateTask delegateTask) {
        TaskListener taskListenerInstance = getTaskListenerInstance(delegateTask);
        taskListenerInstance.notify(delegateTask);
    }

    protected TaskListener getTaskListenerInstance(DelegateTask delegateTask) {
        Object delegateInstance = instantiate(className);
        applyFieldExtensions(fieldExtensions, delegateInstance, false);

        if (delegateInstance instanceof TaskListener) {
            return (TaskListener) delegateInstance;
        } else {
            throw new FlowableIllegalArgumentException(delegateInstance.getClass().getName() + " doesn't implement " + TaskListener.class);
        }
    }

    @Override
    public void stateChanged(DelegatePlanItemInstance planItemInstance, String oldState, String newState) {
        PlanItemInstanceLifecycleListener planItemLifeCycleListenerInstance = getPlanItemLifeCycleListenerInstance();
        planItemLifeCycleListenerInstance.stateChanged(planItemInstance, oldState, newState);
    }

    @Override
    public void stateChanged(CaseInstance caseInstance, String oldState, String newState) {
        CaseInstanceLifecycleListener caseLifeCycleListenerInstance = getCaseLifeCycleListenerInstance();
        caseLifeCycleListenerInstance.stateChanged(caseInstance, oldState, newState);
    }

    protected PlanItemInstanceLifecycleListener getPlanItemLifeCycleListenerInstance() {
        Object delegateInstance = instantiate(className);
        applyFieldExtensions(fieldExtensions, delegateInstance, false);
        if (delegateInstance instanceof PlanItemInstanceLifecycleListener) {
            return (PlanItemInstanceLifecycleListener) delegateInstance;
        } else {
            throw new FlowableIllegalArgumentException(delegateInstance.getClass().getName() + " doesn't implement " + PlanItemInstanceLifecycleListener.class);
        }
    }

    protected CaseInstanceLifecycleListener getCaseLifeCycleListenerInstance() {
        Object delegateInstance = instantiate(className);
        applyFieldExtensions(fieldExtensions, delegateInstance, false);
        if (delegateInstance instanceof CaseInstanceLifecycleListener) {
            return (CaseInstanceLifecycleListener) delegateInstance;
        } else {
            throw new FlowableIllegalArgumentException(delegateInstance.getClass().getName() + " doesn't implement " + CaseInstanceLifecycleListener.class);
        }
    }

    @Override
    public Object aggregateSingleVariable(DelegatePlanItemInstance planItemInstance, PlanItemVariableAggregatorContext context) {
        return getPlanItemVariableAggregator().aggregateSingleVariable(planItemInstance, context);
    }

    @Override
    public Object aggregateMultiVariables(DelegatePlanItemInstance planItemInstance, List<? extends VariableInstance> instances, PlanItemVariableAggregatorContext context) {
        return getPlanItemVariableAggregator().aggregateMultiVariables(planItemInstance, instances, context);
    }

    protected PlanItemVariableAggregator getPlanItemVariableAggregator() {
        Object delegateInstance = instantiate(className);
        applyFieldExtensions(fieldExtensions, delegateInstance, false);
        if (delegateInstance instanceof PlanItemVariableAggregator) {
            return (PlanItemVariableAggregator) delegateInstance;
        } else {
            throw new FlowableIllegalArgumentException(delegateInstance.getClass().getName() + " doesn't implement " + PlanItemVariableAggregator.class);
        }
    }

    protected Object instantiate(String className) {
        return ReflectUtil.instantiate(className);
    }

    public static void applyFieldExtensions(List<FieldExtension> fieldExtensions, Object target, boolean throwExceptionOnMissingField) {
        if (fieldExtensions != null) {
            for (FieldExtension fieldExtension : fieldExtensions) {
                applyFieldExtension(fieldExtension, target, throwExceptionOnMissingField);
            }
        }
    }

    protected static void applyFieldExtension(FieldExtension fieldExtension, Object target, boolean throwExceptionOnMissingField) {
        Object value = null;
        if (fieldExtension.getExpression() != null) {
            ExpressionManager expressionManager = CommandContextUtil.getCmmnEngineConfiguration().getExpressionManager();
            value = expressionManager.createExpression(fieldExtension.getExpression());
        } else {
            value = new FixedValue(fieldExtension.getStringValue());
        }

        ReflectUtil.invokeSetterOrField(target, fieldExtension.getFieldName(), value, throwExceptionOnMissingField);
    }

    @Override
    public String getSourceState() {
        return sourceState;
    }
    public void setSourceState(String sourceState) {
        this.sourceState = sourceState;
    }
    @Override
    public String getTargetState() {
        return targetState;
    }
    public void setTargetState(String targetState) {
        this.targetState = targetState;
    }
    public String getClassName() {
        return className;
    }
    public void setClassName(String className) {
        this.className = className;
    }
    public List<FieldExtension> getFieldExtensions() {
        return fieldExtensions;
    }
    public void setFieldExtensions(List<FieldExtension> fieldExtensions) {
        this.fieldExtensions = fieldExtensions;
    }
    public CmmnActivityBehavior getActivityBehaviorInstance() {
        return activityBehaviorInstance;
    }
    public void setActivityBehaviorInstance(CmmnActivityBehavior activityBehaviorInstance) {
        this.activityBehaviorInstance = activityBehaviorInstance;
    }
}


text:
var express = require('express'),
    app = express(),
    bodyParser = require('body-parser'),
    cookieParser = require('cookie-parser'),
    http = require('http').Server(app),
    io = require('socket.io').listen(http),
    fs = require('fs');

http.listen(process.env.PORT || 8000);

app.use(function(req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'GET, OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Content-Type');
  return next();
});

var players = [],
    correctStats = {},
    commands = {
        READY: 'ready'
    },
    levels = {
        0: ['color', 'red'],
        1: ['display', 'block'],
        2: ['white-space', 'nowrap'],
        3: ['border-collapse', 'collapse'],
        9: ['w', 'e']
    }
    level = 1;

function testSubmission(code) {
    // Empty String
    if (!code) return false;

    // Trim ending semicolon
    code = code.trim().replace(/;$/, '');

    var split = code.split(':').map(function (s) {
        return s.toLowerCase().trim();
    });

    // Not current syntax
    if (split.length < 2) return false;
    console.log('Check ', split, levels[level])

    // Match prop with prop and value with value.
    return split[0] === levels[level][0] && split[1] === levels[level][1]
};

app.use(cookieParser());
app.use(express.static(__dirname + '/public'));

// Required for parsing POST request data.
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: true
}));

function resetCorrectStats() {
    correctStats = {count: 0};
}

var broadcastStats = function() {};
var broadcastSubmission = function() {};

resetCorrectStats();

/////////////////
// POST endpoints
// //////////////
app.post('/code', function (req, res) {
    var code = req.body.code;
    console.log(players.length, 'Code from', req.ip, ' ', code);

    // res.send({success: 0, data: 'Syntax error in your code'});

    var passed = true;

    // Test submitted code.
    if (!testSubmission(code)) {
        passed = false;
        res.send({success: 0, data: 'Wrong Answer. Try again.'});
    }

    broadcastSubmission(code);

    if (passed) {
        var obj = {success: 1, data: correctStats[req.ip] ? 'You already passed this level. Relax.' : ''};

        res.send(obj);

        // CHeck is this IP has not already passed the current test.
        if (!correctStats[req.ip]) {
            correctStats.count++;
            correctStats[req.ip] = 1;
            broadcastStats();
        }
    }
});

///////////////////
// SOCKET listeners
///////////////////

io.sockets.on('connection', function (socket) {
    socket.emit('welcome', {msg: 'Hi, there! Welcome.', id: socket.id});

    var ip = socket.handshake.address,
        cookie = socket.handshake.headers.cookie;

    // If this is a connection from an admini
    if (cookie && cookie.indexOf(process.env.GAME_ADMIN_COOKIE || 'admin') !== -1) {
        console.log('Admin joined.')

        broadcastStats = function () {
            socket.emit('update-stats', {total: players.length - 1, correct: correctStats.count});
        }

        broadcastSubmission = function (code) {
            // console.log('Broadcasted submission to ',socket.id, ' ',  code)
            socket.emit('submission', code);
        }

        socket.on('set-level', function (l) {
            console.log('Reset level: ', l)
            level = parseInt(l, 10);
            resetCorrectStats();
            broadcastStats();
        });
    }

    socket.on('disconnect', function () {
        for (var i = players.length; i--;) {
            if (players[i] === socket) {
                console.log('player disconnect: ', ip)
                players.splice(i, 1);
                break;
            }
        }

        if (correctStats[ip]) {
            correctStats.count--;
            delete correctStats[ip];
        }

        if (socket.data) {
            broadcastStats();
        }
    });

    socket.on('msg', function (msg) {
        if (commands[msg ? msg.toUpperCase() : '']) {
            // we got a predefined command
            return;
        }

        socket.broadcast.emit('msg', '<b>' + socket.data.name + '</b>: ' + msg);
    });

    socket.on('set-data', function (data) {
        data.score = 0;
        socket.data =  data;
        socket.ip = ip;

        // save player in list
        players.push(socket);
        console.log('player joined: ', data && data.name);

        broadcastStats();
    });

    socket.on('update-data', function (data) {
        if (!socket.data) return;
        delete data.id;
        _.extend(socket.data, data);
    });
});

_ = {};
_.extend = function (obj) {
    [].slice.call(arguments, 1).forEach (function (source) {
        if (source) {
            for (var prop in source) {
                obj[prop] = source[prop];
            }
        }
    });
    return obj;
};


text:
package reprovide

import (
	"context"

	merkledag "github.com/ipfs/go-ipfs/merkledag"
	pin "github.com/ipfs/go-ipfs/pin"

	blocks "gx/ipfs/QmaG4DZ4JaqEfvPWt5nPPgoTzhc1tr1T3f4Nu9Jpdm8ymY/go-ipfs-blockstore"
	cid "gx/ipfs/QmcZfnkapfECQGcLZaf9B79NRg7cRa9EnZh4LSbkCzwNvY/go-cid"
	ipld "gx/ipfs/Qme5bWv7wtjUNGsK2BNGVUFPKiuxWrsqrtvYwCLRw8YFES/go-ipld-format"
)

// NewBlockstoreProvider returns key provider using bstore.AllKeysChan
func NewBlockstoreProvider(bstore blocks.Blockstore) KeyChanFunc {
	return func(ctx context.Context) (<-chan *cid.Cid, error) {
		return bstore.AllKeysChan(ctx)
	}
}

// NewPinnedProvider returns provider supplying pinned keys
func NewPinnedProvider(pinning pin.Pinner, dag ipld.DAGService, onlyRoots bool) KeyChanFunc {
	return func(ctx context.Context) (<-chan *cid.Cid, error) {
		set, err := pinSet(ctx, pinning, dag, onlyRoots)
		if err != nil {
			return nil, err
		}

		outCh := make(chan *cid.Cid)
		go func() {
			defer close(outCh)
			for c := range set.new {
				select {
				case <-ctx.Done():
					return
				case outCh <- c:
				}
			}

		}()

		return outCh, nil
	}
}

func pinSet(ctx context.Context, pinning pin.Pinner, dag ipld.DAGService, onlyRoots bool) (*streamingSet, error) {
	set := newStreamingSet()

	go func() {
		defer close(set.new)

		for _, key := range pinning.DirectKeys() {
			set.add(key)
		}

		for _, key := range pinning.RecursiveKeys() {
			set.add(key)

			if !onlyRoots {
				err := merkledag.EnumerateChildren(ctx, merkledag.GetLinksWithDAG(dag), key, set.add)
				if err != nil {
					log.Errorf("reprovide indirect pins: %s", err)
					return
				}
			}
		}
	}()

	return set, nil
}

type streamingSet struct {
	set *cid.Set
	new chan *cid.Cid
}

// NewSet initializes and returns a new Set.
func newStreamingSet() *streamingSet {
	return &streamingSet{
		set: cid.NewSet(),
		new: make(chan *cid.Cid),
	}
}

// add adds a Cid to the set only if it is
// not in it already.
func (s *streamingSet) add(c *cid.Cid) bool {
	if s.set.Visit(c) {
		s.new <- c
		return true
	}

	return false
}


text:
import argparse
import os.path
import re
import signal
import string
import subprocess
import sys
import time

#########################
### UTILITY FUNCTIONS ###
#########################
def chdir(dir, verbose = False):
    os.chdir(dir)
    if verbose:
    	print "Executing chdir to %s" % dir

def execCmd(cmd, verbose = False):
    if verbose:
    	print "Executing command: %s" % sanitizeString(cmd)

    # Use Popen instead of subprocess.check_output as latter only exists in Python 2.7 onwards
    # output = subprocess.check_output(cmd, shell=True, stderr=subprocess.STDOUT)
    output = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[0]

    # print "For output got: %s" % output
    return output

def sanitizeString(input):
    return input.replace("\r", r"\r")

################
### OSIMCTRL ###
################
class OSimCtrl:
    Commands = {
      "start" : { "help" : "Start this component in a screen process." },
      "stop" : { "help" : "Stop this component." },
      "restart" : { "help" : "Stop and start this component." },
      "attach" : { "help" : "Attach to screen process for this component if running." },
      "status" : { "help" : "Status of this component." },
    }

    @property
    def pollingTimeMax(self):
        return self._pollingTimeMax

    @pollingTimeMax.setter
    def pollingTimeMax(self, value):
        if value < 0:
            raise "Max polling time %s invalid as one cannot set a value less than 0" % value

        self._pollingTimeMax = value

    def __init__(self, binaryPath, screenPath, switches, monoPath, componentName, screenName):
        self._binaryPath = binaryPath
        self._screenPath = screenPath
        self._switches = switches
        self._monoPath = monoPath
        self._componentName = componentName
        self._screenName = screenName
        self._pollingTimeMax = 300
        self._pollingInterval = 1
        self._pollingNotificationInterval = 5

    def execCommand(self, command, opts):
        """Execute a command.  Returns True on success, False otherwise."""
        if command == "attach":
            self.attachToComponent(opts)
        elif command == "status":
            self.getComponentStatus(opts)
        elif command == "start":
            self.startComponent(opts)
        elif command == "stop":
            self.stopComponent(opts)
        elif command == "restart":
            self.restartComponent(opts)
        else:
            print "Command %s not recognized" % command

    def attachToComponent(self, opts):
        """Attach to a screen running the component.  Returns True on success, False otherwise."""
        screen = self.findScreen(opts.verbose)

        if screen == None:
            print "Did not find screen named %s for attach" % self._screenName
            return False
        else:
            print "Found screen %s" % screen
            execCmd("%s -x %s" % (self._screenPath, screen))
            return True

    def getComponentStatus(self, opts):
        """Get the status of the given component.  Returns True if active, False if inactive or problem finding."""

        # We'll check screen even if we found PID so that we can get screen information
        screen = self.findScreen(opts.verbose)

        if screen == None:
            print "Did not find screen named %s" % self._screenName
        else:
            print "Found screen %s" % screen

        if opts.verbose:
            print "OpenSimulator path: %s" % self._binaryPath

        if screen != None:
            print "Status: ### Active ###"
            return True
        else:
            print "Status: ### Inactive ###"
            return False

    def startComponent(self, opts):
        """Start the given component.  Returns True on success, False otherwise"""
        screen = self.findScreen(opts.verbose)

        if screen != None:
            print >> sys.stderr, "Screen session %s already started." % (screen)
            return False

        chdir(self._binaryPath, opts.verbose)

        cmd = "%s %s.exe %s" % (self._monoPath, self._componentName, self._switches)

        if opts.autorestart:
            cmd = "bash -c 'set carryon=true; trap \"carryon=false\" SIGUSR1; while $carryon; do %s; done'" % (cmd)

        execCmd("%s -S %s -d -m %s" % (self._screenPath, self._screenName, cmd), opts.verbose)

        screen = self.findScreen(opts.verbose)
        if screen != None:
            print "%s starting in screen instance %s" % (self._componentName, screen)
        else:
            print >> sys.stderr, "ERROR: %s did not start." % self._componentName
            return False

        if opts.attach:
            execCmd("%s -x %s" % (self._screenPath, self._screenName))

        return True

    def stopComponent(self, opts):
        """Stop the given component.  Returns True on success, False if the component was already stopped or if there was a problem stopping."""
        screen = self.findScreen(opts.verbose)

        if screen == None:
            print >> sys.stderr, "No screen session named %s to stop" % self._screenName
            return False

        print "Stopping screen instance %s" % screen

        (autoRestartPid, comm) = execCmd("ps --ppid %s -o pid=,comm=" % screen.split(".")[0], opts.verbose).split()

        # Any uncaught signal sent to mono (including SIGUSR1) will kill it
        if comm == "bash":
            os.kill(int(autoRestartPid), signal.SIGUSR1)

        execCmd("%s -S %s -p 0 -X stuff quit$(printf \r)" % (self._screenPath, screen), opts.verbose)

        timeElapsed = 0

        while timeElapsed < self._pollingTimeMax:
            time.sleep(self._pollingInterval)
            timeElapsed += self._pollingInterval

            screen = self.findScreen(opts.verbose)

            if screen == None:
                print "Screen instance %s terminated." % self._screenName
                return True

            if timeElapsed % self._pollingNotificationInterval == 0:
                print "Waited %s seconds for screen named %s to terminate" % (timeElapsed, self._screenName)

        print >> sys.stderr, "Screen %s has not terminated after %s seconds.  Please investigate." % (self._screenName, self._pollingTimeMax)
        return False

    def restartComponent(self, opts):
        """Restart the given component.  Returns True on success, False otherwise."""
        self.stopComponent(opts)
        return self.startComponent(opts)

    def findScreen(self, verbose = False):
        """Try to find the screen instance for this component.  Returns the screen pid.name on success, None otherwise."""
        screenList = ""

        try:
            screenList = self.getScreenList(verbose)
        except subprocess.CalledProcessError as cpe:
            screenList = cpe.output

        #print "screenList: %s" % screenList
        # TODO: Need to improve this for screens with ( in their name
        res = re.search("\s+(\d+\.%s)\s+\(" % self._screenName, screenList)

        if not res == None:
            return res.group(1)
        else:
            return None

    def getScreenList(self, verbose = False):
        """Get a list of available screens directly from the screen command."""
        return execCmd("%s -list" % self._screenPath, verbose)

###############################
### COMMON SCRIPT FUNCTIONS ###
###############################
def main(binaryPath, screenPath, switches, monoPath, componentName, screenName):
    checkSanity(binaryPath, componentName)

    commands = OSimCtrl.Commands
    parser = argparse.ArgumentParser(formatter_class = argparse.RawTextHelpFormatter)

    parser.add_argument(
      'command',
      choices = commands.keys(),
      help = "\n".join(["%s - %s" % (k, v['help']) for k, v in commands.iteritems()]))

    parser.add_argument(
      '-r',
      '--autorestart',
      help = "Automatically restart component if it crashes.  With this option, it can only be stopped via the stop command, not by manually attaching to the screen and shutting down the component.",
      action = "store_true")

    parser.add_argument(
      '-a',
      '--attach',
      help = "Start and restart commmands will also attach to the started screen instance.",
      action = "store_true")

    parser.add_argument(
      '-v',
      '--verbose',
      help = "Be verbose about commands executed",
      action = "store_true")

    opts = parser.parse_args()

    osimctrl = OSimCtrl(binaryPath, screenPath, switches, monoPath, componentName, screenName)
    osimctrl.execCommand(opts.command, opts)

def checkSanity(binaryPath, componentName):
    """Check that the configured paths really exist"""

    path = "%s/%s.exe" % (binaryPath, componentName)

    if not os.path.exists(path):
        print >> sys.stderr, "config.binaryPath '%s' does not exist!  Aborting." % path
        sys.exit(1)


text:
<?php

namespace Illuminate\Cache;

use Illuminate\Contracts\Cache\Store;

class TagSet
{
    /**
     * The cache store implementation.
     *
     * @var \Illuminate\Contracts\Cache\Store
     */
    protected $store;

    /**
     * The tag names.
     *
     * @var array
     */
    protected $names = [];

    /**
     * Create a new TagSet instance.
     *
     * @param  \Illuminate\Contracts\Cache\Store  $store
     * @param  array  $names
     * @return void
     */
    public function __construct(Store $store, array $names = [])
    {
        $this->store = $store;
        $this->names = $names;
    }

    /**
     * Reset all tags in the set.
     *
     * @return void
     */
    public function reset()
    {
        array_walk($this->names, [$this, 'resetTag']);
    }

    /**
     * Reset the tag and return the new tag identifier.
     *
     * @param  string  $name
     * @return string
     */
    public function resetTag($name)
    {
        $this->store->forever($this->tagKey($name), $id = str_replace('.', '', uniqid('', true)));

        return $id;
    }

    /**
     * Flush all the tags in the set.
     *
     * @return void
     */
    public function flush()
    {
        array_walk($this->names, [$this, 'flushTag']);
    }

    /**
     * Flush the tag from the cache.
     *
     * @param  string  $name
     */
    public function flushTag($name)
    {
        $this->store->forget($this->tagKey($name));
    }

    /**
     * Get a unique namespace that changes when any of the tags are flushed.
     *
     * @return string
     */
    public function getNamespace()
    {
        return implode('|', $this->tagIds());
    }

    /**
     * Get an array of tag identifiers for all of the tags in the set.
     *
     * @return array
     */
    protected function tagIds()
    {
        return array_map([$this, 'tagId'], $this->names);
    }

    /**
     * Get the unique tag identifier for a given tag.
     *
     * @param  string  $name
     * @return string
     */
    public function tagId($name)
    {
        return $this->store->get($this->tagKey($name)) ?: $this->resetTag($name);
    }

    /**
     * Get the tag identifier key for a given tag.
     *
     * @param  string  $name
     * @return string
     */
    public function tagKey($name)
    {
        return 'tag:'.$name.':key';
    }

    /**
     * Get all of the tag names in the set.
     *
     * @return array
     */
    public function getNames()
    {
        return $this->names;
    }
}


text:
package org.apache.isis.core.metamodel.facets.value.integer;

import org.apache.isis.applib.adapters.EncoderDecoder;
import org.apache.isis.applib.adapters.Parser;
import org.apache.isis.core.commons.config.IsisConfiguration;
import org.apache.isis.core.metamodel.adapter.ObjectAdapter;
import org.apache.isis.core.metamodel.facetapi.FacetHolder;
import org.apache.isis.core.metamodel.facets.properties.defaults.PropertyDefaultFacet;
import org.apache.isis.core.metamodel.facets.object.value.vsp.ValueSemanticsProviderContext;

public class IntPrimitiveValueSemanticsProvider extends IntValueSemanticsProviderAbstract implements PropertyDefaultFacet {

    /**
     * Required because implementation of {@link Parser} and
     * {@link EncoderDecoder}.
     */
    public IntPrimitiveValueSemanticsProvider() {
        this(null, null, null);
    }

    public IntPrimitiveValueSemanticsProvider(final FacetHolder holder, final IsisConfiguration configuration, final ValueSemanticsProviderContext context) {
        super(holder, int.class, configuration, context);
    }

    // //////////////////////////////////////////////////////////////////
    // PropertyDefaultFacet
    // //////////////////////////////////////////////////////////////////

    @Override
    public ObjectAdapter getDefault(final ObjectAdapter inObject) {
        return createAdapter(int.class, Integer.valueOf(0));
    }

}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

		<title>Attach to input</title>
		<meta http-equiv="content-type" content="text/html; charset=utf-8" />
		<meta name="featured" content="yes"><meta name="title" content="Samples" />
		<meta name="keywords" content="" />
		<meta name="description" content="" />
		<link rel="icon" href="../common/favicon.ico" type="image/x-icon" />
		<link rel="shortcut icon" href="../common/favicon.ico" type="image/x-icon" />
		<link rel="stylesheet" href="../common/css/style.css" type="text/css" media="screen" />

DHTMLX Docs & Samples Explorer

                <form action="http://docs.dhtmlx.com/doku.php" accept-charset="utf-8" id="dw__search">
<input type="hidden" name="do" value="search" /><input type="text" id="qsearch__in" accesskey="f" name="id" title="Search" /><input class="button" type="submit" value="">

</form>

                All components

                dhtmlxCalendar

                Init

Attach to input

                View page source

            <link rel="stylesheet" type="text/css" href="../../codebase/dhtmlxcalendar.css">
	<link rel="stylesheet" type="text/css" href="../../codebase/skins/dhtmlxcalendar_dhx_skyblue.css">

		<input type="text" id="calendar">
		<input type="text" id="calendar2">
		<input type="text" id="calendar3">

Source

<link rel="stylesheet" type="text/css" href="../../codebase/dhtmlxcalendar.css">
    <link rel="stylesheet" type="text/css" href="../../codebase/skins/dhtmlxcalendar_dhx_skyblue.css">
    <script src="../../codebase/dhtmlxcalendar.js"></script>
    <style>
        #calendar,
        #calendar2,
        #calendar3 {
            border: 1px solid #909090;
            font-family: Tahoma;
            font-size: 12px;
        }
    </style>
    <script>

var myCalendar;
function doOnLoad() {
    myCalendar = new dhtmlXCalendarObject(["calendar", "calendar2", "calendar3"]);
}

</script>

    <div style="position:relative;height:280px;">
        <input type="text" id="calendar">
        <input type="text" id="calendar2">
        <input type="text" id="calendar3">
    </div>

Copyright © 1998-2012 DHTMLX LTD.
All rights reserved.


text:
package com.laytonsmith.abstraction.enums;

import com.laytonsmith.annotations.MEnum;

@MEnum("RabbitType")
public enum MCRabbitType {
	BROWN,
	WHITE,
	BLACK,
	BLACK_AND_WHITE,
	GOLD,
	SALT_AND_PEPPER,
	THE_KILLER_BUNNY
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="vertical">

    <Button
        android:id="@+id/admob_mediation"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_margin="10dp"
        android:text="AdMob"/>

    <Button
        android:id="@+id/native_recyclerview_mopub"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_margin="10dp"
        android:text="MoPub"/>

</LinearLayout>


text:
package com.amazonaws.services.clouddirectory.model;

import java.io.Serializable;
import javax.annotation.Generated;

import com.amazonaws.AmazonWebServiceRequest;

/**
 *
 * @see AWS API
 *      Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class AttachPolicyRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {

    /**
     *

     * The Amazon Resource Name (ARN) that is associated with the Directory where both objects reside. For more
     * information, see arns.
     *

     */
    private String directoryArn;
    /**
     *

     * The reference that is associated with the policy object.
     *

     */
    private ObjectReference policyReference;
    /**
     *

     * The reference that identifies the object to which the policy will be attached.
     *

     */
    private ObjectReference objectReference;

    /**
     *

     * The Amazon Resource Name (ARN) that is associated with the Directory where both objects reside. For more
     * information, see arns.
     *

     *
     * @param directoryArn
     *        The Amazon Resource Name (ARN) that is associated with the Directory where both objects reside. For
     *        more information, see arns.
     */

    public void setDirectoryArn(String directoryArn) {
        this.directoryArn = directoryArn;
    }

    /**
     *

     * The Amazon Resource Name (ARN) that is associated with the Directory where both objects reside. For more
     * information, see arns.
     *

     *
     * @return The Amazon Resource Name (ARN) that is associated with the Directory where both objects reside.
     *         For more information, see arns.
     */

    public String getDirectoryArn() {
        return this.directoryArn;
    }

    /**
     *

     * The Amazon Resource Name (ARN) that is associated with the Directory where both objects reside. For more
     * information, see arns.
     *

     *
     * @param directoryArn
     *        The Amazon Resource Name (ARN) that is associated with the Directory where both objects reside. For
     *        more information, see arns.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public AttachPolicyRequest withDirectoryArn(String directoryArn) {
        setDirectoryArn(directoryArn);
        return this;
    }

    /**
     *

     * The reference that is associated with the policy object.
     *

     *
     * @param policyReference
     *        The reference that is associated with the policy object.
     */

    public void setPolicyReference(ObjectReference policyReference) {
        this.policyReference = policyReference;
    }

    /**
     *

     * The reference that is associated with the policy object.
     *

     *
     * @return The reference that is associated with the policy object.
     */

    public ObjectReference getPolicyReference() {
        return this.policyReference;
    }

    /**
     *

     * The reference that is associated with the policy object.
     *

     *
     * @param policyReference
     *        The reference that is associated with the policy object.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public AttachPolicyRequest withPolicyReference(ObjectReference policyReference) {
        setPolicyReference(policyReference);
        return this;
    }

    /**
     *

     * The reference that identifies the object to which the policy will be attached.
     *

     *
     * @param objectReference
     *        The reference that identifies the object to which the policy will be attached.
     */

    public void setObjectReference(ObjectReference objectReference) {
        this.objectReference = objectReference;
    }

    /**
     *

     * The reference that identifies the object to which the policy will be attached.
     *

     *
     * @return The reference that identifies the object to which the policy will be attached.
     */

    public ObjectReference getObjectReference() {
        return this.objectReference;
    }

    /**
     *

     * The reference that identifies the object to which the policy will be attached.
     *

     *
     * @param objectReference
     *        The reference that identifies the object to which the policy will be attached.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public AttachPolicyRequest withObjectReference(ObjectReference objectReference) {
        setObjectReference(objectReference);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getDirectoryArn() != null)
            sb.append("DirectoryArn: ").append(getDirectoryArn()).append(",");
        if (getPolicyReference() != null)
            sb.append("PolicyReference: ").append(getPolicyReference()).append(",");
        if (getObjectReference() != null)
            sb.append("ObjectReference: ").append(getObjectReference());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof AttachPolicyRequest == false)
            return false;
        AttachPolicyRequest other = (AttachPolicyRequest) obj;
        if (other.getDirectoryArn() == null ^ this.getDirectoryArn() == null)
            return false;
        if (other.getDirectoryArn() != null && other.getDirectoryArn().equals(this.getDirectoryArn()) == false)
            return false;
        if (other.getPolicyReference() == null ^ this.getPolicyReference() == null)
            return false;
        if (other.getPolicyReference() != null && other.getPolicyReference().equals(this.getPolicyReference()) == false)
            return false;
        if (other.getObjectReference() == null ^ this.getObjectReference() == null)
            return false;
        if (other.getObjectReference() != null && other.getObjectReference().equals(this.getObjectReference()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getDirectoryArn() == null) ? 0 : getDirectoryArn().hashCode());
        hashCode = prime * hashCode + ((getPolicyReference() == null) ? 0 : getPolicyReference().hashCode());
        hashCode = prime * hashCode + ((getObjectReference() == null) ? 0 : getObjectReference().hashCode());
        return hashCode;
    }

    @Override
    public AttachPolicyRequest clone() {
        return (AttachPolicyRequest) super.clone();
    }

}


text:
---
title: "Diameter of Binary Tree"
description: "Some description ..."
authors: ["lek-tin"]
tags: ["leetcode", "dfs", "binary-tree"]
categories: ["algorithm"]
date: 2019-03-09T18:50:51-08:00
lastmod: 2020-04-11T18:50:51-08:00
draft: false
archive: false
---

Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.

### Example

```
Given a binary tree
          1
         / \
        2   3
       / \
      4   5
Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].
```

### Solution

```python
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def diameterOfBinaryTree(self, root: TreeNode) -> int:
        self.max_diamter = 0
        self.dfs(root)
        return self.max_diamter

    def dfs(self, root):
        if not root:
            return -1

        left_height = self.dfs(root.left) + 1
        right_height = self.dfs(root.right) + 1
        combined_len = left_height + right_height

        if combined_len > self.max_diamter:
            self.max_diamter = combined_len

        return left_height if left_height > right_height else right_height
```

### Solution

```java
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    private int maxDiameter = 0;

    public int diameterOfBinaryTree(TreeNode root) {
        if (root == null) return 0;

        helper(root);

        return maxDiameter;
    }

    private int helper(TreeNode node) {
        if (node == null) return - 1;

        int leftHeight = helper(node.left) + 1;
        int rightHeight = helper(node.right) + 1;
        int len = leftHeight + rightHeight;
        if (len > maxDiameter) {
            maxDiameter = len;
        }

        return leftHeight > rightHeight ? leftHeight : rightHeight;
    }
}
```

#### Note

The length of path between two nodes is represented by the number of edges between them.


text:
package org.hsqldb.persist;

import org.hsqldb.lib.Storage;

import java.io.IOException;

import org.hsqldb.Database;

public interface ScaledRAInterface extends Storage {

    boolean canAccess(int length);

    boolean canSeek(long position);

    Database getDatabase();
}


text:
package fs

// Validate returns any errors encountered when validating it's elements
func (f FsPathS) Validate() error {
	er := new(Errors)
	var err error
	for i := range f {
		_, err = f[i].Stat()
		er.err(err)
	}
	return er.got()
}

// Accessible returns any errors encountered when accessing it's elements
func (f FsPathS) Accessible() error {
	er := new(Errors)
	for i := range f {
		er.err(f[i].Accessible())
	}
	return er.got()
}


text:
package ghostdriver;

import java.io.File;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.FileOutputStream;
import java.io.IOException;

import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import static org.junit.Assert.assertEquals;

public class FileUploadTest extends BaseTest {
    private static final String LOREM_IPSUM_TEXT = "lorem ipsum dolor sit amet";
    private static final String FILE_HTML = "<div>" + LOREM_IPSUM_TEXT + "</div>";

    @Test
    public void checkFileUploadCompletes() throws IOException {
        WebDriver d = getDriver();

        // Create the test file for uploading
        File testFile = File.createTempFile("webdriver", "tmp");
        testFile.deleteOnExit();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
            new FileOutputStream(testFile.getAbsolutePath()), "utf-8"));
        writer.write(FILE_HTML);
        writer.close();

        d.get("http://ci.seleniumhq.org:2310/common/upload.html");
        d.findElement(By.id("upload")).sendKeys(testFile.getAbsolutePath());
        d.findElement(By.id("go")).submit();

        // Uploading files across a network may take a while, even if they're really small.
        // Wait for the loading label to disappear.
        WebDriverWait wait = new WebDriverWait(d, 30);
        wait.until(ExpectedConditions.invisibilityOfElementLocated(By.id("upload_label")));

        d.switchTo().frame("upload_target");

        wait = new WebDriverWait(d, 5);
        wait.until(ExpectedConditions.textToBePresentInElement(By.xpath("//body"), LOREM_IPSUM_TEXT));

        // Navigate after file upload to verify callbacks are properly released.
        d.get("http://www.google.com/");
    }

    @Test
    public void checkUploadingTheSameFileMultipleTimes() throws IOException {
        WebDriver d = getDriver();

        File file = File.createTempFile("test", "txt");
        file.deleteOnExit();

        d.get("http://ci.seleniumhq.org:2310/common/formPage.html");
        WebElement uploadElement = d.findElement(By.id("upload"));
        uploadElement.sendKeys(file.getAbsolutePath());
        uploadElement.submit();

        d.get("http://ci.seleniumhq.org:2310/common/formPage.html");
        uploadElement = d.findElement(By.id("upload"));
        uploadElement.sendKeys(file.getAbsolutePath());
        uploadElement.submit();
     }

    @Test
    public void checkOnChangeEventIsFiredOnFileUpload() throws IOException {
        WebDriver d = getDriver();

        d.get("http://ci.seleniumhq.org:2310/common/formPage.html");
        WebElement uploadElement = d.findElement(By.id("upload"));
        WebElement result = d.findElement(By.id("fileResults"));
        assertEquals("", result.getText());

        File file = File.createTempFile("test", "txt");
        file.deleteOnExit();

        uploadElement.sendKeys(file.getAbsolutePath());
        // Shift focus to something else because send key doesn't make the focus leave
        d.findElement(By.id("id-name1")).click();

        assertEquals("changed", result.getText());
     }
}