/**
* @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 FixedToCamera component enables a Game Object to be rendered relative to the game camera coordinates, regardless
* of where in the world the camera is. This is used for things like sticking game UI to the camera that scrolls as it moves around the world.
*
* @class
*/
Phaser.Component.FixedToCamera = function () {};

/**
 * The FixedToCamera component postUpdate handler.
 * Called automatically by the Game Object.
 *
 * @method
 */
Phaser.Component.FixedToCamera.postUpdate = function () {

    if (this.fixedToCamera)
    {
        this.position.x = (this.game.camera.view.x + this.cameraOffset.x) / this.game.camera.scale.x;
        this.position.y = (this.game.camera.view.y + this.cameraOffset.y) / this.game.camera.scale.y;
    }

};

Phaser.Component.FixedToCamera.prototype = {

    /**
    * @property {boolean} _fixedToCamera
    * @private
    */
    _fixedToCamera: false,

    /**
    * A Game Object that is "fixed" to the camera uses its x/y coordinates as offsets from the top left of the camera during rendering.
    *
    * The values are adjusted at the rendering stage, overriding the Game Objects actual world position.
    *
    * The end result is that the Game Object will appear to be 'fixed' to the camera, regardless of where in the game world
    * the camera is viewing. This is useful if for example this Game Object is a UI item that you wish to be visible at all times
    * regardless where in the world the camera is.
    *
    * The offsets are stored in the `cameraOffset` property.
    *
    * Note that the `cameraOffset` values are in addition to any parent of this Game Object on the display list.
    *
    * Be careful not to set `fixedToCamera` on Game Objects which are in Groups that already have `fixedToCamera` enabled on them.
    *
    * @property {boolean} fixedToCamera
    */
    fixedToCamera: {

        get: function () {

            return this._fixedToCamera;

        },

        set: function (value) {

            if (value)
            {
                this._fixedToCamera = true;
                this.cameraOffset.set(this.x, this.y);
            }
            else
            {
                this._fixedToCamera = false;
            }

        }

    },

    /**
    * The x/y coordinate offset applied to the top-left of the camera that this Game Object will be drawn at if `fixedToCamera` is true.
    *
    * The values are relative to the top-left of the camera view and in addition to any parent of the Game Object on the display list.
    * @property {Phaser.Point} cameraOffset
    */
    cameraOffset: new Phaser.Point()

};


var PhysicsGroup = require('./PhysicsGroup');

var StaticPhysicsGroup = require('./StaticPhysicsGroup');

//  When registering a factory function 'this' refers to the GameObjectFactory context.

//  There are several properties available to use:

//  this.scene - a reference to the Scene that owns the GameObjectFactory

//  this.displayList - a reference to the Display List the Scene owns

//  this.updateList - a reference to the Update List the Scene owns

module.exports = {

    TILEMAP_CSV: 0,
    TILEMAP_TILED_JSON: 1,
    TILEMAP_2D_ARRAY: 2

};


var ArcadeImage = require('./ArcadeImage');
var ArcadeSprite = require('./ArcadeSprite');
var Class = require('../../utils/Class');
var CONST = require('./const');
var PhysicsGroup = require('./PhysicsGroup');
var StaticPhysicsGroup = require('./StaticPhysicsGroup');

var Factory = new Class({

    initialize:

    function Factory (world)
    {
        this.world = world;

        this.scene = world.scene;

        this.sys = world.scene.sys;
    },

    collider: function (object1, object2, collideCallback, processCallback, callbackContext)
    {
        return this.world.addCollider(object1, object2, collideCallback, processCallback, callbackContext);
    },

    overlap: function (object1, object2, collideCallback, processCallback, callbackContext)
    {
        return this.world.addOverlap(object1, object2, collideCallback, processCallback, callbackContext);
    },

    staticImage: function (x, y, key, frame)
    {
        var image = new ArcadeImage(this.scene, x, y, key, frame);

        this.sys.displayList.add(image);

        this.world.enableBody(image, CONST.STATIC_BODY);

        return image;
    },

    image: function (x, y, key, frame)
    {
        var image = new ArcadeImage(this.scene, x, y, key, frame);

        this.sys.displayList.add(image);

        this.world.enableBody(image, CONST.DYNAMIC_BODY);

        return image;
    },

    staticSprite: function (x, y, key, frame)
    {
        var sprite = new ArcadeSprite(this.scene, x, y, key, frame);

        this.sys.displayList.add(sprite);
        this.sys.updateList.add(sprite);

        this.world.enableBody(sprite, CONST.STATIC_BODY);

        return sprite;
    },

    sprite: function (x, y, key, frame)
    {
        var sprite = new ArcadeSprite(this.scene, x, y, key, frame);

        this.sys.displayList.add(sprite);
        this.sys.updateList.add(sprite);

        this.world.enableBody(sprite, CONST.DYNAMIC_BODY);

        return sprite;
    },

    staticGroup: function (children, config)
    {
        return new StaticPhysicsGroup(this.world, this.world.scene, children, config);
    },

    group: function (children, config)
    {
        return new PhysicsGroup(this.world, this.world.scene, children, config);
    }

});

module.exports = Factory;


/**
* @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 Physics Manager is responsible for looking after all of the running physics systems.
* Phaser supports 4 physics systems: Arcade Physics, P2, Ninja Physics and Box2D via a commercial plugin.
*
* Game Objects (such as Sprites) can only belong to 1 physics system, but you can have multiple systems active in a single game.
*
* For example you could have P2 managing a polygon-built terrain landscape that an vehicle drives over, while it could be firing bullets that use the
* faster (due to being much simpler) Arcade Physics system.
*
* @class Phaser.Physics
* @constructor
* @param {Phaser.Game} game - A reference to the currently running game.
* @param {object} [physicsConfig=null] - A physics configuration object to pass to the Physics world on creation.
*/
Phaser.Physics = function (game, config) {

    config = config || {};

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

    /**
    * @property {object} config - The physics configuration object as passed to the game on creation.
    */
    this.config = config;

    /**
    * @property {Phaser.Physics.Arcade} arcade - The Arcade Physics system.
    */
    this.arcade = null;

    /**
    * @property {Phaser.Physics.P2} p2 - The P2.JS Physics system.
    */
    this.p2 = null;

    /**
    * @property {Phaser.Physics.Ninja} ninja - The N+ Ninja Physics system.
    */
    this.ninja = null;

    /**
    * @property {Phaser.Physics.Box2D} box2d - The Box2D Physics system.
    */
    this.box2d = null;

    /**
    * @property {Phaser.Physics.Chipmunk} chipmunk - The Chipmunk Physics system (to be done).
    */
    this.chipmunk = null;

    /**
    * @property {Phaser.Physics.Matter} matter - The MatterJS Physics system (coming soon).
    */
    this.matter = null;

    this.parseConfig();

};

/**
* @const
* @type {number}
*/
Phaser.Physics.ARCADE = 0;

/**
* @const
* @type {number}
*/
Phaser.Physics.P2JS = 1;

/**
* @const
* @type {number}
*/
Phaser.Physics.NINJA = 2;

/**
* @const
* @type {number}
*/
Phaser.Physics.BOX2D = 3;

/**
* @const
* @type {number}
*/
Phaser.Physics.CHIPMUNK = 4;

/**
* @const
* @type {number}
*/
Phaser.Physics.MATTERJS = 5;

Phaser.Physics.prototype = {

    /**
    * Parses the Physics Configuration object passed to the Game constructor and starts any physics systems specified within.
    *
    * @method Phaser.Physics#parseConfig
    */
    parseConfig: function () {

        if ((!this.config.hasOwnProperty('arcade') || this.config['arcade'] === true) && Phaser.Physics.hasOwnProperty('Arcade'))
        {
            //  If Arcade isn't specified, we create it automatically if we can
            this.arcade = new Phaser.Physics.Arcade(this.game);
        }

        if (this.config.hasOwnProperty('ninja') && this.config['ninja'] === true && Phaser.Physics.hasOwnProperty('Ninja'))
        {
            this.ninja = new Phaser.Physics.Ninja(this.game);
        }

        if (this.config.hasOwnProperty('p2') && this.config['p2'] === true && Phaser.Physics.hasOwnProperty('P2'))
        {
            this.p2 = new Phaser.Physics.P2(this.game, this.config);
        }

        if (this.config.hasOwnProperty('box2d') && this.config['box2d'] === true && Phaser.Physics.hasOwnProperty('BOX2D'))
        {
            this.box2d = new Phaser.Physics.BOX2D(this.game, this.config);
        }

        if (this.config.hasOwnProperty('matter') && this.config['matter'] === true && Phaser.Physics.hasOwnProperty('Matter'))
        {
            this.matter = new Phaser.Physics.Matter(this.game, this.config);
        }

    },

    /**
    * This will create an instance of the requested physics simulation.
    * Phaser.Physics.Arcade is running by default, but all others need activating directly.
    *
    * You can start the following physics systems:
    *
    * Phaser.Physics.P2JS - A full-body advanced physics system by Stefan Hedman.
    * Phaser.Physics.NINJA - A port of Metanet Softwares N+ physics system.
    * Phaser.Physics.BOX2D - A commercial Phaser Plugin (see http://phaser.io)
    *
    * Both Ninja Physics and Box2D require their respective plugins to be loaded before you can start them.
    * They are not bundled into the core Phaser library.
    *
    * If the physics world has already been created (i.e. in another state in your game) then
    * calling startSystem will reset the physics world, not re-create it. If you need to start them again from their constructors
    * then set Phaser.Physics.p2 (or whichever system you want to recreate) to `null` before calling `startSystem`.
    *
    * @method Phaser.Physics#startSystem
    * @param {number} system - The physics system to start: Phaser.Physics.ARCADE, Phaser.Physics.P2JS, Phaser.Physics.NINJA or Phaser.Physics.BOX2D.
    */
    startSystem: function (system) {

        if (system === Phaser.Physics.ARCADE)
        {
            this.arcade = new Phaser.Physics.Arcade(this.game);
        }
        else if (system === Phaser.Physics.P2JS)
        {
            if (this.p2 === null)
            {
                this.p2 = new Phaser.Physics.P2(this.game, this.config);
            }
            else
            {
                this.p2.reset();
            }
        }
        else if (system === Phaser.Physics.NINJA)
        {
            this.ninja = new Phaser.Physics.Ninja(this.game);
        }
        else if (system === Phaser.Physics.BOX2D)
        {
            if (this.box2d === null)
            {
                this.box2d = new Phaser.Physics.Box2D(this.game, this.config);
            }
            else
            {
                this.box2d.reset();
            }
        }
        else if (system === Phaser.Physics.MATTERJS)
        {
            if (this.matter === null)
            {
                this.matter = new Phaser.Physics.Matter(this.game, this.config);
            }
            else
            {
                this.matter.reset();
            }
        }

    },

    /**
    * This will create a default physics body on the given game object or array of objects.
    * A game object can only have 1 physics body active at any one time, and it can't be changed until the object is destroyed.
    * It can be for any of the physics systems that have been started:
    *
    * Phaser.Physics.Arcade - A light weight AABB based collision system with basic separation.
    * Phaser.Physics.P2JS - A full-body advanced physics system supporting multiple object shapes, polygon loading, contact materials, springs and constraints.
    * Phaser.Physics.NINJA - A port of Metanet Softwares N+ physics system. Advanced AABB and Circle vs. Tile collision.
    * Phaser.Physics.BOX2D - A port of https://code.google.com/p/box2d-html5
    * Phaser.Physics.MATTER - A full-body and light-weight advanced physics system (still in development)
    * Phaser.Physics.CHIPMUNK is still in development.
    *
    * If you require more control over what type of body is created, for example to create a Ninja Physics Circle instead of the default AABB, then see the
    * individual physics systems `enable` methods instead of using this generic one.
    *
    * @method Phaser.Physics#enable
    * @param {object|array} object - The game object to create the physics body on. Can also be an array of objects, a body will be created on every object in the array.
    * @param {number} [system=Phaser.Physics.ARCADE] - The physics system that will be used to create the body. Defaults to Arcade Physics.
    * @param {boolean} [debug=false] - Enable the debug drawing for this body. Defaults to false.
    */
    enable: function (object, system, debug) {

        if (system === undefined) { system = Phaser.Physics.ARCADE; }
        if (debug === undefined) { debug = false; }

        if (system === Phaser.Physics.ARCADE)
        {
            this.arcade.enable(object);
        }
        else if (system === Phaser.Physics.P2JS && this.p2)
        {
            this.p2.enable(object, debug);
        }
        else if (system === Phaser.Physics.NINJA && this.ninja)
        {
            this.ninja.enableAABB(object);
        }
        else if (system === Phaser.Physics.BOX2D && this.box2d)
        {
            this.box2d.enable(object);
        }
        else if (system === Phaser.Physics.MATTERJS && this.matter)
        {
            this.matter.enable(object);
        }
        else
        {
            console.warn(object.key + ' is attempting to enable a physics body using an unknown physics system.');
        }

    },

    /**
    * preUpdate checks.
    *
    * @method Phaser.Physics#preUpdate
    * @protected
    */
    preUpdate: function () {

        //  ArcadePhysics / Ninja don't have a core to preUpdate

        if (this.p2)
        {
            this.p2.preUpdate();
        }

        if (this.box2d)
        {
            this.box2d.preUpdate();
        }

        if (this.matter)
        {
            this.matter.preUpdate();
        }

    },

    /**
    * Updates all running physics systems.
    *
    * @method Phaser.Physics#update
    * @protected
    */
    update: function () {

        //  ArcadePhysics / Ninja don't have a core to update

        if (this.p2)
        {
            this.p2.update();
        }

        if (this.box2d)
        {
            this.box2d.update();
        }

        if (this.matter)
        {
            this.matter.update();
        }

    },

    /**
    * Updates the physics bounds to match the world dimensions.
    *
    * @method Phaser.Physics#setBoundsToWorld
    * @protected
    */
    setBoundsToWorld: function () {

        if (this.arcade)
        {
            this.arcade.setBoundsToWorld();
        }

        if (this.ninja)
        {
            this.ninja.setBoundsToWorld();
        }

        if (this.p2)
        {
            this.p2.setBoundsToWorld();
        }

        if (this.box2d)
        {
            this.box2d.setBoundsToWorld();
        }

        if (this.matter)
        {
            this.matter.setBoundsToWorld();
        }

    },

    /**
    * Clears down all active physics systems. This doesn't destroy them, it just clears them of objects and is called when the State changes.
    *
    * @method Phaser.Physics#clear
    * @protected
    */
    clear: function () {

        if (this.p2)
        {
            this.p2.clear();
        }

        if (this.box2d)
        {
            this.box2d.clear();
        }

        if (this.matter)
        {
            this.matter.clear();
        }

    },

    /**
    * Resets the active physics system. Called automatically on a Phaser.State swap.
    *
    * @method Phaser.Physics#reset
    * @protected
    */
    reset: function () {

        if (this.p2)
        {
            this.p2.reset();
        }

        if (this.box2d)
        {
            this.box2d.reset();
        }

        if (this.matter)
        {
            this.matter.reset();
        }

    },

    /**
    * Destroys all active physics systems. Usually only called on a Game Shutdown, not on a State swap.
    *
    * @method Phaser.Physics#destroy
    */
    destroy: function () {

        if (this.p2)
        {
            this.p2.destroy();
        }

        if (this.box2d)
        {
            this.box2d.destroy();
        }

        if (this.matter)
        {
            this.matter.destroy();
        }

        this.arcade = null;
        this.ninja = null;
        this.p2 = null;
        this.box2d = null;
        this.matter = null;

    }

};

