<commit_before>/**
* See [Demo.js](https://github.com/liabru/matter-js/blob/master/demo/js/Demo.js)
* and [DemoMobile.js](https://github.com/liabru/matter-js/blob/master/demo/js/DemoMobile.js) for usage examples.
*
* @class RenderPixi
*/

var RenderPixi = {};

(function() {

    /**
     * Creates a new Pixi.js WebGL renderer
     * @method create
     * @param {object} options
     * @return {RenderPixi} A new renderer
     */
    RenderPixi.create = function(options) {
        var defaults = {
            controller: RenderPixi,
            element: null,
            canvas: null,
            options: {
                width: 800,
                height: 600,
                background: '#fafafa',
                wireframeBackground: '#222',
                hasBounds: false,
                enabled: true,
                wireframes: true,
                showSleeping: true,
                showDebug: false,
                showBroadphase: false,
                showBounds: false,
                showVelocity: false,
                showCollisions: false,
                showAxes: false,
                showPositions: false,
                showAngleIndicator: false,
                showIds: false,
                showShadows: false
            }
        };

        var render = Common.extend(defaults, options),
            transparent = !render.options.wireframes && render.options.background === 'transparent';

        // init pixi
        render.context = new PIXI.WebGLRenderer(render.options.width, render.options.height, render.canvas, transparent, true);
        render.canvas = render.context.view;
        render.container = new PIXI.DisplayObjectContainer();
        render.stage = new PIXI.Stage();
        render.stage.addChild(render.container);
        render.bounds = render.bounds || {
            min: {
                x: 0,
                y: 0
            },
            max: {
                x: render.options.width,
                y: render.options.height
            }
        };

        // caches
        render.textures = {};
        render.sprites = {};
        render.primitives = {};

        // use a sprite batch for performance
        render.spriteBatch = new PIXI.SpriteBatch();
        render.container.addChild(render.spriteBatch);

        // insert canvas
        if (Common.isElement(render.element)) {
            render.element.appendChild(render.canvas);
        } else {
            Common.log('No "render.element" passed, "render.canvas" was not inserted into document.', 'warn');
        }

        // prevent menus on canvas
        render.canvas.oncontextmenu = function() { return false; };
        render.canvas.onselectstart = function() { return false; };

        return render;
    };

    /**
     * Clears the scene graph
     * @method clear
     * @param {RenderPixi} render
     */
    RenderPixi.clear = function(render) {
        var container = render.container,
            spriteBatch = render.spriteBatch;

        // clear stage container
        while (container.children[0]) {
            container.removeChild(container.children[0]);
        }

        // clear sprite batch
        while (spriteBatch.children[0]) {
            spriteBatch.removeChild(spriteBatch.children[0]);
        }

        var bgSprite = render.sprites['bg-0'];

        // clear caches
        render.textures = {};
        render.sprites = {};
        render.primitives = {};

        // set background sprite
        render.sprites['bg-0'] = bgSprite;
        if (bgSprite)
            spriteBatch.addChildAt(bgSprite, 0);

        // add sprite batch back into container
        render.container.addChild(render.spriteBatch);

        // reset background state
        render.currentBackground = null;

        // reset bounds transforms
        container.scale.set(1, 1);
        container.position.set(0, 0);
    };

    /**
     * Sets the background of the canvas
     * @method setBackground
     * @param {RenderPixi} render
     * @param {string} background
     */
    RenderPixi.setBackground = function(render, background) {
        if (render.currentBackground !== background) {
            var isColor = background.indexOf && background.indexOf('#') !== -1,
                bgSprite = render.sprites['bg-0'];

            if (isColor) {
                // if solid background color
                var color = Common.colorToNumber(background);
                render.stage.setBackgroundColor(color);

                // remove background sprite if existing
                if (bgSprite)
                    render.spriteBatch.removeChild(bgSprite);
            } else {
                // initialise background sprite if needed
                if (!bgSprite) {
                    var texture = _getTexture(render, background);

                    bgSprite = render.sprites['bg-0'] = new PIXI.Sprite(texture);
                    bgSprite.position.x = 0;
                    bgSprite.position.y = 0;
                    render.spriteBatch.addChildAt(bgSprite, 0);
                }
            }

            render.currentBackground = background;
        }
    };

    /**
     * Description
     * @method world
     * @param {engine} engine
     */
    RenderPixi.world = function(engine) {
        var render = engine.render,
            world = engine.world,
            context = render.context,
            stage = render.stage,
            container = render.container,
            options = render.options,
            bodies = Composite.allBodies(world),
            allConstraints = Composite.allConstraints(world),
            constraints = [],
            i;

        if (options.wireframes) {
            RenderPixi.setBackground(render, options.wireframeBackground);
        } else {
            RenderPixi.setBackground(render, options.background);
        }

        // handle bounds
        var boundsWidth = render.bounds.max.x - render.bounds.min.x,
            boundsHeight = render.bounds.max.y - render.bounds.min.y,
            boundsScaleX = boundsWidth / render.options.width,
            boundsScaleY = boundsHeight / render.options.height;

        if (options.hasBounds) {
            // Hide bodies that are not in view
            for (i = 0; i < bodies.length; i++) {
                var body = bodies[i];
                body.render.sprite.visible = Bounds.overlaps(body.bounds, render.bounds);
            }

            // filter out constraints that are not in view
            for (i = 0; i < allConstraints.length; i++) {
                var constraint = allConstraints[i],
                    bodyA = constraint.bodyA,
                    bodyB = constraint.bodyB,
                    pointAWorld = constraint.pointA,
                    pointBWorld = constraint.pointB;

                if (bodyA) pointAWorld = Vector.add(bodyA.position, constraint.pointA);
                if (bodyB) pointBWorld = Vector.add(bodyB.position, constraint.pointB);

                if (!pointAWorld || !pointBWorld)
                    continue;

                if (Bounds.contains(render.bounds, pointAWorld) || Bounds.contains(render.bounds, pointBWorld))
                    constraints.push(constraint);
            }

            // transform the view
            container.scale.set(1 / boundsScaleX, 1 / boundsScaleY);
            container.position.set(-render.bounds.min.x * (1 / boundsScaleX), -render.bounds.min.y * (1 / boundsScaleY));
        } else {
            constraints = allConstraints;
        }

        for (i = 0; i < bodies.length; i++)
            RenderPixi.body(engine, bodies[i]);

        for (i = 0; i < constraints.length; i++)
            RenderPixi.constraint(engine, constraints[i]);

        context.render(stage);
    };

    /**
     * Description
     * @method constraint
     * @param {engine} engine
     * @param {constraint} constraint
     */
    RenderPixi.constraint = function(engine, constraint) {
        var render = engine.render,
            bodyA = constraint.bodyA,
            bodyB = constraint.bodyB,
            pointA = constraint.pointA,
            pointB = constraint.pointB,
            container = render.container,
            constraintRender = constraint.render,
            primitiveId = 'c-' + constraint.id,
            primitive = render.primitives[primitiveId];

        // initialise constraint primitive if not existing
        if (!primitive)
            primitive = render.primitives[primitiveId] = new PIXI.Graphics();

        // don't render if constraint does not have two end points
        if (!constraintRender.visible || !constraint.pointA || !constraint.pointB) {
            primitive.clear();
            return;
        }

        // add to scene graph if not already there
        if (Common.indexOf(container.children, primitive) === -1)
            container.addChild(primitive);

        // render the constraint on every update, since they can change dynamically
        primitive.clear();
        primitive.beginFill(0, 0);
        primitive.lineStyle(constraintRender.lineWidth, Common.colorToNumber(constraintRender.strokeStyle), 1);

        if (bodyA) {
            primitive.moveTo(bodyA.position.x + pointA.x, bodyA.position.y + pointA.y);
        } else {
            primitive.moveTo(pointA.x, pointA.y);
        }

        if (bodyB) {
            primitive.lineTo(bodyB.position.x + pointB.x, bodyB.position.y + pointB.y);
        } else {
            primitive.lineTo(pointB.x, pointB.y);
        }

        primitive.endFill();
    };

    /**
     * Description
     * @method body
     * @param {engine} engine
     * @param {body} body
     */
    RenderPixi.body = function(engine, body) {
        var render = engine.render,
            bodyRender = body.render;

        if (!bodyRender.visible)
            return;

        if (bodyRender.sprite && bodyRender.sprite.texture) {
            var spriteId = 'b-' + body.id,
                sprite = render.sprites[spriteId],
                spriteBatch = render.spriteBatch;

            // initialise body sprite if not existing
            if (!sprite)
                sprite = render.sprites[spriteId] = _createBodySprite(render, body);

            // add to scene graph if not already there
            if (Common.indexOf(spriteBatch.children, sprite) === -1)
                spriteBatch.addChild(sprite);

            // update body sprite
            sprite.position.x = body.position.x;
            sprite.position.y = body.position.y;
            sprite.rotation = body.angle;
            sprite.scale.x = bodyRender.sprite.xScale || 1;
            sprite.scale.y = bodyRender.sprite.yScale || 1;
        } else {
            var primitiveId = 'b-' + body.id,
                primitive = render.primitives[primitiveId],
                container = render.container;

            // initialise body primitive if not existing
            if (!primitive) {
                primitive = render.primitives[primitiveId] = _createBodyPrimitive(render, body);
                primitive.initialAngle = body.angle;
            }

            // add to scene graph if not already there
            if (Common.indexOf(container.children, primitive) === -1)
                container.addChild(primitive);

            // update body primitive
            primitive.position.x = body.position.x;
            primitive.position.y = body.position.y;
            primitive.rotation = body.angle - primitive.initialAngle;
        }
    };

    /**
     * Creates a body sprite
     * @method _createBodySprite
     * @private
     * @param {RenderPixi} render
     * @param {body} body
     * @return {PIXI.Sprite} sprite
     */
    var _createBodySprite = function(render, body) {
        var bodyRender = body.render,
            texturePath = bodyRender.sprite.texture,
            texture = _getTexture(render, texturePath),
            sprite = new PIXI.Sprite(texture);

        sprite.anchor.x = 0.5;
        sprite.anchor.y = 0.5;

        return sprite;
    };

    /**
     * Creates a body primitive
     * @method _createBodyPrimitive
     * @private
     * @param {RenderPixi} render
     * @param {body} body
     * @return {PIXI.Graphics} graphics
     */
    var _createBodyPrimitive = function(render, body) {
        var bodyRender = body.render,
            options = render.options,
            primitive = new PIXI.Graphics();

        primitive.clear();

        if (!options.wireframes) {
            primitive.beginFill(Common.colorToNumber(bodyRender.fillStyle), 1);
            primitive.lineStyle(body.render.lineWidth, Common.colorToNumber(bodyRender.strokeStyle), 1);
        } else {
            primitive.beginFill(0, 0);
            primitive.lineStyle(1, Common.colorToNumber('#bbb'), 1);
        }

        primitive.moveTo(body.vertices[0].x - body.position.x, body.vertices[0].y - body.position.y);

        for (var j = 1; j < body.vertices.length; j++) {
            primitive.lineTo(body.vertices[j].x - body.position.x, body.vertices[j].y - body.position.y);
        }

        primitive.lineTo(body.vertices[0].x - body.position.x, body.vertices[0].y - body.position.y);

        primitive.endFill();

        // angle indicator
        if (options.showAngleIndicator || options.showAxes) {
            primitive.beginFill(0, 0);

            if (options.wireframes) {
                primitive.lineStyle(1, Common.colorToNumber('#CD5C5C'), 1);
            } else {
                primitive.lineStyle(1, Common.colorToNumber(body.render.strokeStyle));
            }

            primitive.moveTo(0, 0);
            primitive.lineTo(((body.vertices[0].x + body.vertices[body.vertices.length-1].x) / 2) - body.position.x,
                             ((body.vertices[0].y + body.vertices[body.vertices.length-1].y) / 2) - body.position.y);

            primitive.endFill();
        }

        return primitive;
    };

    /**
     * Gets the requested texture (a PIXI.Texture) via its path
     * @method _getTexture
     * @private
     * @param {RenderPixi} render
     * @param {string} imagePath
     * @return {PIXI.Texture} texture
     */
    var _getTexture = function(render, imagePath) {
        var texture = render.textures[imagePath];

        if (!texture)
            texture = render.textures[imagePath] = PIXI.Texture.fromImage(imagePath);

        return texture;
    };

})();
<commit_msg>fixed RenderPixi for compound bodies<commit_after>/**
* See [Demo.js](https://github.com/liabru/matter-js/blob/master/demo/js/Demo.js)
* and [DemoMobile.js](https://github.com/liabru/matter-js/blob/master/demo/js/DemoMobile.js) for usage examples.
*
* @class RenderPixi
*/

var RenderPixi = {};

(function() {

    /**
     * Creates a new Pixi.js WebGL renderer
     * @method create
     * @param {object} options
     * @return {RenderPixi} A new renderer
     */
    RenderPixi.create = function(options) {
        var defaults = {
            controller: RenderPixi,
            element: null,
            canvas: null,
            options: {
                width: 800,
                height: 600,
                background: '#fafafa',
                wireframeBackground: '#222',
                hasBounds: false,
                enabled: true,
                wireframes: true,
                showSleeping: true,
                showDebug: false,
                showBroadphase: false,
                showBounds: false,
                showVelocity: false,
                showCollisions: false,
                showAxes: false,
                showPositions: false,
                showAngleIndicator: false,
                showIds: false,
                showShadows: false
            }
        };

        var render = Common.extend(defaults, options),
            transparent = !render.options.wireframes && render.options.background === 'transparent';

        // init pixi
        render.context = new PIXI.WebGLRenderer(render.options.width, render.options.height, render.canvas, transparent, true);
        render.canvas = render.context.view;
        render.container = new PIXI.DisplayObjectContainer();
        render.stage = new PIXI.Stage();
        render.stage.addChild(render.container);
        render.bounds = render.bounds || {
            min: {
                x: 0,
                y: 0
            },
            max: {
                x: render.options.width,
                y: render.options.height
            }
        };

        // caches
        render.textures = {};
        render.sprites = {};
        render.primitives = {};

        // use a sprite batch for performance
        render.spriteBatch = new PIXI.SpriteBatch();
        render.container.addChild(render.spriteBatch);

        // insert canvas
        if (Common.isElement(render.element)) {
            render.element.appendChild(render.canvas);
        } else {
            Common.log('No "render.element" passed, "render.canvas" was not inserted into document.', 'warn');
        }

        // prevent menus on canvas
        render.canvas.oncontextmenu = function() { return false; };
        render.canvas.onselectstart = function() { return false; };

        return render;
    };

    /**
     * Clears the scene graph
     * @method clear
     * @param {RenderPixi} render
     */
    RenderPixi.clear = function(render) {
        var container = render.container,
            spriteBatch = render.spriteBatch;

        // clear stage container
        while (container.children[0]) {
            container.removeChild(container.children[0]);
        }

        // clear sprite batch
        while (spriteBatch.children[0]) {
            spriteBatch.removeChild(spriteBatch.children[0]);
        }

        var bgSprite = render.sprites['bg-0'];

        // clear caches
        render.textures = {};
        render.sprites = {};
        render.primitives = {};

        // set background sprite
        render.sprites['bg-0'] = bgSprite;
        if (bgSprite)
            spriteBatch.addChildAt(bgSprite, 0);

        // add sprite batch back into container
        render.container.addChild(render.spriteBatch);

        // reset background state
        render.currentBackground = null;

        // reset bounds transforms
        container.scale.set(1, 1);
        container.position.set(0, 0);
    };

    /**
     * Sets the background of the canvas
     * @method setBackground
     * @param {RenderPixi} render
     * @param {string} background
     */
    RenderPixi.setBackground = function(render, background) {
        if (render.currentBackground !== background) {
            var isColor = background.indexOf && background.indexOf('#') !== -1,
                bgSprite = render.sprites['bg-0'];

            if (isColor) {
                // if solid background color
                var color = Common.colorToNumber(background);
                render.stage.setBackgroundColor(color);

                // remove background sprite if existing
                if (bgSprite)
                    render.spriteBatch.removeChild(bgSprite);
            } else {
                // initialise background sprite if needed
                if (!bgSprite) {
                    var texture = _getTexture(render, background);

                    bgSprite = render.sprites['bg-0'] = new PIXI.Sprite(texture);
                    bgSprite.position.x = 0;
                    bgSprite.position.y = 0;
                    render.spriteBatch.addChildAt(bgSprite, 0);
                }
            }

            render.currentBackground = background;
        }
    };

    /**
     * Description
     * @method world
     * @param {engine} engine
     */
    RenderPixi.world = function(engine) {
        var render = engine.render,
            world = engine.world,
            context = render.context,
            stage = render.stage,
            container = render.container,
            options = render.options,
            bodies = Composite.allBodies(world),
            allConstraints = Composite.allConstraints(world),
            constraints = [],
            i;

        if (options.wireframes) {
            RenderPixi.setBackground(render, options.wireframeBackground);
        } else {
            RenderPixi.setBackground(render, options.background);
        }

        // handle bounds
        var boundsWidth = render.bounds.max.x - render.bounds.min.x,
            boundsHeight = render.bounds.max.y - render.bounds.min.y,
            boundsScaleX = boundsWidth / render.options.width,
            boundsScaleY = boundsHeight / render.options.height;

        if (options.hasBounds) {
            // Hide bodies that are not in view
            for (i = 0; i < bodies.length; i++) {
                var body = bodies[i];
                body.render.sprite.visible = Bounds.overlaps(body.bounds, render.bounds);
            }

            // filter out constraints that are not in view
            for (i = 0; i < allConstraints.length; i++) {
                var constraint = allConstraints[i],
                    bodyA = constraint.bodyA,
                    bodyB = constraint.bodyB,
                    pointAWorld = constraint.pointA,
                    pointBWorld = constraint.pointB;

                if (bodyA) pointAWorld = Vector.add(bodyA.position, constraint.pointA);
                if (bodyB) pointBWorld = Vector.add(bodyB.position, constraint.pointB);

                if (!pointAWorld || !pointBWorld)
                    continue;

                if (Bounds.contains(render.bounds, pointAWorld) || Bounds.contains(render.bounds, pointBWorld))
                    constraints.push(constraint);
            }

            // transform the view
            container.scale.set(1 / boundsScaleX, 1 / boundsScaleY);
            container.position.set(-render.bounds.min.x * (1 / boundsScaleX), -render.bounds.min.y * (1 / boundsScaleY));
        } else {
            constraints = allConstraints;
        }

        for (i = 0; i < bodies.length; i++)
            RenderPixi.body(engine, bodies[i]);

        for (i = 0; i < constraints.length; i++)
            RenderPixi.constraint(engine, constraints[i]);

        context.render(stage);
    };

    /**
     * Description
     * @method constraint
     * @param {engine} engine
     * @param {constraint} constraint
     */
    RenderPixi.constraint = function(engine, constraint) {
        var render = engine.render,
            bodyA = constraint.bodyA,
            bodyB = constraint.bodyB,
            pointA = constraint.pointA,
            pointB = constraint.pointB,
            container = render.container,
            constraintRender = constraint.render,
            primitiveId = 'c-' + constraint.id,
            primitive = render.primitives[primitiveId];

        // initialise constraint primitive if not existing
        if (!primitive)
            primitive = render.primitives[primitiveId] = new PIXI.Graphics();

        // don't render if constraint does not have two end points
        if (!constraintRender.visible || !constraint.pointA || !constraint.pointB) {
            primitive.clear();
            return;
        }

        // add to scene graph if not already there
        if (Common.indexOf(container.children, primitive) === -1)
            container.addChild(primitive);

        // render the constraint on every update, since they can change dynamically
        primitive.clear();
        primitive.beginFill(0, 0);
        primitive.lineStyle(constraintRender.lineWidth, Common.colorToNumber(constraintRender.strokeStyle), 1);

        if (bodyA) {
            primitive.moveTo(bodyA.position.x + pointA.x, bodyA.position.y + pointA.y);
        } else {
            primitive.moveTo(pointA.x, pointA.y);
        }

        if (bodyB) {
            primitive.lineTo(bodyB.position.x + pointB.x, bodyB.position.y + pointB.y);
        } else {
            primitive.lineTo(pointB.x, pointB.y);
        }

        primitive.endFill();
    };

    /**
     * Description
     * @method body
     * @param {engine} engine
     * @param {body} body
     */
    RenderPixi.body = function(engine, body) {
        var render = engine.render,
            bodyRender = body.render;

        if (!bodyRender.visible)
            return;

        if (bodyRender.sprite && bodyRender.sprite.texture) {
            var spriteId = 'b-' + body.id,
                sprite = render.sprites[spriteId],
                spriteBatch = render.spriteBatch;

            // initialise body sprite if not existing
            if (!sprite)
                sprite = render.sprites[spriteId] = _createBodySprite(render, body);

            // add to scene graph if not already there
            if (Common.indexOf(spriteBatch.children, sprite) === -1)
                spriteBatch.addChild(sprite);

            // update body sprite
            sprite.position.x = body.position.x;
            sprite.position.y = body.position.y;
            sprite.rotation = body.angle;
            sprite.scale.x = bodyRender.sprite.xScale || 1;
            sprite.scale.y = bodyRender.sprite.yScale || 1;
        } else {
            var primitiveId = 'b-' + body.id,
                primitive = render.primitives[primitiveId],
                container = render.container;

            // initialise body primitive if not existing
            if (!primitive) {
                primitive = render.primitives[primitiveId] = _createBodyPrimitive(render, body);
                primitive.initialAngle = body.angle;
            }

            // add to scene graph if not already there
            if (Common.indexOf(container.children, primitive) === -1)
                container.addChild(primitive);

            // update body primitive
            primitive.position.x = body.position.x;
            primitive.position.y = body.position.y;
            primitive.rotation = body.angle - primitive.initialAngle;
        }
    };

    /**
     * Creates a body sprite
     * @method _createBodySprite
     * @private
     * @param {RenderPixi} render
     * @param {body} body
     * @return {PIXI.Sprite} sprite
     */
    var _createBodySprite = function(render, body) {
        var bodyRender = body.render,
            texturePath = bodyRender.sprite.texture,
            texture = _getTexture(render, texturePath),
            sprite = new PIXI.Sprite(texture);

        sprite.anchor.x = 0.5;
        sprite.anchor.y = 0.5;

        return sprite;
    };

    /**
     * Creates a body primitive
     * @method _createBodyPrimitive
     * @private
     * @param {RenderPixi} render
     * @param {body} body
     * @return {PIXI.Graphics} graphics
     */
    var _createBodyPrimitive = function(render, body) {
        var bodyRender = body.render,
            options = render.options,
            primitive = new PIXI.Graphics(),
            fillStyle = Common.colorToNumber(bodyRender.fillStyle),
            strokeStyle = Common.colorToNumber(bodyRender.strokeStyle),
            strokeStyleIndicator = Common.colorToNumber(bodyRender.strokeStyle),
            strokeStyleWireframe = Common.colorToNumber('#bbb'),
            strokeStyleWireframeIndicator = Common.colorToNumber('#CD5C5C'),
            part;

        primitive.clear();

        // handle compound parts
        for (var k = body.parts.length > 1 ? 1 : 0; k < body.parts.length; k++) {
            part = body.parts[k];

            if (!options.wireframes) {
                primitive.beginFill(fillStyle, 1);
                primitive.lineStyle(bodyRender.lineWidth, strokeStyle, 1);
            } else {
                primitive.beginFill(0, 0);
                primitive.lineStyle(1, strokeStyleWireframe, 1);
            }

            primitive.moveTo(part.vertices[0].x - body.position.x, part.vertices[0].y - body.position.y);

            for (var j = 1; j < part.vertices.length; j++) {
                primitive.lineTo(part.vertices[j].x - body.position.x, part.vertices[j].y - body.position.y);
            }

            primitive.lineTo(part.vertices[0].x - body.position.x, part.vertices[0].y - body.position.y);

            primitive.endFill();

            // angle indicator
            if (options.showAngleIndicator || options.showAxes) {
                primitive.beginFill(0, 0);

                if (options.wireframes) {
                    primitive.lineStyle(1, strokeStyleWireframeIndicator, 1);
                } else {
                    primitive.lineStyle(1, strokeStyleIndicator);
                }

                primitive.moveTo(part.position.x - body.position.x, part.position.y - body.position.y);
                primitive.lineTo(((part.vertices[0].x + part.vertices[part.vertices.length-1].x) / 2 - body.position.x),
                                 ((part.vertices[0].y + part.vertices[part.vertices.length-1].y) / 2 - body.position.y));

                primitive.endFill();
            }
        }

        return primitive;
    };

    /**
     * Gets the requested texture (a PIXI.Texture) via its path
     * @method _getTexture
     * @private
     * @param {RenderPixi} render
     * @param {string} imagePath
     * @return {PIXI.Texture} texture
     */
    var _getTexture = function(render, imagePath) {
        var texture = render.textures[imagePath];

        if (!texture)
            texture = render.textures[imagePath] = PIXI.Texture.fromImage(imagePath);

        return texture;
    };

})();
<|endoftext|>