Phaser.Physics.prototype.constructor = Phaser.Physics;


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

/**
* Create a new `Bullet` object. Bullets are used by the `Phaser.Weapon` class, and are normal Sprites,
* with a few extra properties in the data object to handle Weapon specific features.
*
* @class Phaser.Bullet
* @constructor
* @extends Phaser.Sprite
* @param {Phaser.Game} game - A reference to the currently running game.
* @param {number} x - The x coordinate (in world space) to position the Particle at.
* @param {number} y - The y coordinate (in world space) to position the Particle at.
* @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the Particle during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture.
* @param {string|number} frame - If this Particle is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index.
*/
Phaser.Bullet = function (game, x, y, key, frame) {

    Phaser.Sprite.call(this, game, x, y, key, frame);

    this.anchor.set(0.5);

    this.data = {
        bulletManager: null,
        fromX: 0,
        fromY: 0,
        bodyDirty: true,
        rotateToVelocity: false,
        killType: 0,
        killDistance: 0
    };

};

Phaser.Bullet.prototype = Object.create(Phaser.Sprite.prototype);
Phaser.Bullet.prototype.constructor = Phaser.Bullet;

/**
* Kills the Bullet, freeing it up for re-use by the Weapon bullet pool.
* Also dispatches the `Weapon.onKill` signal.
*
* @method Phaser.Bullet#kill
* @memberof Phaser.Bullet
*/
Phaser.Bullet.prototype.kill = function () {

    this.alive = false;
    this.exists = false;
    this.visible = false;

    this.data.bulletManager.onKill.dispatch(this);

    return this;

};

/**
* Updates the Bullet, killing as required.
*
* @method Phaser.Bullet#kill
* @memberof Phaser.Bullet
*/
Phaser.Bullet.prototype.update = function () {

    if (!this.exists)
    {
        return;
    }

    if (this.data.killType > Phaser.Weapon.KILL_LIFESPAN)
    {
        if (this.data.killType === Phaser.Weapon.KILL_DISTANCE)
        {
            if (this.game.physics.arcade.distanceToXY(this, this.data.fromX, this.data.fromY, true) > this.data.killDistance)
            {
                this.kill();
            }
        }
        else
        {
            if (!this.data.bulletManager.bulletBounds.intersects(this))
            {
                this.kill();
            }
        }
    }

    if (this.data.rotateToVelocity)
    {
        this.rotation = Math.atan2(this.body.velocity.y, this.body.velocity.x);
    }

    if (this.data.bulletManager.bulletWorldWrap)
    {
        this.game.world.wrap(this, this.data.bulletManager.bulletWorldWrapPadding);
    }

};


/**
* @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 Animation Component provides a `play` method, which is a proxy to the `AnimationManager.play` method.
*
* @class
*/
Phaser.Component.Animation = function () {};

Phaser.Component.Animation.prototype = {

    /**
    * Plays an Animation.
    *
    * The animation should have previously been created via `animations.add`.
    *
    * If the animation is already playing calling this again won't do anything.
    * If you need to reset an already running animation do so directly on the Animation object itself or via `AnimationManager.stop`.
    *
    * @method
    * @param {string} name - The name of the animation to be played, e.g. "fire", "walk", "jump". Must have been previously created via 'AnimationManager.add'.
    * @param {number} [frameRate=null] - The framerate to play the animation at. The speed is given in frames per second. If not provided the previously set frameRate of the Animation is used.
    * @param {boolean} [loop=false] - Should the animation be looped after playback. If not provided the previously set loop value of the Animation is used.
    * @param {boolean} [killOnComplete=false] - If set to true when the animation completes (only happens if loop=false) the parent Sprite will be killed.
    * @return {Phaser.Animation} A reference to playing Animation.
    */
    play: function (name, frameRate, loop, killOnComplete) {

        if (this.animations)
        {
            return this.animations.play(name, frameRate, loop, killOnComplete);
        }

    }

};


staticGroup: function (children, config)

return new StaticPhysicsGroup(this.world, this.world.scene, children, config);

keep keep keep replace keep keep keep keep

return this.sys.updateList.add(new StaticPhysicsGroup(this.world, this.world.scene, children, config));

//  Phaser.Physics.Arcade.PhysicsGroup

var ArcadeSprite = require('./ArcadeSprite');
var Class = require('../../utils/Class');
var CONST = require('./const');
var GetFastValue = require('../../utils/object/GetFastValue');
var Group = require('../../gameobjects/group/Group');

var PhysicsGroup = new Class({

    Extends: Group,

    initialize:

    function PhysicsGroup (world, scene, children, config)
    {
        if (config === undefined && !Array.isArray(children) && typeof children === 'object')
        {
            config = children;
            children = null;
        }
        else if (config === undefined)
        {
            config = {};
        }

        this.world = world;

        config.createCallback = this.createCallback;
        config.removeCallback = this.removeCallback;
        config.classType = ArcadeSprite;

        this.physicsType = CONST.DYNAMIC_BODY;

        this.defaults = {
            setCollideWorldBounds: GetFastValue(config, 'collideWorldBounds', false),
            setAccelerationX: GetFastValue(config, 'accelerationX', 0),
            setAccelerationY: GetFastValue(config, 'accelerationY', 0),
            setBounceX: GetFastValue(config, 'bounceX', 0),
            setBounceY: GetFastValue(config, 'bounceY', 0),
            setDragX: GetFastValue(config, 'dragX', 0),
            setDragY: GetFastValue(config, 'dragY', 0),
            setGravityX: GetFastValue(config, 'gravityX', 0),
            setGravityY: GetFastValue(config, 'gravityY', 0),
            setFrictionX: GetFastValue(config, 'frictionX', 0),
            setFrictionY: GetFastValue(config, 'frictionY', 0),
            setVelocityX: GetFastValue(config, 'velocityX', 0),
            setVelocityY: GetFastValue(config, 'velocityY', 0),
            setAngularVelocity: GetFastValue(config, 'angularVelocity', 0),
            setAngularAcceleration: GetFastValue(config, 'angularAcceleration', 0),
            setAngularDrag: GetFastValue(config, 'angularDrag', 0),
            setMass: GetFastValue(config, 'mass', 1),
            setImmovable: GetFastValue(config, 'immovable', false)
        };

        Group.call(this, scene, children, config);
    },

    createCallback: function (child)
    {
        if (!child.body)
        {
            this.world.enableBody(child, CONST.DYNAMIC_BODY);
        }

        var body = child.body;

        for (var key in this.defaults)
        {
            body[key](this.defaults[key]);
        }
    },

    removeCallback: function (child)
    {
        if (child.body)
        {
            this.world.disableBody(child);
        }
    },

    setVelocity: function (x, y, step)
    {
        if (step === undefined) { step = 0; }

        var items = this.getChildren();

        for (var i = 0; i < items.length; i++)
        {
            items[i].body.velocity.set(x + (i * step), y + (i * step));
        }

        return this;
    },

    setVelocityX: function (value, step)
    {
        if (step === undefined) { step = 0; }

        var items = this.getChildren();

        for (var i = 0; i < items.length; i++)
        {
            items[i].body.velocity.x = value + (i * step);
        }

        return this;
    },

    setVelocityY: function (value, step)
    {
        if (step === undefined) { step = 0; }

        var items = this.getChildren();

        for (var i = 0; i < items.length; i++)
        {
            items[i].body.velocity.y = value + (i * step);
        }

        return this;
    }

});

module.exports = PhysicsGroup;