<commit_before>var cadence = require('cadence')
var url = require('url')
var typer = require('media-typer')
var assert = require('assert')
var Delta = require('delta')
var slice = [].slice
var logger = require('prolific').createLogger('bigeasy.vizsla')
var transport = {
    HTTP: require('./http'),
    Mock: require('./mock')
}
var interrupt = require('interrupt/redux').createInterrupter('bigeasy.vizsla')

function UserAgent (middleware) {
    this._tokens = {}
    this._transport = middleware ? new transport.Mock(middleware) : new transport.HTTP
}

UserAgent.prototype.fetch = cadence(function (async) {
    var request = {
        options: { headers: {} }
    }

    function override (object) {
        if (Array.isArray(object)) {
            object.forEach(override)
        } else {
            for (var key in object) {
                if (key == 'url') {
                    if (request.options.url) {
                        request.options.url = url.resolve(request.options.url, object.url)
                    } else {
                        request.options[key] = object[key]
                        request.baseUrl = url.parse(object.url)
                    }
                } else if (key == 'headers') {
                    for (var header in object.headers) {
                        request.options.headers[header.toLowerCase()] = object.headers[header]
                    }
                } else if (/^(?:context|body|payload|grant|token|timeout|post|put|raise|nullify)$/.test(key)) {
                    request[key] = object[key]
                } else {
                    request.options[key] = object[key]
                }
            }
        }
    }

    slice.call(arguments, 1).forEach(override)
    if (request.put) {
        request.payload = request.put
        request.options.method = 'PUT'
    } else if (request.post) {
        request.payload = request.post
        request.options.method = 'POST'
    } else if (request.body) {
        request.payload = request.body
    }
    if (!request.options.method) {
        request.options.method = request.payload ? 'POST' : 'GET'
    }
    if (request.payload && !request.options.headers['content-type']) {
        request.options.headers['content-type'] = 'application/json'
    }
    request.options.headers['accept'] = 'application/json'
    request.url = url.parse(request.options.url)

    if (!request.options.socketPath) {
        request.options.hostname = request.url.hostname
        request.options.port = request.url.port
    }
    request.options.path = url.format({
        pathname: request.url.pathname,
        search: request.url.search,
        hash: request.url.hash
    })

    request.key = request.url.hostname + ':' + request.url.port

    if (request.grant == 'cc') {
        request.token = this._tokens[request.key]
    }
    var sent = {
        options: request.options,
        body: request.payload,
        when: Date.now(),
        duration: null
    }

    async(function () {
        if (request.grant == 'cc' && !request.token) {
            assert.ok(request.baseUrl.auth)
            async(function () {
                this.fetch({
                    url: url.format(request.url),
                    ca: request.options.ca,
                    rejectUnauthorized: request.options.rejectUnauthorized,
                    timeout: request.timeout
                }, {
                    url: '/token',
                    headers: {
                        authorization: 'Basic ' + new Buffer(request.baseUrl.auth).toString('base64')
                    },
                    payload: {
                        grant_type: 'client_credentials'
                    }
                }, async())
            }, function (body, response) {
                if (body.token_type == 'Bearer' && body.access_token) {
                    request.token = this._tokens[request.key] = body.access_token
                }
            })
        } else {
            return [ null, { statusCode: 200 } ]
        }
    }, function (body, response) {
        if (Math.floor(response.statusCode / 100) != 2) return
        var http, options = {}
        if (request.token) {
            request.options.headers.authorization = 'Bearer ' + request.token
        }
        for (var key in request.options) {
            if (key == 'ca' || key == 'agent') {
                options[key] = true
            } else {
                options[key] = request.options[key]
            }
        }
        logger.debug('request', {
            url: request.url,
            options: options,
            sent: request.payload
        })
        if (request.payload && !Buffer.isBuffer(request.payload)) {
            request.payload = new Buffer(JSON.stringify(request.payload))
        }
        if (request.payload) {
            request.options.headers['content-length'] = request.payload.length
        }
        async([function () {
            this._transport.send(request, async())
        }, function (error) {
            sent.duration = Date.now() - sent.when
            var body = new Buffer(JSON.stringify({ message: error.message, errno: error.code }))
            var response = {
                statusCode: 599,
                errno: error.code,
                okay: false,
                sent: sent,
                headers: {
                    'content-length': body.length,
                    'content-type': 'application/json'
                }
            }
            logger.debug('response', {
                status: 'exceptional',
                options: request.options,
                sent: request.payload,
                received: JSON.parse(body.toString()),
                statusCode: response.statusCode,
                headers: response.headers
            })
            if (request.raise) {
                throw interrupt('fetch', {
                    url: url,
                    statusCode: response.statusCode,
                    headers: {
                        sent: request.headers
                    },
                    cause: error
                }, {
                    response: response,
                    parsed: JSON.parse(body.toString()),
                    body: body
                })
            } else if (request.nullify) {
                return [ async.break, null, response, body ]
            }
            return [ async.break, JSON.parse(body.toString()), response, body ]
        }], function (response) {
            var chunks = []
            async(function () {
                new Delta(async()).ee(response)
                     .on('data', function (chunk) { chunks.push(chunk) })
                     .on('end')
            }, function () {
                sent.duration = Date.now() - sent.when
                response.sent = sent
                var parsed = null
                var body = Buffer.concat(chunks)
                var parsed = body
                var display = null
                var type = typer.parse(response.headers['content-type'] || 'application/octet-stream')
                switch (type.type + '/' + type.subtype) {
                case 'application/json':
                    try {
                        display = parsed = JSON.parse(body.toString())
                    } catch (e) {
                        display = body.toString()
                    }
                    break
                case 'text/html':
                case 'text/plain':
                    display = body.toString()
                    break
                }
                response.okay = Math.floor(response.statusCode / 100) == 2
                logger.debug('response', {
                    status: 'responded',
                    options: request.options,
                    sent: request.payload,
                    received: display,
                    parsed: parsed,
                    statusCode: response.statusCode,
                    headers: response.headers
                })
                if (request.grant == 'cc' && response.statusCode == 401) {
                    delete this._tokens[request.key]
                }
                if (!response.okay) {
                    if (request.raise) {
                        throw interrupt('fetch', {
                            url: url,
                            statusCode: response.statusCode,
                            headers: {
                                sent: request.headers,
                                received: response.headers,
                            }
                        }, {
                            response: response,
                            parsed: parsed,
                            body: body
                        })
                    } else if (request.nullify) {
                        return [ null, response, body ]
                    }
                }
                return [ parsed, response, body ]
            })
        })
    })
})

UserAgent.prototype.lookupToken = function (location) {
    location = url.parse(location)
    return this._tokens[location.hostname + ':' + location.port]
}

module.exports = UserAgent
<commit_msg>Tidy error message context.<commit_after>var cadence = require('cadence')
var url = require('url')
var typer = require('media-typer')
var assert = require('assert')
var Delta = require('delta')
var slice = [].slice
var logger = require('prolific').createLogger('bigeasy.vizsla')
var transport = {
    HTTP: require('./http'),
    Mock: require('./mock')
}
var interrupt = require('interrupt/redux').createInterrupter('bigeasy.vizsla')

function UserAgent (middleware) {
    this._tokens = {}
    this._transport = middleware ? new transport.Mock(middleware) : new transport.HTTP
}

UserAgent.prototype.fetch = cadence(function (async) {
    var request = {
        options: { headers: {} }
    }

    function override (object) {
        if (Array.isArray(object)) {
            object.forEach(override)
        } else {
            for (var key in object) {
                if (key == 'url') {
                    if (request.options.url) {
                        request.options.url = url.resolve(request.options.url, object.url)
                    } else {
                        request.options[key] = object[key]
                        request.baseUrl = url.parse(object.url)
                    }
                } else if (key == 'headers') {
                    for (var header in object.headers) {
                        request.options.headers[header.toLowerCase()] = object.headers[header]
                    }
                } else if (/^(?:context|body|payload|grant|token|timeout|post|put|raise|nullify)$/.test(key)) {
                    request[key] = object[key]
                } else {
                    request.options[key] = object[key]
                }
            }
        }
    }

    slice.call(arguments, 1).forEach(override)
    if (request.put) {
        request.payload = request.put
        request.options.method = 'PUT'
    } else if (request.post) {
        request.payload = request.post
        request.options.method = 'POST'
    } else if (request.body) {
        request.payload = request.body
    }
    if (!request.options.method) {
        request.options.method = request.payload ? 'POST' : 'GET'
    }
    if (request.payload && !request.options.headers['content-type']) {
        request.options.headers['content-type'] = 'application/json'
    }
    request.options.headers['accept'] = 'application/json'
    request.url = url.parse(request.options.url)

    if (!request.options.socketPath) {
        request.options.hostname = request.url.hostname
        request.options.port = request.url.port
    }
    request.options.path = url.format({
        pathname: request.url.pathname,
        search: request.url.search,
        hash: request.url.hash
    })

    request.key = request.url.hostname + ':' + request.url.port

    if (request.grant == 'cc') {
        request.token = this._tokens[request.key]
    }
    var sent = {
        options: request.options,
        body: request.payload,
        when: Date.now(),
        duration: null
    }

    async(function () {
        if (request.grant == 'cc' && !request.token) {
            assert.ok(request.baseUrl.auth)
            async(function () {
                this.fetch({
                    url: url.format(request.url),
                    ca: request.options.ca,
                    rejectUnauthorized: request.options.rejectUnauthorized,
                    timeout: request.timeout
                }, {
                    url: '/token',
                    headers: {
                        authorization: 'Basic ' + new Buffer(request.baseUrl.auth).toString('base64')
                    },
                    payload: {
                        grant_type: 'client_credentials'
                    }
                }, async())
            }, function (body, response) {
                if (body.token_type == 'Bearer' && body.access_token) {
                    request.token = this._tokens[request.key] = body.access_token
                }
            })
        } else {
            return [ null, { statusCode: 200 } ]
        }
    }, function (body, response) {
        if (Math.floor(response.statusCode / 100) != 2) return
        var http, options = {}
        if (request.token) {
            request.options.headers.authorization = 'Bearer ' + request.token
        }
        for (var key in request.options) {
            if (key == 'ca' || key == 'agent') {
                options[key] = true
            } else {
                options[key] = request.options[key]
            }
        }
        logger.debug('request', {
            url: request.url,
            options: options,
            sent: request.payload
        })
        if (request.payload && !Buffer.isBuffer(request.payload)) {
            request.payload = new Buffer(JSON.stringify(request.payload))
        }
        if (request.payload) {
            request.options.headers['content-length'] = request.payload.length
        }
        async([function () {
            this._transport.send(request, async())
        }, function (error) {
            sent.duration = Date.now() - sent.when
            var body = new Buffer(JSON.stringify({ message: error.message, errno: error.code }))
            var response = {
                statusCode: 599,
                errno: error.code,
                okay: false,
                sent: sent,
                headers: {
                    'content-length': body.length,
                    'content-type': 'application/json'
                }
            }
            logger.debug('response', {
                status: 'exceptional',
                options: request.options,
                sent: request.payload,
                received: JSON.parse(body.toString()),
                statusCode: response.statusCode,
                headers: response.headers
            })
            if (request.raise) {
                throw interrupt('fetch', {
                    url: request.options.url,
                    statusCode: response.statusCode,
                    headers: {
                        sent: request.options.headers
                    },
                    cause: error
                }, {
                    response: response,
                    parsed: JSON.parse(body.toString()),
                    body: body
                })
            } else if (request.nullify) {
                return [ async.break, null, response, body ]
            }
            return [ async.break, JSON.parse(body.toString()), response, body ]
        }], function (response) {
            var chunks = []
            async(function () {
                new Delta(async()).ee(response)
                     .on('data', function (chunk) { chunks.push(chunk) })
                     .on('end')
            }, function () {
                sent.duration = Date.now() - sent.when
                response.sent = sent
                var parsed = null
                var body = Buffer.concat(chunks)
                var parsed = body
                var display = null
                var type = typer.parse(response.headers['content-type'] || 'application/octet-stream')
                switch (type.type + '/' + type.subtype) {
                case 'application/json':
                    try {
                        display = parsed = JSON.parse(body.toString())
                    } catch (e) {
                        display = body.toString()
                    }
                    break
                case 'text/html':
                case 'text/plain':
                    display = body.toString()
                    break
                }
                response.okay = Math.floor(response.statusCode / 100) == 2
                logger.debug('response', {
                    status: 'responded',
                    options: request.options,
                    sent: request.payload,
                    received: display,
                    parsed: parsed,
                    statusCode: response.statusCode,
                    headers: response.headers
                })
                if (request.grant == 'cc' && response.statusCode == 401) {
                    delete this._tokens[request.key]
                }
                if (!response.okay) {
                    if (request.raise) {
                        throw interrupt('fetch', {
                            url: request.options.url,
                            statusCode: response.statusCode,
                            headers: {
                                sent: request.options.headers,
                                received: response.headers,
                            }
                        }, {
                            response: response,
                            parsed: parsed,
                            body: body
                        })
                    } else if (request.nullify) {
                        return [ null, response, body ]
                    }
                }
                return [ parsed, response, body ]
            })
        })
    })
})