<?php
    class Parameter
    {
        public $processor;
        public $name; // rect, copy, etc
        public $types = []; // an array containing all possible types it can be: string, number, etc
        public $help = [];
        public $optional = false;
        public $default = null; // assigned value is the default value
        public $debug = '';

        public function __construct($processor, $line)
        {
            $this->processor = $processor;

            preg_match("/.*(@param)\s?{(\S*)} (\S*)( - ?)?(.*)/", $line, $output);

            // $this->processor->log("Parameter count: " . count($output));

            if (count($output) > 2)
            {
                // $this->processor->log("parsePhaser parameter");
                $this->parsePhaser($output);
            }
            else
            {
                preg_match("/(@param)\s(\S*)\s{(\S*)}\s?(.*)?/", $line, $output);

                // $this->processor->log("parsePixi parameter - " . count($output));

                if (count($output) > 0)
                {
                    $this->parsePixi($output);
                }
            }

        }

        public function parsePhaser($output)
        {
            $name = $output[3];

            // $this->processor->log("parameter: $name");

            if ($name[0] === '[')
            {
                $this->optional = true;
                $name = substr($name, 1, -1);

                //  Default?
                $equals = strpos($name, '=');

                if ($equals > 0)
                {
                    $this->default = (string) substr($name, $equals + 1);
                    $name = substr($name, 0, $equals);
                }
            }

            $this->name = $name;

            $this->types = $this->processor->parseTypes($output[2], false, $name);

            $this->help[] = $output[5];

        }

        public function parsePixi($output)
        {
            $this->name = $output[2];

            // $this->processor->log("parameter: $this->name");

            $this->types = $this->processor->parseTypes($output[3], true, $this->name);

            if (isset($output[4]))
            {
                $this->help[] = $output[4];
            }

        }

        public function getArray()
        {
            return array(
                'name' => $this->name,
                'type' => $this->types,
                'help' => implode('\n', $this->help),
                'optional' => $this->optional,
                'default' => $this->default
            );

        }

        public function getJSON()
        {
            return json_encode($this->getArray());
        }

    }
?>


<?js
var data = obj;
var self = this;
function mkSignature (data) {
    var attribs = data.attribs;
    attribs = attribs.replace('protected', 'internal');

    return (attribs + (data.kind === 'class' ? 'new ' : '') +
        data.name +
        (data.kind !== 'event' ? data.signature : ''));
}
?>

    <h4 class="name <?js= data.deprecated ? 'toc-deprecated' : ''?>"
        id="<?js= id ?>"><?js= mkSignature(data) ?>

    <?js if (data.summary) { ?>

<?js= summary ?>

    <?js } ?>

    <?js if (data.deprecated) { ?>

            This method is deprecated and should not be used. It may be removed in the future.

    <?js } ?>

    <?js if (data.description) { ?>

        <?js= data.description ?>

    <?js } ?>

    <?js if (kind === 'event' && data.type && data.type.names) {?>

Type:

                <?js= self.partial('type.tmpl', data.type.names) ?>

    <?js } ?>

    <?js if (data['this']) { ?>

This:

<?js= this.linkto(data['this'], data['this']) ?>

    <?js } ?>

    <?js if (data.params && params.length) { ?>

Parameters:

        <?js= this.partial('params.tmpl', params) ?>
    <?js } ?>

    <?js if (data.returns && returns.length) { ?>

Returns:

        <?js returns.forEach(function(r) { ?>
            <?js= self.partial('returns.tmpl', r) ?>
        <?js }); ?>

    <?js } ?>

    <?js= this.partial('details.tmpl', data) ?>

    <?js if (data.fires && fires.length) { ?>

Fires:

<?js fires.forEach(function(f) { ?>

<?js= self.linkto(f) ?>

    <?js }); ?>

    <?js } ?>

    <?js if (data.listens && listens.length) { ?>

Listens to Events:

<?js listens.forEach(function(f) { ?>

<?js= self.linkto(f) ?>

    <?js }); ?>

    <?js } ?>

    <?js if (data.listeners && listeners.length) { ?>

Listeners of This Event:

<?js listeners.forEach(function(f) { ?>

<?js= self.linkto(f) ?>

    <?js }); ?>

    <?js } ?>

    <?js if (data.exceptions && exceptions.length) { ?>

Throws:

    <?js if (exceptions.length > 1) { ?>
<?js
        exceptions.forEach(function(r) { ?>

<?js= self.partial('exceptions.tmpl', r) ?>

        <?js });
    ?>
<?js } else {
        exceptions.forEach(function(r) { ?>
            <?js= self.partial('exceptions.tmpl', r) ?>
        <?js });
    } } ?>

    <?js if (data.examples && examples.length) { ?>

Example<?js= examples.length > 1? 's':'' ?>

        <?js= this.partial('examples.tmpl', examples) ?>
    <?js } ?>


var Random = require('../geom/rectangle/Random');

/**
 * [description]
 *
 * @function Phaser.Actions.RandomRectangle
 * @since 3.0.0
 *
 * @param {array} items - An array of Game Objects. The contents of this array are updated by this Action.
 * @param {Phaser.Geom.Rectangle} rect - [description]
 *
 * @return {array} The array of Game Objects that was passed to this Action.
 */
var RandomRectangle = function (items, rect)
{
    for (var i = 0; i < items.length; i++)
    {
        Random(rect, items[i]);
    }

    return items;
};

module.exports = RandomRectangle;


return new PhysicsGroup(this.world, this.world.scene, children, config);

return this.sys.updateList.add(new PhysicsGroup(this.world, this.world.scene, children, config));


//  Gets the Active scene at the given position

/**
 * [description]
 *
 * @method Phaser.Scenes.GlobalSceneManager#getSceneAt
 * @since 3.0.0
 *
 * @param {integer} index - [description]
 *
 * @return {Phaser.Scene} [description]
 */
var GetSceneAt = function (index)
{
    if (this.active[index])
    {
        return this.active[index].scene;
    }
};

module.exports = GetSceneAt;


var ComputeVelocity = function (axis, body, velocity, acceleration, drag, max)
{
    if (max === undefined) { max = 10000; }

    if (axis === 1 && body.allowGravity)
    {
        velocity += (this.gravity.x + body.gravity.x) * this.delta;
    }
    else if (axis === 2 && body.allowGravity)
    {
        velocity += (this.gravity.y + body.gravity.y) * this.delta;
    }

    if (acceleration)
    {
        velocity += acceleration * this.delta;
    }
    else if (drag && body.allowDrag)
    {
        drag *= this.delta;

        if (velocity - drag > 0)
        {
            velocity -= drag;
        }
        else if (velocity + drag < 0)
        {
            velocity += drag;
        }
        else
        {
            velocity = 0;
        }
    }

    if (velocity > max)
    {
        velocity = max;
    }
    else if (velocity < -max)
    {
        velocity = -max;
    }

    return velocity;
};

module.exports = ComputeVelocity;


Phaser.Particles.Arcade

Arcade Particles is a Particle System integrated with Arcade Physics.


config.classType = GetFastValue(config, 'classType', ArcadeSprite);


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

Phaser.GameObject.RetroFont.FACTORY_KEY = 'retroFont';

/**
* Create a new RetroFont object.
*
* A RetroFont can be used as a texture for an Image or Sprite and optionally add it to the Cache.
* A RetroFont uses a bitmap which contains fixed with characters for the font set. You use character spacing to define the set.
* If you need variable width character support then use a BitmapText object instead. The main difference between a RetroFont and a BitmapText
* is that a RetroFont creates a single texture that you can apply to a game object, where-as a BitmapText creates one Sprite object per letter of text.
* The texture can be asssigned or one or multiple images/sprites, but note that the text the RetroFont uses will be shared across them all,
* i.e. if you need each Image to have different text in it, then you need to create multiple RetroFont objects.
*
* @method Phaser.GameObject.Factory#retroFont
* @param {string} font - The key of the image in the Game.Cache that the RetroFont will use.
* @param {number} characterWidth - The width of each character in the font set.
* @param {number} characterHeight - The height of each character in the font set.
* @param {string} chars - The characters used in the font set, in display order. You can use the TEXT_SET consts for common font set arrangements.
* @param {number} charsPerRow - The number of characters per row in the font set.
* @param {number} [xSpacing=0] - If the characters in the font set have horizontal spacing between them set the required amount here.
* @param {number} [ySpacing=0] - If the characters in the font set have vertical spacing between them set the required amount here.
* @param {number} [xOffset=0] - If the font set doesn't start at the top left of the given image, specify the X coordinate offset here.
* @param {number} [yOffset=0] - If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here.
* @return {Phaser.RetroFont} The newly created RetroFont texture which can be applied to an Image or Sprite.
*/
Phaser.GameObject.RetroFont.FACTORY_ADD = function (font, characterWidth, characterHeight, chars, charsPerRow, xSpacing, ySpacing, xOffset, yOffset)
{
    return new Phaser.GameObject.RetroFont(this.game, font, characterWidth, characterHeight, chars, charsPerRow, xSpacing, ySpacing, xOffset, yOffset);
};

/**
* Create a new RetroFont object.
*
* A RetroFont can be used as a texture for an Image or Sprite and optionally add it to the Cache.
* A RetroFont uses a bitmap which contains fixed with characters for the font set. You use character spacing to define the set.
* If you need variable width character support then use a BitmapText object instead. The main difference between a RetroFont and a BitmapText
* is that a RetroFont creates a single texture that you can apply to a game object, where-as a BitmapText creates one Sprite object per letter of text.
* The texture can be asssigned or one or multiple images/sprites, but note that the text the RetroFont uses will be shared across them all,
* i.e. if you need each Image to have different text in it, then you need to create multiple RetroFont objects.
*
* @method Phaser.GameObjectCreator#retroFont
* @param {string} font - The key of the image in the Game.Cache that the RetroFont will use.
* @param {number} characterWidth - The width of each character in the font set.
* @param {number} characterHeight - The height of each character in the font set.
* @param {string} chars - The characters used in the font set, in display order. You can use the TEXT_SET consts for common font set arrangements.
* @param {number} charsPerRow - The number of characters per row in the font set.
* @param {number} [xSpacing=0] - If the characters in the font set have horizontal spacing between them set the required amount here.
* @param {number} [ySpacing=0] - If the characters in the font set have vertical spacing between them set the required amount here.
* @param {number} [xOffset=0] - If the font set doesn't start at the top left of the given image, specify the X coordinate offset here.
* @param {number} [yOffset=0] - If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here.
* @return {Phaser.RetroFont} The newly created RetroFont texture which can be applied to an Image or Sprite.
*/
Phaser.GameObject.RetroFont.FACTORY_MAKE = function (font, characterWidth, characterHeight, chars, charsPerRow, xSpacing, ySpacing, xOffset, yOffset)
{
    return new Phaser.GameObject.RetroFont(this.game, font, characterWidth, characterHeight, chars, charsPerRow, xSpacing, ySpacing, xOffset, yOffset);
};


var ResetAll = function ()
{
    while (this.cameras.length > 0)
    {
        this.cameraPool.push(this.cameras.pop());
    }

    this.main = this.add();

    return this.main;
};

module.exports = ResetAll;


/* Tomorrow Theme */
/* Original theme - https://github.com/chriskempson/tomorrow-theme */
/* Pretty printing styles. Used with prettify.js. */
/* SPAN elements with the classes below are added by prettyprint. */
/* plain text */
.pln {
  color: #4d4d4c; }

@media screen {
  /* string content */
  .str {
    color: #718c00; }

  /* a keyword */
  .kwd {
    color: #8959a8; }

  /* a comment */
  .com {
    color: #8e908c; }

  /* a type name */
  .typ {
    color: #4271ae; }

  /* a literal value */
  .lit {
    color: #f5871f; }

  /* punctuation */
  .pun {
    color: #4d4d4c; }

  /* lisp open bracket */
  .opn {
    color: #4d4d4c; }

  /* lisp close bracket */
  .clo {
    color: #4d4d4c; }

  /* a markup tag name */
  .tag {
    color: #c82829; }

  /* a markup attribute name */
  .atn {
    color: #f5871f; }

  /* a markup attribute value */
  .atv {
    color: #3e999f; }

  /* a declaration */
  .dec {
    color: #f5871f; }

  /* a variable name */
  .var {
    color: #c82829; }

  /* a function name */
  .fun {
    color: #4271ae; } }
/* Use higher contrast and text-weight for printable form. */
@media print, projection {
  .str {
    color: #060; }

  .kwd {
    color: #006;
    font-weight: bold; }

  .com {
    color: #600;
    font-style: italic; }

  .typ {
    color: #404;
    font-weight: bold; }

  .lit {
    color: #044; }

  .pun, .opn, .clo {
    color: #440; }

  .tag {
    color: #006;
    font-weight: bold; }

  .atn {
    color: #404; }

  .atv {
    color: #060; } }
/* Style */
/*
pre.prettyprint {
  background: white;
  font-family: Menlo, Monaco, Consolas, monospace;
  font-size: 12px;
  line-height: 1.5;
  border: 1px solid #ccc;
  padding: 10px; }
*/

/* Specify class=linenums on a pre to get line numbering */
ol.linenums {
  margin-top: 0;
  margin-bottom: 0; }

/* IE indents via margin-left */
li.L0,
li.L1,
li.L2,
li.L3,
li.L4,
li.L5,
li.L6,
li.L7,
li.L8,
li.L9 {
  /* */ }

/* Alternate shading for lines */
li.L1,
li.L3,
li.L5,
li.L7,
li.L9 {
  /* */ }


from OpenGL.GL import GL_FILL, GL_FRONT_AND_BACK, GL_LINE, GL_MODELVIEW

from OpenGL.GL import glCallList, glMatrixMode, glPolygonMode, glPopMatrix, glPushMatrix, glTranslated, \

#! /usr/bin/env python
from OpenGL.GL import glCallList, glClear, glClearColor, glColorMaterial, glCullFace, glDepthFunc, glDisable, glEnable,\
                      glFlush, glGetFloatv, glLightfv, glLoadIdentity, glMatrixMode, glMultMatrixf, glPopMatrix, \
                      glPushMatrix, glTranslated, glViewport
from OpenGL.GL import GL_AMBIENT_AND_DIFFUSE, GL_BACK, GL_CULL_FACE, GL_COLOR_BUFFER_BIT, GL_COLOR_MATERIAL, \
                      GL_DEPTH_BUFFER_BIT, GL_DEPTH_TEST, GL_FRONT_AND_BACK, GL_LESS, GL_LIGHT0, GL_LIGHTING, \
                      GL_MODELVIEW, GL_MODELVIEW_MATRIX, GL_POSITION, GL_PROJECTION, GL_SPOT_DIRECTION
from OpenGL.constants import GLfloat_3, GLfloat_4
from OpenGL.GLU import gluPerspective, gluUnProject
from OpenGL.GLUT import glutCreateWindow, glutDisplayFunc, glutGet, glutInit, glutInitDisplayMode, \
                        glutInitWindowSize, glutMainLoop
from OpenGL.GLUT import GLUT_SINGLE, GLUT_RGB, GLUT_WINDOW_HEIGHT, GLUT_WINDOW_WIDTH

import numpy
from numpy.linalg import norm, inv

from interaction import Interaction
from primitive import init_primitives, G_OBJ_PLANE
from node import Sphere, Cube
from scene import Scene

class Viewer(object):
    def __init__(self):
        """ Initialize the viewer. """
        self.init_interface()
        self.init_opengl()
        self.init_scene()
        self.init_interaction()
        init_primitives()

    def init_interface(self):
        """ initialize the window and register the render function """
        glutInit()
        glutInitWindowSize(640, 480)
        glutCreateWindow("3D Modeller")
        glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB)
        glutDisplayFunc(self.render)

    def init_interaction(self):
        """ init user interaction and callbacks """
        self.interaction = Interaction()
        self.interaction.register_callback('pick', self.pick)
        self.interaction.register_callback('move', self.move)
        self.interaction.register_callback('place', self.place)
        self.interaction.register_callback('rotate_color', self.rotate_color)
        self.interaction.register_callback('scale', self.scale)

    def init_scene(self):
        """ initialize the scene object and initial scene """
        self.scene = Scene()
        self.initial_scene()

    def init_opengl(self):
        """ initialize the opengl settings to render the scene """
        self.inverseModelView = numpy.identity(4)
        self.modelView = numpy.identity(4)

        glEnable(GL_CULL_FACE)
        glCullFace(GL_BACK)
        glEnable(GL_DEPTH_TEST)
        glDepthFunc(GL_LESS)

        glEnable(GL_LIGHT0)
        glLightfv(GL_LIGHT0, GL_POSITION, GLfloat_4(0, 0, 1, 0))
        glLightfv(GL_LIGHT0, GL_SPOT_DIRECTION, GLfloat_3(0, 0, -1))

        glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE)
        glEnable(GL_COLOR_MATERIAL)
        glClearColor(1.0, 1.0, 1.0, 0.0)

    def main_loop(self):
        glutMainLoop()

    def render(self):
        """ The render pass for the scene """
        self.init_view()

        # Enable lighting and color
        glEnable(GL_LIGHTING)

        glClearColor(0.4, 0.4, 0.4, 0.0)
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        # Load the modelview matrix from the current state of the trackball
        glMatrixMode(GL_MODELVIEW)
        glPushMatrix()
        glLoadIdentity()
        loc = self.interaction.translation
        glTranslated(-loc[0], -loc[1], -loc[2])
        glMultMatrixf(self.interaction.trackball.matrix)

        # store the inverse of the current modelview.
        currentModelView = numpy.array(glGetFloatv(GL_MODELVIEW_MATRIX))
        self.modelView = numpy.transpose(currentModelView)
        self.inverseModelView = inv(numpy.transpose(currentModelView))

        # render the scene. This will call the render function for each object in the scene
        self.scene.render()

        # draw the grid
        glDisable(GL_LIGHTING)
        glCallList(G_OBJ_PLANE)
        glPopMatrix()

        # flush the buffers so that the scene can be drawn
        glFlush()

    def init_view(self):
        """ initialize the projection matrix """
        xSize, ySize = glutGet(GLUT_WINDOW_WIDTH), glutGet(GLUT_WINDOW_HEIGHT)
        aspect_ratio = float(xSize) / float(ySize)

        # load the projection matrix. Always the same
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()

        glViewport(0, 0, xSize, ySize)
        gluPerspective(70, aspect_ratio, 0.1, 1000.0)
        glTranslated(0, 0, -15)

    def initial_scene(self):
        cube_node = Cube()
        cube_node.translate(2, 0, 2)
        cube_node.color_index = 2
        self.scene.add_node(cube_node)

        sphere_node = Sphere()
        sphere_node.translate(-2, 0, 2)
        sphere_node.color_index = 3
        self.scene.add_node(sphere_node)

        sphere_node_2 = Sphere()
        sphere_node_2.translate(-2, 0, -2)
        sphere_node_2.color_index = 1
        self.scene.add_node(sphere_node_2)

    def get_ray(self, x, y):
        """ Generate a ray beginning at the near plane, in the direction that the x, y coordinates are facing
            Consumes: x, y coordinates of mouse on screen
            Return: start, direction of the ray """
        self.init_view()

        glMatrixMode(GL_MODELVIEW)
        glLoadIdentity()

        # get two points on the line.
        start = numpy.array(gluUnProject(x, y, 0.001))
        end = numpy.array(gluUnProject(x, y, 0.999))

        # convert those points into a ray
        direction = end - start
        direction = direction / norm(direction)

        return (start, direction)

    def pick(self, x, y):
        """ Execute pick of an object. Selects an object in the scene.
            Consumes: x, y coordinates of the mouse on the screen """
        start, direction = self.get_ray(x, y)
        self.scene.pick(start, direction, self.modelView)

    def move(self, x, y):
        """ Execute a move command on the scene.
            Consumes: x, y coordinates of the mouse on the screen """
        start, direction = self.get_ray(x, y)
        self.scene.move(start, direction, self.inverseModelView)

    def place(self, shape, x, y):
        """ Execute a placement of a new primitive into the scene.
            Consumes: x, y coordinates of the mouse on the screen """
        start, direction = self.get_ray(x, y)
        self.scene.place(shape, start, direction, self.inverseModelView)

    def rotate_color(self, forward):
        """ Rotate the color of the selected Node. Boolean 'forward' indicates direction of rotation. """
        self.scene.rotate_color(forward)

    def scale(self, up):
        """ Scale the selected Node. Boolean up indicates scaling larger."""
        self.scene.scale(up)

if __name__ == "__main__":
    viewer = Viewer()
    viewer.main_loop()


import protocol
from member import Component

class Heartbeat(Component):

    def __init__(self, member, clock):
        super(Heartbeat, self).__init__(member)
        self.running = False
        self.last_heard_from = {}
        self.peers = None
        self.clock = clock

    def on_view_change_event(self, viewchange):
        self.peers = set(viewchange.peers)
        for peer in self.peers:
            self.last_heard_from[peer] = self.clock()
        if not self.running:
            self.heartbeat()
            self.running = True

    def do_HEARTBEAT(self, sender):
        self.last_heard_from[sender] = self.clock()

    def heartbeat(self):
        # send heartbeats to other nodes
        self.send(self.last_heard_from.keys(), 'HEARTBEAT', sender=self.address)

        # determine if any peers are down, and notify if so; note that this
        # notification will occur repeatedly until a view change
        too_old = self.clock() - 2 * protocol.HEARTBEAT_INTERVAL
        active_peers = set(p for p in self.last_heard_from if self.last_heard_from[p] >= too_old)
        if active_peers != self.peers:
            self.event('peers_down', down=self.peers - active_peers)

        self.set_timer(protocol.HEARTBEAT_INTERVAL, self.heartbeat)


import protocol
from util import defaultlist, view_primary
from protocol import Proposal, ViewChange
from member import Component

class Replica(Component):

    def __init__(self, member, execute_fn):
        super(Replica, self).__init__(member)
        self.execute_fn = execute_fn
        self.proposals = defaultlist()
        self.viewchange_proposal = None

    def start(self, state, slot_num, decisions, viewid, peers):
        self.state = state
        self.slot_num = slot_num
        # next slot num for a proposal (may lead slot_num)
        self.next_slot = slot_num
        self.decisions = defaultlist(decisions)
        self.viewid = viewid
        self.peers = peers
        self.peers_down = set()

        self.repropose()

    # creating proposals

    def do_INVOKE(self, caller, cid, input):
        proposal = Proposal(caller, cid, input)
        if proposal not in self.proposals:
            self.propose(proposal)
        else:
            slot = self.proposals.index(proposal)
            self.logger.info("proposal %s already proposed in slot %d" %
                             (proposal, slot))

    def do_JOIN(self, requester):
        if requester not in self.peers:
            viewchange = ViewChange(self.viewid + 1,
                                    tuple(sorted(set(self.peers) | set([requester]))))
            self.propose(Proposal(None, None, viewchange))

    # injecting proposals

    def propose(self, proposal, slot=None):
        if not slot:
            slot = self.next_slot
            self.next_slot += 1
        self.proposals[slot] = proposal
        # find a leader we think is working, deterministically
        leaders = [view_primary(self.viewid, self.peers)] + \
            list(self.peers)
        leader = (l for l in leaders if l not in self.peers_down).next()
        self.logger.info("proposing %s at slot %d to leader %s" %
                         (proposal, slot, leader))
        self.send([leader], 'PROPOSE', slot=slot, proposal=proposal)

    def repropose(self):
        "re-transmit any un-decided proposals"
        for slot in xrange(self.slot_num, self.next_slot):
            if self.proposals[slot]:
                self.propose(self.proposals[slot], slot)
            else:
                # make an empty proposal to learn what was decided
                self.propose(Proposal(None, None, None), slot)
        self.set_timer(protocol.REPROPOSE_INTERVAL, self.repropose)

    # view changes

    def on_view_change_event(self, viewchange):
        self.peers = viewchange.peers
        self.peers_down = set()

    def on_peers_down_event(self, down):
        self.peers_down = down
        if self.viewchange_proposal and self.viewchange_proposal not in self.decisions:
            return  # we're still working on a viewchange that hasn't been decided
        new_peers = tuple(sorted(set(self.peers) - set(down)))
        if len(new_peers) < 3:
            self.logger.info("lost peer(s) %s; need at least three peers" % (down,))
            return
        self.logger.info("lost peer(s) %s; proposing new view" % (down,))
        self.viewchange_proposal = Proposal(
                None, None,
                ViewChange(self.viewid + 1, tuple(sorted(set(self.peers) - set(down)))))
        self.propose(self.viewchange_proposal)

    # handling decided proposals

    def do_DECISION(self, slot, proposal):
        if self.decisions[slot] is not None:
            assert self.decisions[slot] == proposal, \
                "slot %d already decided: %r!" % (
                    slot, self.decisions[slot])
            return
        self.decisions[slot] = proposal
        self.next_slot = max(self.next_slot, slot + 1)

        # execute any pending, decided proposals, eliminating duplicates
        while True:
            decided_proposal = self.decisions[self.slot_num]
            if not decided_proposal:
                break  # not decided yet

            # re-propose any of our proposals which have lost in their slot
            our_proposal = self.proposals[self.slot_num]
            if our_proposal is not None and our_proposal != decided_proposal:
                self.propose(our_proposal)

            self.slot_num += 1

            if decided_proposal in self.decisions[:self.slot_num - 1]:
                continue  # duplicate
            self.logger.info("invoking %r" % (decided_proposal,))
            output = self.invoke(decided_proposal)
            if decided_proposal.caller:
                self.send([decided_proposal.caller], 'INVOKED',
                                 cid=decided_proposal.cid, output=output)

    def invoke(self, proposal):
        "actually invoke a proposal that is decided and in sequence"
        if isinstance(proposal.input, ViewChange):
            self.invoke_viewchange(proposal.input)
        else:
            # perform a client operation
            self.state, output = self.execute_fn(
                self.state, proposal.input)
            return output

    def invoke_viewchange(self, viewchange):
        if viewchange.viewid == self.viewid + 1:
            self.logger.info("entering view %d with peers %s" %
                                (viewchange.viewid, viewchange.peers))
            self.viewid = viewchange.viewid
            self.send(list(set(viewchange.peers) - set(self.peers)), 'WELCOME',
                      state=self.state,
                      slot_num=self.slot_num,
                      decisions=self.decisions,
                      viewid=viewchange.viewid,
                      peers=viewchange.peers)
            if self.address not in viewchange.peers:
                self.stop()
                return
            self.event('view_change', viewchange=viewchange)
        else:
            self.logger.info(
                "ignored out-of-sequence view change operation")


from OpenGL.GL import GL_EMISSION, GL_FRONT

from primitive import G_OBJ_CUBE, G_OBJ_SPHERE

from transformation import scaling, translation

keep replace replace keep keep keep keep keep

from OpenGL.GL import glCallList, glColor3f, glMaterialfv, glMultMatrixf, glPopMatrix, glPushMatrix, \

from OpenGL.GL import glBegin, glColor3f, glEnd, glEndList, glLineWidth, glNewList, glNormal3f, glVertex3f
from OpenGL.GL import GL_COMPILE, GL_LINES, GL_QUADS
from OpenGL.GLU import gluDeleteQuadric, gluNewQuadric, gluSphere

G_OBJ_PLANE = 1
G_OBJ_SPHERE = 2
G_OBJ_CUBE = 3

def make_plane():
    glNewList(G_OBJ_PLANE, GL_COMPILE)
    glBegin(GL_LINES)
    glColor3f(0, 0, 0)
    for i in xrange(41):
        glVertex3f(-10.0 + 0.5 * i, 0, -10)
        glVertex3f(-10.0 + 0.5 * i, 0, 10)
        glVertex3f(-10.0, 0, -10 + 0.5 * i)
        glVertex3f(10.0, 0, -10 + 0.5 * i)

    # Axes
    glEnd()
    glLineWidth(5)

    glBegin(GL_LINES)
    glColor3f(0.5, 0.7, 0.5)
    glVertex3f(0.0, 0.0, 0.0)
    glVertex3f(5, 0.0, 0.0)
    glEnd()

    glBegin(GL_LINES)
    glColor3f(0.5, 0.7, 0.5)
    glVertex3f(0.0, 0.0, 0.0)
    glVertex3f(0.0, 5, 0.0)
    glEnd()

    glBegin(GL_LINES)
    glColor3f(0.5, 0.7, 0.5)
    glVertex3f(0.0, 0.0, 0.0)
    glVertex3f(0.0, 0.0, 5)
    glEnd()

    # Draw the Y.
    glBegin(GL_LINES)
    glColor3f(0.0, 0.0, 0.0)
    glVertex3f(0.0, 5.0, 0.0)
    glVertex3f(0.0, 5.5, 0.0)
    glVertex3f(0.0, 5.5, 0.0)
    glVertex3f(-0.5, 6.0, 0.0)
    glVertex3f(0.0, 5.5, 0.0)
    glVertex3f(0.5, 6.0, 0.0)

    # Draw the Z.
    glVertex3f(-0.5, 0.0, 5.0)
    glVertex3f(0.5, 0.0, 5.0)
    glVertex3f(0.5, 0.0, 5.0)
    glVertex3f(-0.5, 0.0, 6.0)
    glVertex3f(-0.5, 0.0, 6.0)
    glVertex3f(0.5, 0.0, 6.0)

    # Draw the X.
    glVertex3f(5.0, 0.0, 0.5)
    glVertex3f(6.0, 0.0, -0.5)
    glVertex3f(5.0, 0.0, -0.5)
    glVertex3f(6.0, 0.0, 0.5)

    glEnd()
    glLineWidth(1)
    glEndList()

def make_sphere():
    glNewList(G_OBJ_SPHERE, GL_COMPILE)
    quad = gluNewQuadric()
    gluSphere(quad, 0.5, 30, 30)
    gluDeleteQuadric(quad)
    glEndList()

def make_cube():
    glNewList(G_OBJ_CUBE, GL_COMPILE)
    vertices = [((-0.5, -0.5, -0.5), (-0.5, -0.5, 0.5), (-0.5, 0.5, 0.5), (-0.5, 0.5, -0.5)),
                ((-0.5, -0.5, -0.5), (-0.5, 0.5, -0.5), (0.5, 0.5, -0.5), (0.5, -0.5, -0.5)),
                ((0.5, -0.5, -0.5), (0.5, 0.5, -0.5), (0.5, 0.5, 0.5), (0.5, -0.5, 0.5)),
                ((-0.5, -0.5, 0.5), (0.5, -0.5, 0.5), (0.5, 0.5, 0.5), (-0.5, 0.5, 0.5)),
                ((-0.5, -0.5, 0.5), (-0.5, -0.5, -0.5), (0.5, -0.5, -0.5), (0.5, -0.5, 0.5)),
                ((-0.5, 0.5, -0.5), (-0.5, 0.5, 0.5), (0.5, 0.5, 0.5), (0.5, 0.5, -0.5))]
    normals = [(-1.0, 0.0, 0.0), (0.0, 0.0, -1.0), (1.0, 0.0, 0.0), (0.0, 0.0, 1.0), (0.0, -1.0, 0.0), (0.0, 1.0, 0.0)]

    glBegin(GL_QUADS)
    for i in xrange(6):
        glNormal3f(normals[i][0], normals[i][1], normals[i][2])
        for j in xrange(4):
            glVertex3f(vertices[i][j][0], vertices[i][j][1], vertices[i][j][2])
    glEnd()
    glEndList()

def init_primitives():
    make_plane()
    make_sphere()
    make_cube()


require "catechism/version"
require "core_ext/object"
require "catechism/describe_block"
require "catechism/subject_wrapper"
require "catechism/cli"


-record(torrent_info, { tracker_url  :: binary(),
                info_hash    :: binary(),
                name         :: string(),
                piece_length :: pos_integer(),
                total_length :: pos_integer(),
                num_pieces   :: pos_integer(),
                piece_hashes :: binary()
              }).

-record(client, { peer_id    :: binary(),
                  ip         :: inet:ip_address(),
                  port       :: inet:port_number() }).

-define(BLOCK_SIZE, (1 bsl 14)).


from OpenGL.GL import GL_COMPILE, GL_LINES, GL_QUADS

from OpenGL.GLU import gluDeleteQuadric, gluNewQuadric, gluSphere

from OpenGL.GL import glBegin, glColor3f, glEnd, glEndList, glLineWidth, glNewList, glNormal3f, glVertex3f, \


# Graph layout engine

A graph layout engine.
Author: Julia Evans

TODO: Everything.


module Catechism
  module Matchers
    class Equal < Struct.new(:subject, :expectation, :negated)
      def equal?
        subject == expectation
      end

      def valid?
        equal? ^ negated
      end

      def failure_message
        if negated
          "#{subject} equals #{expected}"
        else
          "#{subject} does not equal #{expected}"
        end
      end
    end
  end
end


class Member(object):

    def __init__(self, execute_fn):
        self.execute_fn = execute_fn

    def start(self, initial_value=None):
        self.state = initial_value

    def invoke(self, input):
        self.state, output = self.execute_fn(self.state, input)
        return output

class Client(object):

    def __init__(self, member):
        self.member = member

    def invoke(self, input):
        return self.member.invoke(input)

def sequence_generator(state, input):
    return state + input, range(state, state + input)

if __name__ == "__main__":
    member = Member(sequence_generator)
    member.start(initial_value=0)
    print Client(member).invoke(4)
    print Client(member).invoke(1)


from OpenGL.GL import glCallList, glClear, glClearColor, glColorMaterial, glCullFace, glDepthFunc, glDisable, glEnable,\

glFlush, glGetFloatv, glLightfv, glLoadIdentity, glMatrixMode, glMultMatrixf, glPopMatrix, \

from OpenGL.GL import GL_AMBIENT_AND_DIFFUSE, GL_BACK, GL_CULL_FACE, GL_COLOR_BUFFER_BIT, GL_COLOR_MATERIAL, \

GL_DEPTH_BUFFER_BIT, GL_DEPTH_TEST, GL_FRONT_AND_BACK, GL_LESS, GL_LIGHT0, GL_LIGHTING, \

GL_MODELVIEW, GL_MODELVIEW_MATRIX, GL_POSITION, GL_PROJECTION, GL_SPOT_DIRECTION

from OpenGL.constants import GLfloat_3, GLfloat_4

from OpenGL.GLU import gluPerspective, gluUnProject

keep keep keep replace replace keep keep keep keep

glPushMatrix, glTranslated, glViewport, \


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

<title>Cluster Status</title>


import protocol
from protocol import ViewChange
from member import Component

class Bootstrap(Component):

    def __init__(self, member, peers, bootstrapped_cb):
        super(Bootstrap, self).__init__(member)
        self.peers = peers
        self.bootstrapped_cb = bootstrapped_cb

    def start(self):
        self.join()

    def join(self):
        "Try to join the cluster"
        self.peers = self.peers[1:] + self.peers[:1] # rotate through peers
        self.send([self.peers[0]], 'JOIN', requester=self.address)
        self.set_timer(protocol.JOIN_RETRANSMIT, self.join)

    def do_WELCOME(self, state, slot_num, decisions, viewid, peers):
        self.bootstrapped_cb(state, slot_num, decisions, viewid, peers)
        self.event('view_change', viewchange=ViewChange(viewid, peers))  # TODO: pass viewid, peers separately
        self.stop()


from collections import defaultdict
from protocol import Ballot
from member import Component

class Acceptor(Component):

    def __init__(self, member):
        super(Acceptor, self).__init__(member)
        self.ballot_num = Ballot(-1, -1)
        self.accepted = defaultdict()  # { (b,s) : p }

    def do_PREPARE(self, scout_id, ballot_num):  # p1a
        if ballot_num > self.ballot_num:
            self.ballot_num = ballot_num
        self.send([scout_id.address], 'PROMISE',  # p1b
                         scout_id=scout_id,
                         acceptor=self.address,
                         ballot_num=self.ballot_num,
                         accepted=self.accepted)

    def do_ACCEPT(self, commander_id, ballot_num, slot, proposal):  # p2a
        if ballot_num >= self.ballot_num:
            self.ballot_num = ballot_num
            self.accepted[(ballot_num, slot)] = proposal
        self.send([commander_id.address], 'ACCEPTED',  # p2b
                         commander_id=commander_id,
                         acceptor=self.address,
                         ballot_num=self.ballot_num)


from OpenGL.GLUT import glutCreateWindow, glutDisplayFunc, glutGet, glutInit, glutInitDisplayMode, \

from OpenGL.GLUT import GLUT_SINGLE, GLUT_RGB, GLUT_WINDOW_HEIGHT, GLUT_WINDOW_WIDTH

keep keep keep keep replace replace keep keep keep keep keep


require "catechism/it_block"

class Catechism::DescribeBlock < Struct.new(:description)
  def it(description, &block)
    Catechism::ItBlock.new(description, self).instance_eval(&block) if block_given?
  end
end


class FakeNode(object):

    def __init__(self):
        self.unique_id = 999
        self.address = 'F999'
        self.component = None
        self.timers = []
        self.sent = []

    def register(self, component):
        assert not self.component
        self.component = component

    def set_timer(self, seconds, callable):
        self.timers.append([seconds, callable, True])
        return self.timers[-1]

    def cancel_timer(self, timer):
        timer[2] = False

    def send(self, destinations, action, **kwargs):
        self.sent.append((destinations, action, kwargs))

    def fake_message(self, action, **kwargs):
        fn = getattr(self.component, 'do_%s' % action)
        fn(**kwargs)


# testquery.py : CGI script that echoes query parameters.

import time, cgiutil

rawData = cgiutil.getRawCgiData()
params = cgiutil.parseCgiData(rawData)

print "Content-type: text/html"
print
print ""
print ""
print "
Query parameters as of %s
" % time.asctime()
if not params:
    print "
No parameters
"
else:
    print "
%d parameter(s)
" % len(params)
    print '
'
    keys = params.keys()
    keys.sort()
    for k in keys:
        v = cgiutil.htmlEncode('|'.join(params[k]))
        k = cgiutil.htmlEncode(k)
        print "
%s	%s
" % (k, v)
    print "
"
print ""
print ""


// If Redux DevTools Extension is installed use it, otherwise use Redux compose

/* eslint-disable no-underscore-dangle */

const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;

process.env.NODE_ENV !== 'production' &&

/**
 * Create the store with asynchronously loaded reducers
 */

import { createStore, applyMiddleware, compose } from 'redux';
import { fromJS } from 'immutable';
import { routerMiddleware } from 'react-router-redux';
import createSagaMiddleware from 'redux-saga';
import createReducer from './reducers';

const sagaMiddleware = createSagaMiddleware();
const devtools = window.devToolsExtension || (() => (noop) => noop);

export default function configureStore(initialState = {}, history) {
  // Create the store with two middlewares
  // 1. sagaMiddleware: Makes redux-sagas work
  // 2. routerMiddleware: Syncs the location/URL path to the state
  const middlewares = [
    sagaMiddleware,
    routerMiddleware(history),
  ];

  const enhancers = [
    applyMiddleware(...middlewares),
    devtools(),
  ];

  const store = createStore(
    createReducer(),
    fromJS(initialState),
    compose(...enhancers)
  );

  // Extensions
  store.runSaga = sagaMiddleware.run;
  store.asyncReducers = {}; // Async reducer registry

  // Make reducers hot reloadable, see http://mxs.is/googmo
  /* istanbul ignore next */
  if (module.hot) {
    module.hot.accept('./reducers', () => {
      System.import('./reducers').then((reducerModule) => {
        const createReducers = reducerModule.default;
        const nextReducers = createReducers(store.asyncReducers);

        store.replaceReducer(nextReducers);
      });
    });
  }

  return store;
}


/*
 *
 * {{ properCase name }} actions
 *
 */

import {
  DEFAULT_ACTION,
} from './constants';

export function defaultAction() {
  return {
    type: DEFAULT_ACTION,
  };
}


# Gotchas

These are some things to be aware of when using this boilerplate.

## Special images in HTML files

If you specify your images in the `.html` files using the `<img>` tag, everything
will work fine. The problem comes up if you try to include images using anything
except that tag, like meta tags:

```HTML
<meta property="og:image" content="img/yourimg.png" />
```

The webpack `html-loader` does not recognise this as an image file and will not
transfer the image to the build folder. To get webpack to transfer them, you
have to import them with the file loader in your JavaScript somewhere, e.g.:

```JavaScript
import 'file?name=[name].[ext]!../img/yourimg.png';
```

Then webpack will correctly transfer the image to the build folder.


import LanguageProvider from '../index';

import expect from 'expect';
import { shallow } from 'enzyme';
import { FormattedMessage, defineMessages } from 'react-intl';
import configureStore from '../../../store';
import React from 'react';
import { Provider } from 'react-redux';
import { browserHistory } from 'react-router';
import { translationMessages } from '../../../i18n';

describe('<LanguageProvider />', () => {
  let store;

  before(() => {
    store = configureStore({}, browserHistory);
  });

  it('should render the default language messages', () => {
    const messages = defineMessages({
      someMessage: {
        id: 'some.id',
        defaultMessage: 'This is some default message',
      },
    });
    const renderedComponent = shallow(
      <Provider store={store}>
        <LanguageProvider messages={translationMessages}>
          <FormattedMessage {...messages.someMessage} />
        </LanguageProvider>
      </Provider>
    );
    expect(renderedComponent.contains(<FormattedMessage {...messages.someMessage} />)).toEqual(true);
  });
});


import { routerMiddleware } from 'react-router-redux';

import createSagaMiddleware from 'redux-saga';

const sagaMiddleware = createSagaMiddleware();

const devtools = window.devToolsExtension || (() => (noop) => noop);

export default function configureStore(initialState = {}, history) {

// Create the store with two middlewares

keep keep keep keep keep replace keep keep keep


import React from 'react';
import expect from 'expect';
import { shallow } from 'enzyme';

import ListItem from '../ListItem';

describe('<ListItem />', () => {
  it('should render an <li> tag', () => {
    const renderedComponent = shallow(<ListItem />);
    expect(renderedComponent.type()).toEqual('li');
  });

  it('should have a className attribute', () => {
    const renderedComponent = shallow(<ListItem />);
    expect(renderedComponent.prop('className')).toExist();
  });

  it('should adopt a valid attribute', () => {
    const id = 'test';
    const renderedComponent = shallow(<ListItem id={id} />);
    expect(renderedComponent.prop('id')).toEqual(id);
  });

  it('should not adopt an invalid attribute', () => {
    const renderedComponent = shallow(<ListItem attribute={'test'} />);
    expect(renderedComponent.prop('attribute')).toNotExist();
  });
});


# `reselect`

reselect memoizes ("caches") previous state trees and calculations based on said
tree. This means repeated changes and calculations are fast and efficient,
providing us with a performance boost over standard `mapStateToProps`
implementations.

The [official documentation](https://github.com/reactjs/reselect)
offers a good starting point!

## Usage

There are two different kinds of selectors, simple and complex ones.

### Simple selectors

Simple selectors are just that: they take the application state and select a
part of it.

```javascript
const mySelector = (state) => state.get('someState');

export {
  mySelector,
};
```

### Complex selectors

If we need to, we can combine simple selectors to build more complex ones which
get nested state parts with reselect's `createSelector` function. We import other
selectors and pass them to the `createSelector` call:

```javascript
import { createSelector } from 'reselect';
import mySelector from 'mySelector';

const myComplexSelector = createSelector(
  mySelector,
  (myState) => myState.get('someNestedState')
);

export {
  myComplexSelector,
};
```

These selectors can then either be used directly in our containers as
`mapStateToProps` functions or be nested with `createSelector` once again:

```javascript
export default connect(createSelector(
  myComplexSelector,
  (myNestedState) => ({ data: myNestedState })
))(SomeComponent);
```

### Adding a new selector

If you have a `selectors.js` file next to the reducer which's part of the state
you want to select, add your selector to said file. If you don't have one yet,
add a new one into your container folder and fill it with this boilerplate code:

```JS
import { createSelector } from 'reselect';

const selectMyState = () => createSelector(

);

export {
  selectMyState,
};
```

---

_Don't like this feature? [Click here](remove.md)_


# ImmutableJS

Immutable data structures can be deeply compared in no time. This allows us to
efficiently determine if our components need to rerender since we know if the
`props` changed or not!

Check out the [official documentation](https://facebook.github.io/immutable-js/)
for a good explanation of the more intricate benefits it has.

## Usage

In our reducers, we make the initial state an immutable data structure with the
`fromJS` function. We pass it an object or an array, and it takes care of
converting it to a immutable data structure. (Note: the conversion is performed deeply so
that even arbitrarily nested arrays/objects are immutable structures too!)

```JS
import { fromJS } from 'immutable';

const initialState = fromJS({
  myData: {
  	message: 'Hello World!'
  },
});
```

When a reducer is subscribed to an action and needs to return the new state they can do so by using setter methods such as [`.set`](https://facebook.github.io/immutable-js/docs/#/Map/set) and [`.update`](https://facebook.github.io/immutable-js/docs/#/Map/update) and [`.merge`](https://facebook.github.io/immutable-js/docs/#/Map/merge).
If the changing state data is nested, we can utilize the 'deep' versions of these setters: [`.setIn`](https://facebook.github.io/immutable-js/docs/#/Map/setIn) and [`.updateIn`](https://facebook.github.io/immutable-js/docs/#/Map/updateIn), [`.mergeIn`](https://facebook.github.io/immutable-js/docs/#/Map/mergeIn).

```JS
import { SOME_ACTION, SOME_OTHER_ACTION } from './actions';

// […]

function myReducer(state = initialState, action) {
  switch (action.type) {
    case SOME_ACTION:
      return state.set('myData', action.payload);
    case SOME_OTHER_ACTION:
      return state.setIn(['myData', 'message'], action.payload);
    default:
      return state;
  }
}
```

We use [`reselect`](./reselect.md) to efficiently cache our computed application
state. Since that state is now immutable, we need to use the [`.get`](https://facebook.github.io/immutable-js/docs/#/Iterable/get) and [`.getIn`](https://facebook.github.io/immutable-js/docs/#/Iterable/getIn)
functions to select the part we want.

```JS
const myDataSelector = (state) => state.get('myData');
const messageSelector = (state) => state.getIn(['myData', 'message']);

export default myDataSelector;
```

To learn more, check out [`reselect.md`](reselect.md)!

## Immutable Records

ImmutableJS provides a number of immutable structures such as [`Map`](https://facebook.github.io/immutable-js/docs/#/Map), [`Set`](https://facebook.github.io/immutable-js/docs/#/Set) and [`List`](https://facebook.github.io/immutable-js/docs/#/List).
One drawback to these structures is that properties must be accessed via the getter methods (`.get` or `.getIn`) and cannot be accessed with dot notation as they would in a plain javascript object.
For instance you'll write `map.get('property')` instead of `object.property`, and `list.get(0)` instead of `array[0]`.
This can make your code a little harder to follow and requires you to be extra cautious when passing arguments or props to functions or components that try to access values with regular dot notation.
ImmutableJS's [`Record`](https://facebook.github.io/immutable-js/docs/#/Record) structure offers a solution to this issue.

A `Record` is similar to a `Map` but has a fixed shape, meaning it's property keys are predefined and you can't later add a new property after the record is created. Attempting to set new properties will cause an error.
One benefit of `Record` is that you can now, along with other immutable read methods (.get, .set, .merge and so on), use the dot notation to access properties.

The creation of a record is less simple than simply calling `.toJS()`.
First, you have to define the `Record` shape. With the example above, to create your initial state, you'll write:

```JS
// Defining the shape
const StateRecord = Record({
  myData: {
      message: 'Hello World!'
  }
});

const initialState = new StateRecord({}); // initialState is now a new StateRecord instance
                                          // initialized with myData.message set by default as 'Hello World!'
```

Now, if you want to access `myData`, you can just write `state.myData` in your reducer code and to access the `message` property you can write `state.myData.message` as you would in a plain javascript object.

### Gotchas of Using Records

Although dot notation can now be used to read properties the same does not apply to setting properties. Any attempts to set a property on a `Record` using dot notation will result in errors.
Instead setter methods ( `.set`, `.update`, `.merge`) should be used.

Certain properties can not be set on a record as they would conflict with the API. Consider the below example:
```JS
const ProductRecord = Record({
    type: 'tshirt',
    size: 'small'
});
```

Because record.size is used to return the records count (similar to array.length), the above definition would throw an error.


routerMiddleware(history),
];
const enhancers = [
applyMiddleware(...middlewares),
devtools(),
];

keep keep keep keep keep replace keep keep


/**
 *
 * App.react.js
 *
 * This component is the skeleton around the actual pages, and should only
 * contain code that should be seen on all pages. (e.g. navigation bar)
 *
 * NOTE: while this component should technically be a stateless functional
 * component (SFC), hot reloading does not currently support SFCs. If hot
 * reloading is not a necessity for you then you can refactor it and remove
 * the linting exception.
 */

import React from 'react';

export default class App extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function

  static propTypes = {
    children: React.PropTypes.node,
  };

  render() {
    return (
      <div>
        {React.Children.toArray(this.props.children)}
      </div>
    );
  }
}


# Contributing to react-boilerplate

Love react-boilerplate and want to help? Thanks so much, there's something to do for everybody!

Please take a moment to review this document in order to make the contribution process easy and effective for everyone involved.

Following these guidelines helps to communicate that you respect the time of the developers managing and developing this open source project. In return, they should reciprocate that respect in addressing your issue or assessing patches and features.

## Using the issue tracker

The [issue tracker](https://github.com/mxstbr/react-boilerplate/issues) is
the preferred channel for [bug reports](#bugs), [features requests](#features)
and [submitting pull requests](#pull-requests).

## Bug reports

A bug is a _demonstrable problem_ that is caused by the code in the repository.
Good bug reports are extremely helpful - thank you!

Guidelines for bug reports:

1. **Use the GitHub issue search** — check if the issue has already been reported.

2. **Check if the issue has been fixed** — try to reproduce it using the latest `master` or development branch in the repository.

3. **Isolate the problem** — ideally create a [reduced test case](https://css-tricks.com/reduced-test-cases/) and a live example.

A good bug report shouldn't leave others needing to chase you up for more information. Please try to be as detailed as possible in your report. What is your environment? What steps will reproduce the issue? What browser(s) and OS
experience the problem? What would you expect to be the outcome? All these details will help people to fix any potential bugs.

Example:

> Short and descriptive example bug report title
>
> A summary of the issue and the browser/OS environment in which it occurs. If
> suitable, include the steps required to reproduce the bug.
>
> 1. This is the first step
> 2. This is the second step
> 3. Further steps, etc.
>
> `<url>` - a link to the reduced test case
>
> Any other information you want to share that is relevant to the issue being
> reported. This might include the lines of code that you have identified as
> causing the bug, and potential solutions (and your opinions on their
> merits).

## Feature requests

Feature requests are welcome. But take a moment to find out whether your idea fits with the scope and aims of the project. It's up to *you* to make a strong case to convince the project's developers of the merits of this feature. Please provide as much detail and context as possible.

## Pull requests

Good pull requests - patches, improvements, new features - are a fantastic
help. They should remain focused in scope and avoid containing unrelated
commits.

**Please ask first** before embarking on any significant pull request (e.g.
implementing features, refactoring code, porting to a different language),
otherwise you risk spending a lot of time working on something that the
project's developers might not want to merge into the project.

Please adhere to the coding conventions used throughout a project (indentation,
accurate comments, etc.) and any other requirements (such as test coverage).

Since the `master` branch is what people actually use in production, we have a
`dev` branch that unstable changes get merged into first. Only when we
consider that stable we merge it into the `master` branch and release the
changes for real.

Adhering to the following process is the best way to get your work
included in the project:

1. [Fork](https://help.github.com/articles/fork-a-repo/) the project, clone your fork, and configure the remotes:

   ```bash
   # Clone your fork of the repo into the current directory
   git clone https://github.com/<your-username>/react-boilerplate.git
   # Navigate to the newly cloned directory
   cd react-boilerplate
   # Assign the original repo to a remote called "upstream"
   git remote add upstream https://github.com/mxstbr/react-boilerplate.git
   ```

2. If you cloned a while ago, get the latest changes from upstream:

   ```bash
   git checkout dev
   git pull upstream dev
   ```

3. Create a new topic branch (off the `dev` branch) to contain your feature, change, or fix:

   ```bash
   git checkout -b <topic-branch-name>
   ```

4. Commit your changes in logical chunks. Please adhere to these [git commit message guidelines](http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html) or your code is unlikely be merged into the main project. Use Git's [interactive rebase](https://help.github.com/articles/about-git-rebase/) feature to tidy up your commits before making them public.

5. Locally merge (or rebase) the upstream dev branch into your topic branch:

   ```bash
   git pull [--rebase] upstream dev
   ```

6. Push your topic branch up to your fork:

   ```bash
   git push origin <topic-branch-name>
   ```

7. [Open a Pull Request](https://help.github.com/articles/using-pull-requests/)
    with a clear title and description.

**IMPORTANT**: By submitting a patch, you agree to allow the project
owners to license your work under the terms of the [MIT License](https://github.com/mxstbr/react-boilerplate/blob/master/LICENSE.md).


import { fromJS } from 'immutable';
import expect from 'expect';

import {
  selectGlobal,
  selectCurrentUser,
  selectLoading,
  selectError,
  selectRepos,
  selectLocationState,
} from '../selectors';

describe('selectGlobal', () => {
  const globalSelector = selectGlobal();
  it('should select the global state', () => {
    const globalState = fromJS({});
    const mockedState = fromJS({
      global: globalState,
    });
    expect(globalSelector(mockedState)).toEqual(globalState);
  });
});

describe('selectCurrentUser', () => {
  const currentUserSelector = selectCurrentUser();
  it('should select the current user', () => {
    const username = 'mxstbr';
    const mockedState = fromJS({
      global: {
        currentUser: username,
      },
    });
    expect(currentUserSelector(mockedState)).toEqual(username);
  });
});

describe('selectLoading', () => {
  const loadingSelector = selectLoading();
  it('should select the loading', () => {
    const loading = false;
    const mockedState = fromJS({
      global: {
        loading,
      },
    });
    expect(loadingSelector(mockedState)).toEqual(loading);
  });
});

describe('selectError', () => {
  const errorSelector = selectError();
  it('should select the error', () => {
    const error = 404;
    const mockedState = fromJS({
      global: {
        error,
      },
    });
    expect(errorSelector(mockedState)).toEqual(error);
  });
});

describe('selectRepos', () => {
  const reposSelector = selectRepos();
  it('should select the repos', () => {
    const repositories = fromJS([]);
    const mockedState = fromJS({
      global: {
        userData: {
          repositories,
        },
      },
    });
    expect(reposSelector(mockedState)).toEqual(repositories);
  });
});

describe('selectLocationState', () => {
  const locationStateSelector = selectLocationState();
  it('should select the route as a plain JS object', () => {
    const route = fromJS({
      locationBeforeTransitions: null,
    });
    const mockedState = fromJS({
      route,
    });
    expect(locationStateSelector(mockedState)).toEqual(route.toJS());
  });
});


];
const store = createStore(
createReducer(),
fromJS(initialState),

// If Redux DevTools Extension is installed use it, otherwise use Redux compose

/* eslint-disable no-underscore-dangle */


import React from 'react';
import expect from 'expect';
import { shallow } from 'enzyme';

import Wrapper from '../Wrapper';

describe('<Wrapper />', () => {
  it('should render an <div> tag', () => {
    const renderedComponent = shallow(<Wrapper />);
    expect(renderedComponent.type()).toEqual('div');
  });

  it('should have a className attribute', () => {
    const renderedComponent = shallow(<Wrapper />);
    expect(renderedComponent.prop('className')).toExist();
  });

  it('should adopt a valid attribute', () => {
    const id = 'test';
    const renderedComponent = shallow(<Wrapper id={id} />);
    expect(renderedComponent.prop('id')).toEqual(id);
  });

  it('should not adopt an invalid attribute', () => {
    const renderedComponent = shallow(<Wrapper attribute={'test'} />);
    expect(renderedComponent.prop('attribute')).toNotExist();
  });
});


This project is licensed under the MIT license.

Enjoy the best DX and code your app at the speed of thought! Your
    saved changes to the CSS and JS are reflected instantaneously
    without refreshing the page. Preserve application state even when
    you update something in the underlying code!

Complete i18n Standard Internationalization & Pluralization

Scalable apps need to support multiple languages, easily add and support multiple languages with `react-intl`.

Use template strings, object destructuring, arrow functions, JSX
    syntax and more, today.

The next frontier in performant web apps: availability without a
      network connection from the instant your users load the app.

Write composable CSS that's co-located with your components for
    complete modularity. Unique generated class names keep the
    specificity low while eliminating style clashes. Ship only the
    styles that are on the page for the best performance.

Automate the creation of components, containers, routes, selectors
  and sagas - and their tests - right from the CLI!

Unidirectional data flow allows for change logging and time travel
    debugging.

Start your next react project in seconds

A highly scalable, offline-first foundation with the best DX and a focus on performance and best practices


# Testing

- [Unit Testing](unit-testing.md)
- [Component Testing](component-testing.md)
- [Remote Testing](remote-testing.md)

Testing your application is a vital part of serious development. There are a few
things you should test. If you've never done this before start with [unit testing](unit-testing.md).
Move on to [component testing](component-testing.md) when you feel like you
understand that!

We also support [remote testing](remote-testing.md) your local application,
which is quite awesome, so definitely check that out!

## Usage with this boilerplate

To test your application started with this boilerplate do the following:

1. Sprinkle `.test.js` files directly next to the parts of your application you
   want to test. (Or in `test/` subdirectories, it doesn't really matter as long
   as they are directly next to those parts and end in `.test.js`)

1. Write your unit and component tests in those files.

1. Run `npm run test` in your terminal and see all the tests pass! (hopefully)

There are a few more commands related to testing, checkout the [commands documentation](../general/commands.md#testing)
for the full list!


const store = createStore(
createReducer(),
fromJS(initialState),
compose(...enhancers)
);
// Extensions
store.runSaga = sagaMiddleware.run;


import styled from 'styled-components';

const ListItem = styled.li`
  margin: 1em 0;
`;

export default ListItem;


# Don't check auto-generated stuff into git
coverage
build
node_modules
stats.json

# Cruft
.DS_Store
npm-debug.log
.idea


'name': objId, // Both ID and Name needed or swf to identifty itself

// If source was supplied pass as a flash var.

if (source.type && vjs.Flash.isStreamingType(source.type)) {

keep keep keep keep replace replace replace keep keep keep keep keep

module('Flash');

var streamToPartsAndBack = function(url) {
  var parts = vjs.Flash.streamToParts(url);
  return vjs.Flash.streamFromParts(parts.connection, parts.stream);
};

test('test using both streamToParts and streamFromParts', function() {
  ok('rtmp://myurl.com/&isthis' === streamToPartsAndBack('rtmp://myurl.com/isthis'));
  ok('rtmp://myurl.com/&isthis' === streamToPartsAndBack('rtmp://myurl.com/&isthis'));
  ok('rtmp://myurl.com/isthis/&andthis' === streamToPartsAndBack('rtmp://myurl.com/isthis/andthis'));
});

test('test streamToParts', function() {
  var parts = vjs.Flash.streamToParts('http://myurl.com/streaming&/is/fun');
  ok(parts.connection === 'http://myurl.com/streaming');
  ok(parts.stream === '/is/fun');

  parts = vjs.Flash.streamToParts('http://myurl.com/&streaming&/is/fun');
  ok(parts.connection === 'http://myurl.com/');
  ok(parts.stream === 'streaming&/is/fun');

  parts = vjs.Flash.streamToParts('http://myurl.com/streaming/is/fun');
  ok(parts.connection === 'http://myurl.com/streaming/is/');
  ok(parts.stream === 'fun');

  parts = vjs.Flash.streamToParts('whatisgoingonhere');
  ok(parts.connection === 'whatisgoingonhere');
  ok(parts.stream === '');

  parts = vjs.Flash.streamToParts();
  ok(parts.connection === '');
  ok(parts.stream === '');
});

test('test isStreamingSrc', function() {
  var isStreamingSrc = vjs.Flash.isStreamingSrc;
  ok(isStreamingSrc('rtmp://streaming.is/fun'));
  ok(isStreamingSrc('rtmps://streaming.is/fun'));
  ok(isStreamingSrc('rtmpe://streaming.is/fun'));
  ok(isStreamingSrc('rtmpt://streaming.is/fun'));
  // test invalid protocols
  ok(!isStreamingSrc('rtmp:streaming.is/fun'));
  ok(!isStreamingSrc('rtmpz://streaming.is/fun'));
  ok(!isStreamingSrc('http://streaming.is/fun'));
  ok(!isStreamingSrc('https://streaming.is/fun'));
  ok(!isStreamingSrc('file://streaming.is/fun'));
});

test('test canPlaySource', function() {
  var canPlaySource = vjs.Flash.canPlaySource;

  // supported
  ok(canPlaySource({ type: 'video/mp4; codecs=avc1.42E01E,mp4a.40.2' }), 'codecs supported');
  ok(canPlaySource({ type: 'video/mp4' }), 'video/mp4 supported');
  ok(canPlaySource({ type: 'video/x-flv' }), 'video/x-flv supported');
  ok(canPlaySource({ type: 'video/flv' }), 'video/flv supported');
  ok(canPlaySource({ type: 'video/m4v' }), 'video/m4v supported');
  ok(canPlaySource({ type: 'VIDEO/FLV' }), 'capitalized mime type');

  // not supported
  ok(!canPlaySource({ type: 'video/webm; codecs="vp8, vorbis"' }));
  ok(!canPlaySource({ type: 'video/webm' }));
});

test('currentTime is the seek target during seeking', function() {
  var noop = function() {},
      seeking = false,
      parentEl = document.createElement('div'),
      tech = new vjs.Flash({
        id: noop,
        on: noop,
        options_: {}
      }, {
        'parentEl': parentEl
      }),
      currentTime;

  tech.el().vjs_setProperty = function(property, value) {
    if (property === 'currentTime') {
      currentTime = value;
    }
  };
  tech.el().vjs_getProperty = function(name) {
    if (name === 'currentTime') {
      return currentTime;
    } else if (name === 'seeking') {
      return seeking;
    }
  };

  currentTime = 3;
  strictEqual(3, tech.currentTime(), 'currentTime is retreived from the SWF');

  tech['setCurrentTime'](7);
  seeking = true;
  strictEqual(7, tech.currentTime(), 'during seeks the target time is returned');
});


/* Menu
================================================================================ */
/**
 * The Menu component is used to build pop up menus, including subtitle and
 * captions selection menus.
 *
 * @param {vjs.Player|Object} player
 * @param {Object=} options
 * @class
 * @constructor
 */
vjs.Menu = vjs.Component.extend();

/**
 * Add a menu item to the menu
 * @param {Object|String} component Component or component type to add
 */
vjs.Menu.prototype.addItem = function(component){
  this.addChild(component);
  component.on('click', vjs.bind(this, function(){
    this.unlockShowing();
  }));
};

/** @inheritDoc */
vjs.Menu.prototype.createEl = function(){
  var contentElType = this.options().contentElType || 'ul';
  this.contentEl_ = vjs.createEl(contentElType, {
    className: 'vjs-menu-content'
  });
  var el = vjs.Component.prototype.createEl.call(this, 'div', {
    append: this.contentEl_,
    className: 'vjs-menu'
  });
  el.appendChild(this.contentEl_);

  // Prevent clicks from bubbling up. Needed for Menu Buttons,
  // where a click on the parent is significant
  vjs.on(el, 'click', function(event){
    event.preventDefault();
    event.stopImmediatePropagation();
  });

  return el;
};

/**
 * The component for a menu item. `<li>`
 *
 * @param {vjs.Player|Object} player
 * @param {Object=} options
 * @class
 * @constructor
 */
vjs.MenuItem = vjs.Button.extend({
  /** @constructor */
  init: function(player, options){
    vjs.Button.call(this, player, options);
    this.selected(options['selected']);
  }
});

/** @inheritDoc */
vjs.MenuItem.prototype.createEl = function(type, props){
  return vjs.Button.prototype.createEl.call(this, 'li', vjs.obj.merge({
    className: 'vjs-menu-item',
    innerHTML: this.options_['label']
  }, props));
};

/**
 * Handle a click on the menu item, and set it to selected
 */
vjs.MenuItem.prototype.onClick = function(){
  this.selected(true);
};

/**
 * Set this menu item as selected or not
 * @param  {Boolean} selected
 */
vjs.MenuItem.prototype.selected = function(selected){
  if (selected) {
    this.addClass('vjs-selected');
    this.el_.setAttribute('aria-selected',true);
  } else {
    this.removeClass('vjs-selected');
    this.el_.setAttribute('aria-selected',false);
  }
};

/**
 * A button class with a popup menu
 * @param {vjs.Player|Object} player
 * @param {Object=} options
 * @constructor
 */
vjs.MenuButton = vjs.Button.extend({
  /** @constructor */
  init: function(player, options){
    vjs.Button.call(this, player, options);

    this.menu = this.createMenu();

    // Add list to element
    this.addChild(this.menu);

    // Automatically hide empty menu buttons
    if (this.items && this.items.length === 0) {
      this.hide();
    }

    this.on('keyup', this.onKeyPress);
    this.el_.setAttribute('aria-haspopup', true);
    this.el_.setAttribute('role', 'button');
  }
});

/**
 * Track the state of the menu button
 * @type {Boolean}
 * @private
 */
vjs.MenuButton.prototype.buttonPressed_ = false;

vjs.MenuButton.prototype.createMenu = function(){
  var menu = new vjs.Menu(this.player_);

  // Add a title list item to the top
  if (this.options().title) {
    menu.contentEl().appendChild(vjs.createEl('li', {
      className: 'vjs-menu-title',
      innerHTML: vjs.capitalize(this.options().title),
      tabindex: -1
    }));
  }

  this.items = this['createItems']();

  if (this.items) {
    // Add menu items to the menu
    for (var i = 0; i < this.items.length; i++) {
      menu.addItem(this.items[i]);
    }
  }

  return menu;
};

/**
 * Create the list of menu items. Specific to each subclass.
 */
vjs.MenuButton.prototype.createItems = function(){};

/** @inheritDoc */
vjs.MenuButton.prototype.buildCSSClass = function(){
  return this.className + ' vjs-menu-button ' + vjs.Button.prototype.buildCSSClass.call(this);
};

// Focus - Add keyboard functionality to element
// This function is not needed anymore. Instead, the keyboard functionality is handled by
// treating the button as triggering a submenu. When the button is pressed, the submenu
// appears. Pressing the button again makes the submenu disappear.
vjs.MenuButton.prototype.onFocus = function(){};
// Can't turn off list display that we turned on with focus, because list would go away.
vjs.MenuButton.prototype.onBlur = function(){};

vjs.MenuButton.prototype.onClick = function(){
  // When you click the button it adds focus, which will show the menu indefinitely.
  // So we'll remove focus when the mouse leaves the button.
  // Focus is needed for tab navigation.
  this.one('mouseout', vjs.bind(this, function(){
    this.menu.unlockShowing();
    this.el_.blur();
  }));
  if (this.buttonPressed_){
    this.unpressButton();
  } else {
    this.pressButton();
  }
};

vjs.MenuButton.prototype.onKeyPress = function(event){
  event.preventDefault();

  // Check for space bar (32) or enter (13) keys
  if (event.which == 32 || event.which == 13) {
    if (this.buttonPressed_){
      this.unpressButton();
    } else {
      this.pressButton();
    }
  // Check for escape (27) key
  } else if (event.which == 27){
    if (this.buttonPressed_){
      this.unpressButton();
    }
  }
};

vjs.MenuButton.prototype.pressButton = function(){
  this.buttonPressed_ = true;
  this.menu.lockShowing();
  this.el_.setAttribute('aria-pressed', true);
  if (this.items && this.items.length > 0) {
    this.items[0].el().focus(); // set the focus to the title of the submenu
  }
};

vjs.MenuButton.prototype.unpressButton = function(){
  this.buttonPressed_ = false;
  this.menu.unlockShowing();
  this.el_.setAttribute('aria-pressed', false);
};