UserAgent.prototype.lookupToken = function (location) {
    location = url.parse(location)
    return this._tokens[location.hostname + ':' + location.port]
}

module.exports = UserAgent
<|endoftext|>


<commit_before>(function () {
  function VueRx (Vue, Rx) {
    var warn = Vue.util.warn || function () {}

    function hasRx (vm) {
      if (!Rx) {
        warn(
          '$watchAsObservable requires Rx to be present globally or ' +
          'be passed to Vue.use() as the second argument.',
          vm
        )
        return false
      }
      return true
    }
    function unsub(handle) {
      if(!handle){return}
      if (handle.dispose) {
        handle.dispose()
      } else if (handle.unsubscribe) {
        handle.unsubscribe()
      }
    }
    function getDisposable(target) {
      if (Rx.Subscription) { // Rx5
        return new Rx.Subscription(target)
      } else { // Rx4
        return Rx.Disposable.create(target)
      }
    }

    function defineReactive (vm, key, val) {
      if (key in vm) {
        vm[key] = val
      } else {
        Vue.util.defineReactive(vm, key, val)
      }
    }

    Vue.mixin({
      created: function init () {
        var vm = this
        var obs = vm.$options.subscriptions
        if (typeof obs === 'function') {
          obs = obs.call(vm)
        }
        if (!obs) return
        vm.$observables = {}
        vm._obSubscriptions = []
        Object.keys(obs).forEach(function (key) {
          defineReactive(vm, key, undefined)
          var ob = vm.$observables[key] = obs[key]
          if (!ob || typeof ob.subscribe !== 'function') {
            warn(
              'Invalid Observable found in subscriptions option with key "' + key + '".',
              vm
            )
            return
          }
          vm._obSubscriptions.push(obs[key].subscribe(function (value) {
            vm[key] = value
          }))
        })
      },
      beforeDestroy: function () {
        if (this._obSubscriptions) {
          this._obSubscriptions.forEach(unsub)
        }
      }
    })

    Vue.prototype.$watchAsObservable = function (expOrFn, options) {
      if (!hasRx()) {
        return
      }

      var vm = this
      var obs$ = Rx.Observable.create(function (observer) {
        var _unwatch
        function watch () {
          _unwatch = vm.$watch(expOrFn, function (newValue, oldValue) {
            observer.next({ oldValue: oldValue, newValue: newValue })
          }, options)
        }
        function unwatch () {
          _unwatch && _unwatch()
        }

        // if $watchAsObservable is called inside the subscriptions function,
        // because data hasn't been observed yet, the watcher will not work.
        // in that case, wait until created hook to watch.
        if (vm._data) {
          watch()
        } else {
          vm.$once('hook:created', watch)
        }

        // Returns function which disconnects the $watch expression
        var disposable = getDisposable(unwatch);

        return disposable
      })

      ;(vm._obSubscriptions || (vm._obSubscriptions = [])).push(obs$)
      return obs$
    }

    Vue.prototype.$fromDOMEvent = function (selector, event) {
      if (!hasRx()) {
        return
      }
      if (typeof window === 'undefined') {
        return Rx.Observable.create(function () {})
      }

      var vm = this
      var doc = document.documentElement
      var obs$ = Rx.Observable.create(function (observer) {
        function listener (e) {
          if (!vm.$el) return;
          if (selector === null && vm.$el === e.target) return observer.next(e)
          var els = vm.$el.querySelectorAll(selector);
          var el = e.target;
          for (var i = 0, len = els.length; i < len; i++) {
            if (els[i] === el) return observer.next(e)
          }
        }
        doc.addEventListener(event, listener)
        function unwatch () {
          doc.removeEventListener(event, listener)
        }
        // Returns function which disconnects the $watch expression
        var disposable = getDisposable(unwatch)
        return disposable
      })

      ;(vm._obSubscriptions || (vm._obSubscriptions = [])).push(obs$)
      return obs$
    }

    function findVModelName(vnode) {
      var a= vnode.data.directives.find(function(o) { //Search the vModelName attached to the element
        return o.name === 'ob';
      }).value;
      return a;
    }

    function setVModelValue(value, vnode) {
      vnode.context[findVModelName(vnode)] = value;
    }

    Vue.directive('ob', {

      bind: function (el, binding, vnode) {

        var event = binding.arg;

        var obs$ = Rx.Observable.create(function (observer) {
              function listener (e) {
                observer.next(e)
              }
              el.addEventListener(event, listener)
              function unwatch () {
                el.removeEventListener(event, listener)
              }
              // Returns function which disconnects the $watch expression
              var disposable
              if (Rx.Subscription) { // Rx5
                disposable = new Rx.Subscription(unwatch)
              } else { // Rx4
                disposable = Rx.Disposable.create(unwatch)
              }
              return disposable
            });
        vnode.context[binding.value] = obs$;
      },
      unbind: function (el, binding, vnode) {
        var obs$ = vnode.context[binding.value];
        unsub(obs$);
      }
    });

    Vue.prototype.$subscribeTo = function(observable, next, error, complete) {
      var obs$ = observable.subscribe(next, error, complete)
      ;(this._obSubscriptions || (this._obSubscriptions = [])).push(obs$)
      return obs$
    }
  }

  // auto install
  if (typeof Vue !== 'undefined' && typeof Rx !== 'undefined') {
    Vue.use(VueRx, Rx)
  }

  if (typeof exports === 'object' && typeof module === 'object') {
    module.exports = VueRx
  } else if (typeof define === 'function' && define.amd) {
    define(function () { return VueRx })
  } else if (typeof window !== 'undefined') {
    window.VueRx = VueRx
  }
})()
<commit_msg>clean<commit_after>(function () {
  function VueRx (Vue, Rx) {
    var warn = Vue.util.warn || function () {}

    function hasRx (vm) {
      if (!Rx) {
        warn(
          '$watchAsObservable requires Rx to be present globally or ' +
          'be passed to Vue.use() as the second argument.',
          vm
        )
        return false
      }
      return true
    }
    function unsub(handle) {
      if(!handle){return}
      if (handle.dispose) {
        handle.dispose()
      } else if (handle.unsubscribe) {
        handle.unsubscribe()
      }
    }
    function getDisposable(target) {
      if (Rx.Subscription) { // Rx5
        return new Rx.Subscription(target)
      } else { // Rx4
        return Rx.Disposable.create(target)
      }
    }

    function defineReactive (vm, key, val) {
      if (key in vm) {
        vm[key] = val
      } else {
        Vue.util.defineReactive(vm, key, val)
      }
    }

    Vue.mixin({
      created: function init () {
        var vm = this
        var obs = vm.$options.subscriptions
        if (typeof obs === 'function') {
          obs = obs.call(vm)
        }
        if (!obs) return
        vm.$observables = {}
        vm._obSubscriptions = []
        Object.keys(obs).forEach(function (key) {
          defineReactive(vm, key, undefined)
          var ob = vm.$observables[key] = obs[key]
          if (!ob || typeof ob.subscribe !== 'function') {
            warn(
              'Invalid Observable found in subscriptions option with key "' + key + '".',
              vm
            )
            return
          }
          vm._obSubscriptions.push(obs[key].subscribe(function (value) {
            vm[key] = value
          }))
        })
      },
      beforeDestroy: function () {
        if (this._obSubscriptions) {
          this._obSubscriptions.forEach(unsub)
        }
      }
    })

    Vue.prototype.$watchAsObservable = function (expOrFn, options) {
      if (!hasRx()) {
        return
      }

      var vm = this
      var obs$ = Rx.Observable.create(function (observer) {
        var _unwatch
        function watch () {
          _unwatch = vm.$watch(expOrFn, function (newValue, oldValue) {
            observer.next({ oldValue: oldValue, newValue: newValue })
          }, options)
        }
        function unwatch () {
          _unwatch && _unwatch()
        }

        // if $watchAsObservable is called inside the subscriptions function,
        // because data hasn't been observed yet, the watcher will not work.
        // in that case, wait until created hook to watch.
        if (vm._data) {
          watch()
        } else {
          vm.$once('hook:created', watch)
        }

        // Returns function which disconnects the $watch expression
        var disposable = getDisposable(unwatch);

        return disposable
      })

      ;(vm._obSubscriptions || (vm._obSubscriptions = [])).push(obs$)
      return obs$
    }

    Vue.prototype.$fromDOMEvent = function (selector, event) {
      if (!hasRx()) {
        return
      }
      if (typeof window === 'undefined') {
        return Rx.Observable.create(function () {})
      }

      var vm = this
      var doc = document.documentElement
      var obs$ = Rx.Observable.create(function (observer) {
        function listener (e) {
          if (!vm.$el) return;
          if (selector === null && vm.$el === e.target) return observer.next(e)
          var els = vm.$el.querySelectorAll(selector);
          var el = e.target;
          for (var i = 0, len = els.length; i < len; i++) {
            if (els[i] === el) return observer.next(e)
          }
        }
        doc.addEventListener(event, listener)
        function unwatch () {
          doc.removeEventListener(event, listener)
        }
        // Returns function which disconnects the $watch expression
        var disposable = getDisposable(unwatch)
        return disposable
      })

      ;(vm._obSubscriptions || (vm._obSubscriptions = [])).push(obs$)
      return obs$
    }

    Vue.directive('ob', {

      bind: function (el, binding, vnode) {

        var event = binding.arg;

        var obs$ = Rx.Observable.create(function (observer) {
              function listener (e) {
                observer.next(e)
              }
              el.addEventListener(event, listener)
              function unwatch () {
                el.removeEventListener(event, listener)
              }
              // Returns function which disconnects the $watch expression
              var disposable
              if (Rx.Subscription) { // Rx5
                disposable = new Rx.Subscription(unwatch)
              } else { // Rx4
                disposable = Rx.Disposable.create(unwatch)
              }
              return disposable
            });
        vnode.context[binding.value] = obs$;
      },
      unbind: function (el, binding, vnode) {
        var obs$ = vnode.context[binding.value];
        unsub(obs$);
      }
    });

    Vue.prototype.$subscribeTo = function(observable, next, error, complete) {
      var obs$ = observable.subscribe(next, error, complete)
      ;(this._obSubscriptions || (this._obSubscriptions = [])).push(obs$)
      return obs$
    }
  }

  // auto install
  if (typeof Vue !== 'undefined' && typeof Rx !== 'undefined') {
    Vue.use(VueRx, Rx)
  }

  if (typeof exports === 'object' && typeof module === 'object') {
    module.exports = VueRx
  } else if (typeof define === 'function' && define.amd) {
    define(function () { return VueRx })
  } else if (typeof window !== 'undefined') {
    window.VueRx = VueRx
  }
})()
<|endoftext|>


<commit_before>var my_max = function(arr) {
	max = -1000000
	length = arr.length;

    for (var i = 0; i < length; i++) {
        if (max < arr[i]) {
            max = arr[i];
        }
    }

	return max;
};

var vowel_count = function(str) {
	vowels = 0;
	var is_vowel = function(c) {
		if (c === "a" || c === "e" || c === "i" || c === "o" || c === "u") {
			return true;
		}
		return false;
	};
	length = str.length;

	for (var i = 0; i < length; i++) {
		if (is_vowel(str[i])) {
			vowels++;
		}
	}
	return vowels;
};<commit_msg>reverse warmup solution<commit_after>var my_max = function(arr) {
	max = -1000000
	length = arr.length;

    for (var i = 0; i < length; i++) {
        if (max < arr[i]) {
            max = arr[i];
        }
    }

	return max;
};

var vowel_count = function(str) {
	vowels = 0;
	var is_vowel = function(c) {
		if (c === "a" || c === "e" || c === "i" || c === "o" || c === "u") {
			return true;
		}
		return false;
	};
	length = str.length;

	for (var i = 0; i < length; i++) {
		if (is_vowel(str[i])) {
			vowels++;
		}
	}
	return vowels;
};

var reverse = function(str) {
	ret = "";
	length = str.length;

	for (var i = length - 1; i >= 0; i--) {
		ret += str[i];
	}

	return ret;
};<|endoftext|>


<commit_before>function draw(){
    if(settings[3]){/*clear?*/
        buffer.clearRect(
            0,
            0,
            width,
            height
        )
    }

    buffer.lineWidth = settings[0];
    i = lines.length-1;
    do{
        buffer.beginPath();
        buffer.moveTo(lines[i][0],lines[i][1]);
        buffer.lineTo(mouse_x,mouse_y);
        buffer.closePath();
        buffer.strokeStyle = 'rgb('+lines[i][2]+','+lines[i][3]+','+lines[i][4]+')';
        buffer.stroke()
    }while(i--)

    if(settings[3]){/*clear?*/
        canvas.clearRect(
            0,
            0,
            width,
            height
        )
    }
    canvas.drawImage(get('buffer'),0,0)
}
function get(i){
    return document.getElementById(i)
}
function randomize_lines(){
    lines = [];

    i = settings[1]-1;/*number of lines*/
    do{
        /*create line with start_x, start_y, and random rgb color*/
        lines.push([
            random_number(width),
            random_number(height),
            random_number(255),
            random_number(255),
            random_number(255)
        ])
    }while(i--);

    draw()
}
function random_number(i){
    return Math.floor(Math.random()*i)
}
function resize(){
    if(mode>0){
        width = get('buffer').width = get('canvas').width = window.innerWidth;
        height = get('buffer').height = get('canvas').height = window.innerHeight;
        mouse_x = x = width/2;
        mouse_y = y = height/2;
        randomize_lines()
    }
}
function save(){
    /*save settings into localStorage if differ from default*/

    if(get('randomize-key').value==='R'){
        ls.removeItem('warped2');
        settings[2] = 'R'
    }else{
        settings[2] = get('randomize-key').value;
        ls.setItem('warped2',settings[2])
    }

    i = 1;
    do{
        j = ['line-width','number-of-lines'][i];
        if(get(j).value===[1,100][i] || isNaN(get(j).value) || get(j).value<1){
            ls.removeItem('warped'+i);
            settings[i] = [1,100][i];
            get(j).value = settings[i]
        }else{
            settings[i] = parseInt(get(j).value);
            ls.setItem('warped'+i,settings[i])
        }
    }while(i--);

    i=1;
    do{
        settings[3+i] = get(['clear','mouse-lock'][i]).checked;
        if(settings[3+i]){
            ls.removeItem('warped'+(3+i))
        }else{
            ls.setItem('warped'+(3+i),0)
        }
    }while(i--)
}
function setmode(newmode){
    mode = newmode;
    if(mode>0){
        save();

        get('page').innerHTML = '<canvas id=canvas></canvas>';
        buffer = get('buffer').getContext('2d');
        canvas = get('canvas').getContext('2d');

        resize()
    }else{
        buffer = 0;
        canvas = 0;

        get('page').innerHTML = '

Warped

SEIZURE WARNING!
FLASHING LIGHTS!

Lines

<input id=number-of-lines size=1 type=text value='+settings[1]+'>Lines
<input id=line-width size=1 type=text value='+settings[0]+'>Line Width
<input '+(settings[4] ? 'checked ' : '')+'id=mouse-lock type=checkbox>Mouse Lock

<input disabled size=3 style=border:0 type=text value=ESC>Main Menu
<input id=randomize-key maxlength=1 size=3 type=text value='+settings[2]+'>Randomize

<input '+(settings[3] ? 'checked ' : '')+'id=clear type=checkbox>Clear
Reset Settings

'
    }
}
var buffer = 0;
var canvas = 0;
var height = 0;
var i = 0;
var j = 0;
var lines = [];
var ls = window.localStorage;
var mode = 0;
var mouse_x = 0;
var mouse_y = 0;
var settings = [
    ls.getItem('warped0')===null ? 1 : parseInt(ls.getItem('warped0')),/*line width*/
    ls.getItem('warped1')===null ? 100 : parseInt(ls.getItem('warped1')),/*number of lines*/
    ls.getItem('warped2')===null ? 'R' : ls.getItem('warped2'),/*randomize key*/
    ls.getItem('warped3')===null,/*clear?*/
    ls.getItem('warped4')===null/*mouse lock?*/
];
var x = 0;
var width = 0;
var y = 0;

resize();
setmode(0);

window.onkeydown = function(e){
    if(mode>0){
        i = window.event ? event : e;
        i = i.charCode ? i.charCode : i.keyCode;
        if(String.fromCharCode(i)===settings[2]){/*randomize key*/
            randomize_lines()
        }else if(i===27){/*ESC*/
            setmode(0)
        }
    }
};
window.onmousedown = function(e){
    if(mode>0){
        e.preventDefault();
        if(!settings[4]){/*mouse not locked*/
            mouse_x = e.pageX;
            mouse_y = e.pageY;
            draw()
        }
    }
};
window.onmousemove = function(e){
    if(mode>0 && settings[4]){/*mouse locked*/
        mouse_x = e.pageX;
        mouse_y = e.pageY;
        draw()
    }
}

window.onresize = resize
<commit_msg>improved formatting<commit_after>function draw(){
    if(settings[3]){/*clear?*/
        buffer.clearRect(
            0,
            0,
            width,
            height
        )
    }

    buffer.lineWidth = settings[0];
    i = lines.length - 1;
    do{
        buffer.beginPath();
        buffer.moveTo(
            lines[i][0],
            lines[i][1]
        );
        buffer.lineTo(
            mouse_x,
            mouse_y
        );
        buffer.closePath();
        buffer.strokeStyle = 'rgb(' + lines[i][2] + ',' + lines[i][3] + ',' + lines[i][4] + ')';
        buffer.stroke()
    }while(i--)

    if(settings[3]){/*clear?*/
        canvas.clearRect(
            0,
            0,
            width,
            height
        )
    }
    canvas.drawImage(
        get('buffer'),
        0,
        0
    )
}
function get(i){
    return document.getElementById(i)
}
function randomize_lines(){
    lines = [];

    i = settings[1] - 1;/*number of lines*/
    do{
        /*create line with start_x, start_y, and random rgb color*/
        lines.push([
            random_number(width),
            random_number(height),
            random_number(255),
            random_number(255),
            random_number(255)
        ])
    }while(i--);

    draw()
}
function random_number(i){
    return Math.floor(Math.random() * i)
}
function resize(){
    if(mode > 0){
        width = get('buffer').width = get('canvas').width = window.innerWidth;
        height = get('buffer').height = get('canvas').height = window.innerHeight;
        mouse_x = x = width / 2;
        mouse_y = y = height / 2;
        randomize_lines()
    }
}
function save(){
    /*save settings into localStorage if differ from default*/

    if(get('randomize-key').value === 'R'){
        ls.removeItem('warped2');
        settings[2] = 'R'
    }else{
        settings[2] = get('randomize-key').value;
        ls.setItem('warped2',settings[2])
    }

    i = 1;
    do{
        j = [
            'line-width',
            'number-of-lines'
        ][i];
        if(get(j).value === [1,100][i] || isNaN(get(j).value) || get(j).value < 1){
            ls.removeItem('warped' + i);
            settings[i] = [1,100][i];
            get(j).value = settings[i]
        }else{
            settings[i] = parseInt(get(j).value);
            ls.setItem('warped' + i,settings[i])
        }
    }while(i--);

    i=1;
    do{
        settings[3 + i] = get(['clear','mouse-lock'][i]).checked;
        if(settings[3 + i]){
            ls.removeItem('warped' + (3 + i))
        }else{
            ls.setItem('warped' + (3 + i),0)
        }
    }while(i--)
}
function setmode(newmode){
    mode = newmode;
    if(mode > 0){
        save();

        get('page').innerHTML = '<canvas id=canvas></canvas>';
        buffer = get('buffer').getContext('2d');
        canvas = get('canvas').getContext('2d');

        resize()
    }else{
        buffer = 0;
        canvas = 0;

        get('page').innerHTML = '

Warped

SEIZURE WARNING!
FLASHING LIGHTS!

Lines

<input id=number-of-lines size=1 type=text value=' + settings[1] + '>Lines
<input id=line-width size=1 type=text value=' + settings[0] + '>Line Width
<input ' + (settings[4] ? 'checked ' : '') + 'id=mouse-lock type=checkbox>Mouse Lock

<input disabled size=3 style=border:0 type=text value=ESC>Main Menu
<input id=randomize-key maxlength=1 size=3 type=text value=' + settings[2] + '>Randomize

<input ' + (settings[3] ? 'checked ' : '') + 'id=clear type=checkbox>Clear
Reset Settings

'
    }
}
var buffer = 0;
var canvas = 0;
var height = 0;
var i = 0;
var j = 0;
var lines = [];
var ls = window.localStorage;
var mode = 0;
var mouse_x = 0;
var mouse_y = 0;
var settings = [
    ls.getItem('warped0') === null ? 1 : parseInt(ls.getItem('warped0')),/*line width*/
    ls.getItem('warped1') === null ? 100 : parseInt(ls.getItem('warped1')),/*number of lines*/
    ls.getItem('warped2') === null ? 'R' : ls.getItem('warped2'),/*randomize key*/
    ls.getItem('warped3') === null,/*clear?*/
    ls.getItem('warped4') === null/*mouse lock?*/
];
var x = 0;
var width = 0;
var y = 0;

resize();
setmode(0);

window.onkeydown = function(e){
    if(mode > 0){
        i = window.event ? event : e;
        i = i.charCode ? i.charCode : i.keyCode;
        if(String.fromCharCode(i) === settings[2]){/*randomize key*/
            randomize_lines()
        }else if(i === 27){/*ESC*/
            setmode(0)
        }
    }
};
window.onmousedown = function(e){
    if(mode > 0){
        e.preventDefault();
        if(!settings[4]){/*mouse not locked*/
            mouse_x = e.pageX;
            mouse_y = e.pageY;
            draw()
        }
    }
};
window.onmousemove = function(e){
    if(mode > 0 && settings[4]){/*mouse locked*/
        mouse_x = e.pageX;
        mouse_y = e.pageY;
        draw()
    }
}

window.onresize = resize
<|endoftext|>


<commit_before>var app = require('express').Router();
var story = require('storyboard').mainStory;
var Promise = require('bluebird');

var plugged = require('../lib/client');
var db = require('../lib/db/sql_db');
var utils = require('../lib/utils');
var config = require('../lib/load_config');

app.get('/', function (req, res) {
    res.json({
        plug_data: {
            all: config.web.path + '/v1/all',
            users: config.web.path + '/v1/users',
            media: config.web.path + '/v1/media',
            history: config.web.path + '/v1/history',
            room: config.web.path + '/v1/room'
        },
        bot_data: {
            customCommands: config.web.path + '/v1/customcommands',
            bestVotedSongs: config.web.path + '/v1/highscore',
            blacklist: config.web.path + '/v1/blacklist',
            check: config.web.path + '/v1/check?s={string}',
            user: config.web.path + '/v1/user?id={userid}&name={username}'
        },
        socket: config.web.path + '/v1/socket'
    })
});

app.get('/users', function (req, res) {
    res.json(plugged.getUsers().map(function (e) {
        return {id: e.id, username: e.username, slug: e.slug, gRole: e.gRole, role: e.role, level: e.level}
    }));
});

app.get('/media', function (req, res) {
    res.json({data: (plugged.getMedia().id !== -1 ? plugged.getMedia() : null)});
});

app.get('/history', function (req, res) {
    plugged.getRoomHistory(function (err, history) {
        if (err)res.status(500).end();
        else res.json(history.map(function (e) {
                e.room = undefined;
                return e;
            })
        );
    });
});

app.get('/room', function (req, res) {
    res.json(function () {
        var meta = plugged.getRoomMeta();
        meta.favorite = undefined;
        meta.dj = (plugged.getDJ() !== undefined ? (plugged.getDJ().id !== -1 ? plugged.getDJ() : null) : null);
        return meta;
    }());
});

app.get('/all', function (req, res) {
    plugged.getRoomHistory(function (err, history) {
        res.json({
            room: function () {
                var meta = plugged.getRoomMeta();
                meta.favorite = undefined;
                meta.dj = (plugged.getDJ() !== undefined ? (plugged.getDJ().id !== -1 ? plugged.getDJ() : null) : null);
                return meta;
            }(),
            media: (plugged.getMedia().id !== -1 ? plugged.getMedia() : null),
            users: plugged.getUsers().map(function (e) {
                return {id: e.id, username: e.username, slug: e.slug, gRole: e.gRole, role: e.role, level: e.level};
            }),
            history: (err ? null : history.map(function (e) {
                e.room = undefined;
                return e;
            }))
        })
    });
});

app.get('/customcommands', function (req, res) {
    //noinspection JSUnresolvedFunction
    db.models.CustomCommand.findAll().map(function (e) {
        return {id: e.id, trigger: e.trigger, message: e.message, enabled: e.status};
    }).then(function (ccs) {
        res.json({data: ccs});
    }).catch(function (err) {
        story.warn('web', 'Error getting CustomCommands', {attach: err});
        res.status(500).end();
    });
});

app.get('/highscore', function (req, res) {
    var limit = parseInt(req.query.limit) || 10;
    //noinspection JSUnresolvedFunction
    db.models.Play.findAll({order: [['woots', 'DESC']], limit: limit}).then(function (plays) {
        Promise.all(plays.map(function (e) {
            return e.getUser();
        })).then(function (users) {
            Promise.all(plays.map(function (e) {
                //noinspection JSUnresolvedFunction
                return e.getSong();
            })).then(function (songs) {
                var data = [];
                plays.forEach(function (play, i) {
                    var p = {
                        id: play.id,
                        score: {woots: play.woots, mehs: play.mehs, grabs: play.grabs},
                        time: play.time
                    };
                    p.user = {id: users[i].id, username: users[i].username};
                    p.song = (songs[i] !== null ? {
                        id: songs[i].plug_id,
                        author: songs[i].author,
                        title: songs[i].title,
                        format: songs[i].format,
                        cid: songs[i].cid,
                        duration: songs[i].duration,
                        image: songs[i].image
                    } : null);
                    data.push(p);
                });
                res.json({data: data});
            });
        });
    });
});

app.get('/blacklist', function (req, res) {
    //noinspection JSUnresolvedFunction
    db.models.Song.findAll({where: {is_banned: true}}).then(function (songs) {
        res.json({
            blacklist: songs.map(function (song) {
                return {
                    id: song.id,
                    author: song.author,
                    title: song.title,
                    format: song.format,
                    cid: song.cid,
                    image: song.image,
                    isBanned: song.is_banned,
                    banReason: song.ban_reason
                };
            })
        });
    }).catch(function () {
        res.status(500).json({error: 'SQL Error'});
    });
});

app.get('/check', function (req, res) {
    if (req.query.s !== undefined) {
        utils.resolveCID(req.query.s).then(function (cid) {
            var split = cid.split(':');
            db.models.Song.find({where: {format: split[0], cid: split[1]}}).then(function (song) {
                if (song !== undefined && song !== null) {
                    res.json({
                        data: {
                            id: song.id,
                            author: song.author,
                            title: song.title,
                            format: song.format,
                            cid: song.cid,
                            image: song.image,
                            is_banned: song.is_banned,
                            banReason: (song.is_banned ? song.ban_reason : null)
                        }
                    });
                } else res.status(404).json({error: 'song not found'});
            }).catch(function () {
                res.status(500).json({error: 'SQL Error'});
            });
        }).catch(function (error) {
            res.json({error: error.message});
        });
    } else res.status(400).json({error: 'invalid query'});
});

app.get('/user', function (req, res) {
    var search = {};
    if (req.query.id !== undefined) search.id = req.query.id;
    if (req.query.name !== undefined && req.query.id === undefined) search.username = req.query.name;

    if (req.query.id === undefined && req.query.name === undefined) res.status(400).json({error: 'invalid query'});
    else {
        db.models.User.find({where: search}).then(function (user) {
            if (user !== undefined && user !== null) {
                res.json({
                    data: {
                        id: user.id,
                        username: user.username,
                        avatar: user.avatar_id,
                        badge: user.badge,
                        grole: user.global_role,
                        role: user.s_role,
                        level: user.level,
                        status: user.status
                    }
                });
            } else res.statusCode(404).json({error: 'User not found'});
        }).catch(function () {
            res.status(500).json({error: 'SQL Error'});
        })
    }
});

module.exports = app;<commit_msg>adding channelblacklist to api<commit_after>var app = require('express').Router();
var story = require('storyboard').mainStory;
var Promise = require('bluebird');

var plugged = require('../lib/client');
var db = require('../lib/db/sql_db');
var utils = require('../lib/utils');
var config = require('../lib/load_config');

app.get('/', function (req, res) {
    res.json({
        plug_data: {
            all: config.web.path + '/v1/all',
            users: config.web.path + '/v1/users',
            media: config.web.path + '/v1/media',
            history: config.web.path + '/v1/history',
            room: config.web.path + '/v1/room'
        },
        bot_data: {
            customCommands: config.web.path + '/v1/customcommands',
            bestVotedSongs: config.web.path + '/v1/highscore',
            blacklist: config.web.path + '/v1/blacklist',
            check: config.web.path + '/v1/check?s={string}',
            user: config.web.path + '/v1/user?id={userid}&name={username}'
        },
        socket: config.web.path + '/v1/socket'
    })
});

app.get('/users', function (req, res) {
    res.json(plugged.getUsers().map(function (e) {
        return {id: e.id, username: e.username, slug: e.slug, gRole: e.gRole, role: e.role, level: e.level}
    }));
});

app.get('/media', function (req, res) {
    res.json({data: (plugged.getMedia().id !== -1 ? plugged.getMedia() : null)});
});

app.get('/history', function (req, res) {
    plugged.getRoomHistory(function (err, history) {
        if (err)res.status(500).end();
        else res.json(history.map(function (e) {
                e.room = undefined;
                return e;
            })
        );
    });
});

app.get('/room', function (req, res) {
    res.json(function () {
        var meta = plugged.getRoomMeta();
        meta.favorite = undefined;
        meta.dj = (plugged.getDJ() !== undefined ? (plugged.getDJ().id !== -1 ? plugged.getDJ() : null) : null);
        return meta;
    }());
});

app.get('/all', function (req, res) {
    plugged.getRoomHistory(function (err, history) {
        res.json({
            room: function () {
                var meta = plugged.getRoomMeta();
                meta.favorite = undefined;
                meta.dj = (plugged.getDJ() !== undefined ? (plugged.getDJ().id !== -1 ? plugged.getDJ() : null) : null);
                return meta;
            }(),
            media: (plugged.getMedia().id !== -1 ? plugged.getMedia() : null),
            users: plugged.getUsers().map(function (e) {
                return {id: e.id, username: e.username, slug: e.slug, gRole: e.gRole, role: e.role, level: e.level};
            }),
            history: (err ? null : history.map(function (e) {
                e.room = undefined;
                return e;
            }))
        })
    });
});

app.get('/customcommands', function (req, res) {
    //noinspection JSUnresolvedFunction
    db.models.CustomCommand.findAll().map(function (e) {
        return {id: e.id, trigger: e.trigger, message: e.message, enabled: e.status};
    }).then(function (ccs) {
        res.json({data: ccs});
    }).catch(function (err) {
        story.warn('web', 'Error getting CustomCommands', {attach: err});
        res.status(500).end();
    });
});

app.get('/highscore', function (req, res) {
    var limit = parseInt(req.query.limit) || 10;
    //noinspection JSUnresolvedFunction
    db.models.Play.findAll({order: [['woots', 'DESC']], limit: limit}).then(function (plays) {
        Promise.all(plays.map(function (e) {
            return e.getUser();
        })).then(function (users) {
            Promise.all(plays.map(function (e) {
                //noinspection JSUnresolvedFunction
                return e.getSong();
            })).then(function (songs) {
                var data = [];
                plays.forEach(function (play, i) {
                    var p = {
                        id: play.id,
                        score: {woots: play.woots, mehs: play.mehs, grabs: play.grabs},
                        time: play.time
                    };
                    p.user = {id: users[i].id, username: users[i].username};
                    p.song = (songs[i] !== null ? {
                        id: songs[i].plug_id,
                        author: songs[i].author,
                        title: songs[i].title,
                        format: songs[i].format,
                        cid: songs[i].cid,
                        duration: songs[i].duration,
                        image: songs[i].image
                    } : null);
                    data.push(p);
                });
                res.json({data: data});
            });
        });
    });
});

app.get('/blacklist', function (req, res) {
    //noinspection JSUnresolvedFunction
    db.models.Song.findAll({where: {is_banned: true}}).then(function (songs) {
        res.json({
            data: songs.map(function (song) {
                return {
                    id: song.id,
                    author: song.author,
                    title: song.title,
                    format: song.format,
                    cid: song.cid,
                    image: song.image,
                    isBanned: song.is_banned,
                    banReason: song.ban_reason
                };
            })
        });
    }).catch(function () {
        res.status(500).json({error: 'SQL Error'});
    });
});

app.get('/channelblacklist', function (req, res) {
    db.models.Channel.findAll({where: {is_banned: true}}).then(function (channels) {
        res.json({
            data: channels.map(function (c) {
                return {
                    name: c.name,
                    channel_id: c.cid,
                    is_banned: c.is_banned,
                    ban_reason: c.ban_reason
                };
            })
        });
    }).catch(function () {
        res.status(500).json({error: 'SQL Error'});
    });
});

app.get('/check', function (req, res) {
    if (req.query.s !== undefined) {
        utils.resolveCID(req.query.s).then(function (cid) {
            var split = cid.split(':');
            db.models.Song.find({where: {format: split[0], cid: split[1]}}).then(function (song) {
                if (song !== undefined && song !== null) {
                    res.json({
                        data: {
                            id: song.id,
                            author: song.author,
                            title: song.title,
                            format: song.format,
                            cid: song.cid,
                            image: song.image,
                            is_banned: song.is_banned,
                            banReason: (song.is_banned ? song.ban_reason : null)
                        }
                    });
                } else res.status(404).json({error: 'song not found'});
            }).catch(function () {
                res.status(500).json({error: 'SQL Error'});
            });
        }).catch(function (error) {
            res.json({error: error.message});
        });
    } else res.status(400).json({error: 'invalid query'});
});

app.get('/user', function (req, res) {
    var search = {};
    if (req.query.id !== undefined) search.id = req.query.id;
    if (req.query.name !== undefined && req.query.id === undefined) search.username = req.query.name;

    if (req.query.id === undefined && req.query.name === undefined) res.status(400).json({error: 'invalid query'});
    else {
        db.models.User.find({where: search}).then(function (user) {
            if (user !== undefined && user !== null) {
                res.json({
                    data: {
                        id: user.id,
                        username: user.username,
                        avatar: user.avatar_id,
                        badge: user.badge,
                        grole: user.global_role,
                        role: user.s_role,
                        level: user.level,
                        status: user.status
                    }
                });
            } else res.statusCode(404).json({error: 'User not found'});
        }).catch(function () {
            res.status(500).json({error: 'SQL Error'});
        })
    }
});

module.exports = app;<|endoftext|>