<commit_before>/*
 * jQuery-handlebars
 * https://github.com/softwarespot/jquery-handlebars
 * Author: softwarespot
 * Licensed under the MIT license
 * Version: 0.1.0-beta
 */
; (function ($, undefined) {

    // Initial idea from: http://blog.teamtreehouse.com/handlebars-js-part-3-tips-and-tricks

    // Plugin Logic
    $.fn.extend({

        // data doubles up as options when the action is either 'clear' or 'remove'
        handlebars: function (action, template, dataOrOptions, options) {

            // jQuery object reference for this. Only select the first selector of the collection
            var $this = $(this).first(),

                // Store whether the template is valid or not
                isTemplate = typeof template === 'string' && /^#[\w\-]+$/.test(template);

            // These actions don't require any pre-processing
            if (typeof action === 'string') {

                // If a 'get' action is provided, then get the template(s)
                // The template string if not defined will return all template(s)
                if (/^FIND|GET$/i.test(action)) {

                    // The include parameter will be true, if the template is a string and valid anchor
                    return getTemplate($this, template, isTemplate);

                // If a 'compiled' action is provided, then return the compiled object literal
                } else if (/^COMPILED$/i.test(action)) {

                    return compiled;

                }

            }

            // Set our options from the defaults, overriding with the
            // parameter we pass into this function
            options = $.extend({}, $.fn.handlebars.options, options);

            // START: Sanitize the options

            // Check if the option type is a string and valid
            if (typeof options.type === 'string' && /^APPEND|FILL|REFILL$/i.test(options.type)) {

                // Set to uppercase
                options.type = options.type.toUpperCase();

            } else {

                // Otherwise default to 'append' i.e. if null or simply invalid
                options.type = Type.APPEND;

            }

            // If the removal type is a string and valid, then set to uppercase
            if (typeof options.remove_type === 'string' && /^ALL|NONE|SAME$/i.test(options.remove_type)) {

                // Set to uppercase
                options.remove_type = options.remove_type.toUpperCase();

            } else {

                // Otherwise default to 'none' i.e. if null or simply is invalid
                options.remove_type = Remove.NONE;

            }

            // END: Sanitize the options

            // If a 'clear' action is provided, then remove the template from the content element
            if (/^CLEAR|REMOVE$/i.test(action)) {

                // Extend the options again, as the dataOrOptions acts as an alias for options when a removal action is
                // specified
                options = $.extend(options, dataOrOptions);

                // If the options parameter is not the 'same' and a template string exists, the
                // temporarily override
                if (isTemplate && options.remove_type !== Remove.SAME) {

                    options.remove_type = Remove.SAME;

                } else {

                    // Otherwise use 'all'
                    options.remove_type = Remove.ALL;

                }

                // If the template is not defined, then set as null before removing
                if (!isTemplate) {

                    template = null;

                }

                return removeTemplate(this, $this, template, options);

            }

            // Assume it's an addition i.e. 'add'

            // The data object literal must contain data
            if (typeof options.validate === 'boolean' && options.validate && $.isEmptyObject(dataOrOptions)) {

                console.log('jQuery-handlebars: Data was not passed to the plugin or is simply an empty plain object');
                return this;

            }

            // jQuery object reference
            var $selector = null;

            // If a valid string template is passed then check if it's compiled or get the jQuery object instead
            if (isTemplate) {

                // If compiled already then no need to re-compile
                if (typeof compiled[template] === 'function') {

                    // Debugging only
                    console.log('jQuery-handlebars: %s has already been compiled', template);

                    // Return to continue chaining
                    return setTemplate(this, $this, template, dataOrOptions, options);

                }

                // Not compiled

                // Get the first selection only
                $selector = $(template).first();

                // If the selector doesn't exist for whatever reason, then set to null
                if ($selector.length === 0) {

                    $selector = null;

                }

                // If a valid jQuery selector object
            } else if (template instanceof $ && typeof template.length === 'number' && template.length > 0) {

                // Get the first selection only
                $selector = template.first();

                // Get the selector name for using with the compiled object literal
                // If the selector property doesn't exist, then this will be set to null
                template = typeof $selector.selector !== 'undefined' ? $selector.selector : null;

                // If compiled already then no need to re-compile
                if (template !== null && typeof compiled[template] === 'function') {

                    // Debugging only
                    console.log('jQuery-handlebars: %s has already been compiled', template);

                    // Return to continue chaining
                    return setTemplate(this, $this, template, dataOrOptions, options);

                }
            }

            // If an invalid selector, then return this to continue chaining
            if ($selector === null || template === null || $selector.length === 0) {

                // Debugging only
                console.log('jQuery-handlebars: Template cannot be found');
                return this;

            }

            // Get the HTML of the template only
            var html = $selector.html();

            // Store the compiled template in the compiled store
            compiled[template] = Handlebars.compile(html);

            // Return to continue chaining
            return setTemplate(this, $this, template, dataOrOptions, options);
        }

    });

    // Fields (Private)

    // Store the compiled template(s) using the template string as the identifier i.e. key
    var compiled = {};

    // Methods (Private)

    // Note: Variable are called 'self' to avoid conflict with 'this'

    // Get the template in the content selector
    // include refers to whether to include the template in the selection
    var getTemplate = function ($self, template, include) {

            // Get the divs with the template data attribute and optional specified template string e.g. #some-template
            var templateLocate = (include && template ? '="' + template + '"' : '');
            return $self.find('div[' + DATA_ATTRIBUTE + templateLocate + ']');

        },

        // Remove the specified template from the content selector. If a template is not provided
        // then all template(s) that are contained within the content selector will be removed
        removeTemplate = function (self, $self, template, options) {

            // If the option has been passed to remove 'none', then respect this choice
            if (options.remove_type === Remove.NONE) {

                // Debugging only
                console.log('jQuery-handlebars: Template(s) were not removed [%s]', options.remove_type);

                // Return self to maintain chaining if there is nothing to remove
                return self;

            }

            var filtered = getTemplate($self, template, options.remove_type === Remove.SAME);
            if (filtered.length === 0) {

                // Debugging only
                console.log('jQuery-handlebars: Unable to find any template(s) for removal [%s]', options.remove_type);

                // Return self to maintain chaining if there is nothing to remove
                return self;

            }

            // Remove from the DOM
            filtered.remove();

            // Debugging only
            console.log('jQuery-handlebars: Removing template(s) [%s]', options.remove_type);

            // Remove the template from the compiled store, if the option is true
            if (typeof options.delete_compiled === 'boolean' && options.delete_compiled) {

                // Iterate through the filtered collection and remove from the template string from the compiled store
                $.each(filtered, function (index, element) {

                    // Get the data attribute for the template string if it's not null or has already been removed
                    var attribute = $(this).attr(DATA_ATTRIBUTE);
                    if (attribute === null || compiled[attribute] === undefined) {

                        return;

                    }

                    // Set to undefined to mimic deletion of the template
                    compiled[attribute] = undefined;

                    // Debugging only
                    console.log('jQuery-handlebars: Removing compiled template [%s]', attribute);

                });

                if (template !== null) {

                    // Debugging only
                    console.log('jQuery-handlebars: Removed the template from the compiled store [%s]', template);

                }

            }

        },

        // Set the specified template to the content selector
        setTemplate = function (self, $self, template, data, options) {

            // Previous implementations
            /*
                $self.children('*').not('script[type="text/x-handlebars-template"]').empty();
                $self.children('*:not(script[type="text/x-handlebars-template"])').empty();

                // Get all nodes apart from the Handlebarjs template script elements
                 var filtered = $self.contents().filter(function () {

                    return this.nodeType !== Node.COMMENT_NODE && // Not a comment
                        (this.nodeName !== 'SCRIPT' && this.type !== 'text/x-handlebars-template') // Not a handlebars template
                        ; // /[^\t\n\r ]/.test(this.textContent); // Not whitespace

                });
             */

            // The include parameter will be set to true, when specifically looking for the provided template string
            var filtered = getTemplate($self, template, options.remove_type === Remove.SAME);

            // Remove from the DOM if specified to do so
            if (options.remove_type !== Remove.NONE) {

                // Remove from the DOM
                filtered.remove();

                // Debugging only
                console.log('jQuery-handlebars: Removed previous template(s) [%s]', options.remove_type);

            }

            // If set to not refill and template node(s) exist, then return this
            if (typeof options.refill === 'boolean' && !options.refill) {

                // Get the template(s) after potential removal. The parameter include has been set to true, as we are checking
                // if only the same template(s) exists (perhaps an option could/should be created)
                filtered = getTemplate($self, template, true);
                if (filtered.length > 0) {

                    // Debugging only
                    console.log('jQuery-handlebars: Refill has been set to false and the content element contains template(s) [%s]', options.remove_type);

                    return self;

                }

            }

            // Append to the content element by checking the type. Default is 'append'
            switch (options.type) {
                case 'FILL':
                case 'REFILL':
                    // $self.html(compiled[template](data)); // Dangerous to do if handlebarsjs template(s) are embedded inside the element

                    // Debugging only
                    console.log('jQuery-handlebars: The type fill/refill is NOT implemented [%s]', template);
                    break;

                default:
                    // Create a div element with the template appended to it
                    // This contains a data-* attribute called data-jquery-handlebars for easy association
                    // that it's a Handlebarjs template
                    var $div = $('<div/>')
                        .attr(DATA_ATTRIBUTE, template)
                        .append(compiled[template](data));

                    // Append the div to content element
                    $self.append($div);

                    // Debugging only
                    console.log('jQuery-handlebars: Appending template to the content element [%s]', template);
                    break;
            }

            return self;
        };

    // Constants

    // The data-* attribute name
    var DATA_ATTRIBUTE = 'data-jquery-handlebars',

        // Removal constants. Who enjoys magic values?
        Remove = {
            ALL: 'ALL',
            NONE: 'NONE',
            SAME: 'SAME'
        },

        // Type constants. Who enjoys magic values?
        Type = {
            APPEND: 'APPEND',
            FILL: 'FILL',
            REFILL: 'REFILL'
        };

    // Defaults

    $.fn.handlebars.options = {
        // Delete the template from the compiled store on removal
        delete_compiled: true,

        // Allow the option of adding multiple template(s) inside an element
        refill: true,

        // Remove pre-existing templates from the content element
        // The following options are:
        //      'all': Remove all valid template(s) from the content element
        //      'same': Remove only those template(s) that match the provided template string
        //      'none' (default): Don't remove any template(s)
        remove_type: Remove.NONE,

        // Type of writing: fill, refill, append (default)
        // type: Type.APPEND,

        // Check whether the data passed is empty
        validate: true
    };

})(jQuery);
<commit_msg>Removed js from the name<commit_after>/*
 * jQuery-handlebars
 * https://github.com/softwarespot/jquery-handlebars
 * Author: softwarespot
 * Licensed under the MIT license
 * Version: 0.1.0-beta
 */
; (function ($, undefined) {

    // Initial idea from: http://blog.teamtreehouse.com/handlebars-js-part-3-tips-and-tricks

    // Plugin Logic
    $.fn.extend({

        // data doubles up as options when the action is either 'clear' or 'remove'
        handlebars: function (action, template, dataOrOptions, options) {

            // jQuery object reference for this. Only select the first selector of the collection
            var $this = $(this).first(),

                // Store whether the template is valid or not
                isTemplate = typeof template === 'string' && /^#[\w\-]+$/.test(template);

            // These actions don't require any pre-processing
            if (typeof action === 'string') {

                // If a 'get' action is provided, then get the template(s)
                // The template string if not defined will return all template(s)
                if (/^FIND|GET$/i.test(action)) {

                    // The include parameter will be true, if the template is a string and valid anchor
                    return getTemplate($this, template, isTemplate);

                // If a 'compiled' action is provided, then return the compiled object literal
                } else if (/^COMPILED$/i.test(action)) {

                    return compiled;

                }

            }

            // Set our options from the defaults, overriding with the
            // parameter we pass into this function
            options = $.extend({}, $.fn.handlebars.options, options);

            // START: Sanitize the options

            // Check if the option type is a string and valid
            if (typeof options.type === 'string' && /^APPEND|FILL|REFILL$/i.test(options.type)) {

                // Set to uppercase
                options.type = options.type.toUpperCase();

            } else {

                // Otherwise default to 'append' i.e. if null or simply invalid
                options.type = Type.APPEND;

            }

            // If the removal type is a string and valid, then set to uppercase
            if (typeof options.remove_type === 'string' && /^ALL|NONE|SAME$/i.test(options.remove_type)) {

                // Set to uppercase
                options.remove_type = options.remove_type.toUpperCase();

            } else {

                // Otherwise default to 'none' i.e. if null or simply is invalid
                options.remove_type = Remove.NONE;

            }

            // END: Sanitize the options

            // If a 'clear' action is provided, then remove the template from the content element
            if (/^CLEAR|REMOVE$/i.test(action)) {

                // Extend the options again, as the dataOrOptions acts as an alias for options when a removal action is
                // specified
                options = $.extend(options, dataOrOptions);

                // If the options parameter is not the 'same' and a template string exists, the
                // temporarily override
                if (isTemplate && options.remove_type !== Remove.SAME) {

                    options.remove_type = Remove.SAME;

                } else {

                    // Otherwise use 'all'
                    options.remove_type = Remove.ALL;

                }

                // If the template is not defined, then set as null before removing
                if (!isTemplate) {

                    template = null;

                }

                return removeTemplate(this, $this, template, options);

            }

            // Assume it's an addition i.e. 'add'

            // The data object literal must contain data
            if (typeof options.validate === 'boolean' && options.validate && $.isEmptyObject(dataOrOptions)) {

                console.log('jQuery-handlebars: Data was not passed to the plugin or is simply an empty plain object');
                return this;

            }

            // jQuery object reference
            var $selector = null;

            // If a valid string template is passed then check if it's compiled or get the jQuery object instead
            if (isTemplate) {

                // If compiled already then no need to re-compile
                if (typeof compiled[template] === 'function') {

                    // Debugging only
                    console.log('jQuery-handlebars: %s has already been compiled', template);

                    // Return to continue chaining
                    return setTemplate(this, $this, template, dataOrOptions, options);

                }

                // Not compiled

                // Get the first selection only
                $selector = $(template).first();

                // If the selector doesn't exist for whatever reason, then set to null
                if ($selector.length === 0) {

                    $selector = null;

                }

                // If a valid jQuery selector object
            } else if (template instanceof $ && typeof template.length === 'number' && template.length > 0) {

                // Get the first selection only
                $selector = template.first();

                // Get the selector name for using with the compiled object literal
                // If the selector property doesn't exist, then this will be set to null
                template = typeof $selector.selector !== 'undefined' ? $selector.selector : null;

                // If compiled already then no need to re-compile
                if (template !== null && typeof compiled[template] === 'function') {

                    // Debugging only
                    console.log('jQuery-handlebars: %s has already been compiled', template);

                    // Return to continue chaining
                    return setTemplate(this, $this, template, dataOrOptions, options);

                }
            }

            // If an invalid selector, then return this to continue chaining
            if ($selector === null || template === null || $selector.length === 0) {

                // Debugging only
                console.log('jQuery-handlebars: Template cannot be found');
                return this;

            }

            // Get the HTML of the template only
            var html = $selector.html();

            // Store the compiled template in the compiled store
            compiled[template] = Handlebars.compile(html);

            // Return to continue chaining
            return setTemplate(this, $this, template, dataOrOptions, options);
        }

    });

    // Fields (Private)

    // Store the compiled template(s) using the template string as the identifier i.e. key
    var compiled = {};

    // Methods (Private)

    // Note: Variable are called 'self' to avoid conflict with 'this'

    // Get the template in the content selector
    // include refers to whether to include the template in the selection
    var getTemplate = function ($self, template, include) {

            // Get the divs with the template data attribute and optional specified template string e.g. #some-template
            var templateLocate = (include && template ? '="' + template + '"' : '');
            return $self.find('div[' + DATA_ATTRIBUTE + templateLocate + ']');

        },

        // Remove the specified template from the content selector. If a template is not provided
        // then all template(s) that are contained within the content selector will be removed
        removeTemplate = function (self, $self, template, options) {

            // If the option has been passed to remove 'none', then respect this choice
            if (options.remove_type === Remove.NONE) {

                // Debugging only
                console.log('jQuery-handlebars: Template(s) were not removed [%s]', options.remove_type);

                // Return self to maintain chaining if there is nothing to remove
                return self;

            }

            var filtered = getTemplate($self, template, options.remove_type === Remove.SAME);
            if (filtered.length === 0) {

                // Debugging only
                console.log('jQuery-handlebars: Unable to find any template(s) for removal [%s]', options.remove_type);

                // Return self to maintain chaining if there is nothing to remove
                return self;

            }

            // Remove from the DOM
            filtered.remove();

            // Debugging only
            console.log('jQuery-handlebars: Removing template(s) [%s]', options.remove_type);

            // Remove the template from the compiled store, if the option is true
            if (typeof options.delete_compiled === 'boolean' && options.delete_compiled) {

                // Iterate through the filtered collection and remove from the template string from the compiled store
                $.each(filtered, function (index, element) {

                    // Get the data attribute for the template string if it's not null or has already been removed
                    var attribute = $(this).attr(DATA_ATTRIBUTE);
                    if (attribute === null || compiled[attribute] === undefined) {

                        return;

                    }

                    // Set to undefined to mimic deletion of the template
                    compiled[attribute] = undefined;

                    // Debugging only
                    console.log('jQuery-handlebars: Removing compiled template [%s]', attribute);

                });

                if (template !== null) {

                    // Debugging only
                    console.log('jQuery-handlebars: Removed the template from the compiled store [%s]', template);

                }

            }

        },

        // Set the specified template to the content selector
        setTemplate = function (self, $self, template, data, options) {

            // Previous implementations
            /*
                $self.children('*').not('script[type="text/x-handlebars-template"]').empty();
                $self.children('*:not(script[type="text/x-handlebars-template"])').empty();

                // Get all nodes apart from the Handlebarjs template script elements
                 var filtered = $self.contents().filter(function () {

                    return this.nodeType !== Node.COMMENT_NODE && // Not a comment
                        (this.nodeName !== 'SCRIPT' && this.type !== 'text/x-handlebars-template') // Not a handlebars template
                        ; // /[^\t\n\r ]/.test(this.textContent); // Not whitespace

                });
             */

            // The include parameter will be set to true, when specifically looking for the provided template string
            var filtered = getTemplate($self, template, options.remove_type === Remove.SAME);

            // Remove from the DOM if specified to do so
            if (options.remove_type !== Remove.NONE) {

                // Remove from the DOM
                filtered.remove();

                // Debugging only
                console.log('jQuery-handlebars: Removed previous template(s) [%s]', options.remove_type);

            }

            // If set to not refill and template node(s) exist, then return this
            if (typeof options.refill === 'boolean' && !options.refill) {

                // Get the template(s) after potential removal. The parameter include has been set to true, as we are checking
                // if only the same template(s) exists (perhaps an option could/should be created)
                filtered = getTemplate($self, template, true);
                if (filtered.length > 0) {

                    // Debugging only
                    console.log('jQuery-handlebars: Refill has been set to false and the content element contains template(s) [%s]', options.remove_type);

                    return self;

                }

            }

            // Append to the content element by checking the type. Default is 'append'
            switch (options.type) {
                case 'FILL':
                case 'REFILL':
                    // $self.html(compiled[template](data)); // Dangerous to do if Handlebars template(s) are embedded inside the element

                    // Debugging only
                    console.log('jQuery-handlebars: The type fill/refill is NOT implemented [%s]', template);
                    break;

                default:
                    // Create a div element with the template appended to it
                    // This contains a data-* attribute called data-jquery-handlebars for easy association
                    // that it's a Handlebarjs template
                    var $div = $('<div/>')
                        .attr(DATA_ATTRIBUTE, template)
                        .append(compiled[template](data));

                    // Append the div to content element
                    $self.append($div);

                    // Debugging only
                    console.log('jQuery-handlebars: Appending template to the content element [%s]', template);
                    break;
            }

            return self;
        };

    // Constants

    // The data-* attribute name
    var DATA_ATTRIBUTE = 'data-jquery-handlebars',

        // Removal constants. Who enjoys magic values?
        Remove = {
            ALL: 'ALL',
            NONE: 'NONE',
            SAME: 'SAME'
        },

        // Type constants. Who enjoys magic values?
        Type = {
            APPEND: 'APPEND',
            FILL: 'FILL',
            REFILL: 'REFILL'
        };

    // Defaults

    $.fn.handlebars.options = {
        // Delete the template from the compiled store on removal
        delete_compiled: true,

        // Allow the option of adding multiple template(s) inside an element
        refill: true,

        // Remove pre-existing templates from the content element
        // The following options are:
        //      'all': Remove all valid template(s) from the content element
        //      'same': Remove only those template(s) that match the provided template string
        //      'none' (default): Don't remove any template(s)
        remove_type: Remove.NONE,

        // Type of writing: fill, refill, append (default)
        // type: Type.APPEND,

        // Check whether the data passed is empty
        validate: true
    };

})(jQuery);
<|endoftext|>


<commit_before>$(document).ready(function(){

    //size of display
    var w = 600;
    var h = 600;
    var renderer = new THREE.WebGLRenderer();
    renderer.setSize(w,h);
    $("#screen").append( renderer.domElement );
    //start with center of mass focus selected
    $("#com").button('toggle');

    var scene = new THREE.Scene();
    //do I want perspective?
    var camera = new THREE.PerspectiveCamera( 60, w/h, 0.1, 30 );
    camera.position.z = 2;
    camera.lookAt(new THREE.Vector3(0,0,0));

    //Allows you to look around whilst focusing on the center of mass (0,0,0)
    //http://mrdoob.github.com/three.js/examples/js/controls/OrbitControls.js
    //Argh where is the documentation for this?
    var controls = new THREE.OrbitControls( camera );
    controls.addEventListener('change', render);

    //light at the center of mass
    var light = new THREE.PointLight( 0xffffff, 1, 10 );
    light.position.set( 0, 0, 0 );
    scene.add( light );
    var light2 = new THREE.PointLight( 0xffffff, 0.6, 10 );
    light2.position.set( 0, 0, 1 );
    scene.add( light2 );

    //solutions/starting positions available to simulate
    //[0:14]
    var solution = 3;

    //array of spheres, carries other information like
    //time-step size, trail length
    var bodies = [];
    reset(bodies, scene, solution);

    //simulation parameters
    var step = 0;

    //bind function to dropdown menu for solution selection
    $("#simulationSelection").click(function(x){
        solution = x.target.id;
        reset(bodies, scene, solution);
        camera.position.set(0,0,3);
    });
    var currentFocus = -1;
    //focus point function
    $("#focusRadio").click(function(x){
        var newFocus = x.target.value;
        if (currentFocus != newFocus){
            currentFocus = newFocus;
            reset(bodies, scene, solution);
            camera.position.set(0,0,3);
        }
    });

    function move(){
        for (var i = 0; i < bodies.speed; i++){
            rk4(bodies);
        }
        step++;
        //recenter on the focussed body
        if (currentFocus != -1){
            var adjustment = bodies[currentFocus].position.clone();
            for (var i = 0; i < bodies.length; i++){
                bodies[i].position.sub(adjustment);
            }
        }

        for (var i = 0; i < bodies.length; i++){
            //Lines seem to be fixed length,
            //but we can push and shift to get a trail.
            bodies[i].trail.geometry.vertices.shift();
            bodies[i].trail.geometry.vertices.push(bodies[i].position.clone());
            bodies[i].trail.geometry.verticesNeedUpdate = true;
        }

        if (step % 1000 == 0){
            for (var i = 0; i < bodies.length; i++){
                var v = bodies[i].velocity;
                var p = bodies[i].position;
                if (v.length() > 10 || p.length() > 10){
                    console.log(step);
                    return false
                }
            }
            console.log(step);
        }
        return true;
    }

    function animate(){
        if (!move()){
            reset(bodies, scene, solution);
        }
        requestAnimationFrame( animate );
        controls.update();
        renderer.render( scene, camera );
    }

    function render(){
        renderer.render( scene, camera );
    }

    animate();
});

//https://en.wikipedia.org/wiki/Runge%E2%80%93Kutta_methods#Common_fourth-order_Runge.E2.80.93Kutta_method
//http://home.deds.nl/~infokees/useful/OrbitRungeKutta4.pdf
//Could we improve accuracy by considering all particles at once?
function rk4(bodies){
    var h = bodies.dt;
    var movements= [];
    for (var i = 0; i < bodies.length; i++){
        var r = bodies[i].position;
        var v = bodies[i].velocity;

        //running totals remove need to clone vectors
        //Equations 11 & 12
        var dr = new THREE.Vector3(0,0,0);
        var dv = new THREE.Vector3(0,0,0);

        //Equation 10 is missing a "+"
        var k1v = a(i, r, bodies);
        dv.add(k1v);

        var k1r = v.clone();
        dr.add(k1r);

        var k2v = a(i, k1r.multiplyScalar(h/2).add(r), bodies);
        dv.add(k2v).add(k2v);

        var k2r = k1v.multiplyScalar(h/2).add(v);
        dr.add(k2r).add(k2r);

        var k3v = a(i, k2r.multiplyScalar(h/2).add(r), bodies);
        dv.add(k3v).add(k3v);

        var k3r = k2v.multiplyScalar(h/2).add(v);
        dr.add(k3r).add(k3r);

        var k4v = a(i, k3r.multiplyScalar(h).add(r), bodies);
        dv.add(k4v);

        var k4r = k3v.multiplyScalar(h).add(v);
        dr.add(k4r);

        bodies[i].velocity.add(dv.multiplyScalar(h/6));
        bodies[i].position.add(dr.multiplyScalar(h/6));
    }
}

//calculates the acceleration of body i if it were at position p
function a(i, p, bodies){
    //F = G*m1*m2/r^2
    //G,m = 1
    //F points in the direction of the attractor
    var sum = new THREE.Vector3(0,0,0);
    for (var j = 0; j < bodies.length; j++){
        if (j == i){
            continue;
        }
        var d2 = p.distanceToSquared(bodies[j].position);
        var r = new THREE.Vector3(0,0,0);
        r.subVectors(bodies[j].position, p) //vector to attractor
        .normalize() //unit vector
        .divideScalar(d2);
        sum.add(r);
    }
    return sum;
}

//resets the bodies to the starting positions and velocities given in
//the paper http://arxiv.org/pdf/1303.0181v1.pdf
//solution in [0:14]
function reset(bodies, scene, solution){
    bodies.dt = 0.001;
    bodies.speed = 5;
    //numerical stability is governed by how close the bodies come to each other during an orbit
    //these are derived empically
    var instability = [10,20,10,1,2,10,20,20,50,20,100,10,10,2000,2000];
    bodies.dt /= instability[solution];
    bodies.speed *= instability[solution];

    //period of orbit from paper
    var ts =     [6.2356,  7.0039, 63.5345, 14.8939, 28.6703, 13.8658, 25.8406, 10.4668, 79.4759,  21.2710, 55.5018, 17.3284, 10.9626, 55.7898, 54.2076 ];
    var period = ts[solution];
    //make the trails as long as the orbit
    bodies.segments = period / bodies.dt/bodies.speed ;

    for (var i = 0; i < bodies.length; i++){
        scene.remove(bodies[i].trail);
        scene.remove(bodies[i]);
    }

    //n = 3...
    for (var i = 0; i < 3; i++){
        //size and detail of spheres
        var geometry = new THREE.SphereGeometry(0.1,16,16);
        var material = new THREE.MeshPhongMaterial( { color: 0xff << (i*8)} );
        var body = new THREE.Mesh( geometry, material );
        body.velocity = new THREE.Vector3(0,0,0);

        //trailing lines
        var lineMaterial = new THREE.LineBasicMaterial({ color: body.material.color });
        var lineGeometry = new THREE.Geometry();
        for (var j = 0; j < bodies.segments; j++){
            //lines start at the initial positions of the spheres
            lineGeometry.vertices.push(new THREE.Vector3([-1,1,0][i],0,0));
        }
        body.trail = new THREE.Line(lineGeometry, lineMaterial);
        bodies[i] = body;
    }

    for (var i = 0; i < bodies.length; i++){
        scene.add(bodies[i]);
        scene.add(bodies[i].trail);
    }

    //The paper refers to the particles as 1,2,3
    //I use 0,1,2
    var x1dots = [0.30689, 0.39295, 0.18428, 0.46444, 0.43917, 0.40592, 0.38344, 0.08330, 0.350112, 0.08058, 0.55906, 0.51394, 0.28270, 0.41682, 0.41734];
    var y1dots = [0.12551, 0.09758, 0.58719, 0.39606, 0.45297, 0.23016, 0.37736, 0.12789, 0.079340, 0.58884, 0.34919, 0.30474, 0.32721, 0.33033, 0.31310];

    var x1dot = x1dots[solution];
    var y1dot = y1dots[solution];

    bodies[0].velocity.x = x1dot;
    bodies[1].velocity.x = x1dot;
    bodies[2].velocity.x = -2*x1dot;

    bodies[0].velocity.y = y1dot;
    bodies[1].velocity.y = y1dot;
    bodies[2].velocity.y = -2*y1dot;

    bodies[0].position.x = -1;
    bodies[1].position.x = 1;
    bodies[2].position.x = 0;

    bodies[0].position.y = 0;
    bodies[1].position.y = 0;
    bodies[2].position.y = 0;
}

<commit_msg>bind event listeners to dom element, not document<commit_after>$(document).ready(function(){

    //size of display
    var w = 600;
    var h = 600;
    var renderer = new THREE.WebGLRenderer();
    renderer.setSize(w,h);
    $("#screen").append( renderer.domElement );
    //start with center of mass focus selected
    $("#com").button('toggle');

    var scene = new THREE.Scene();
    //do I want perspective?
    var camera = new THREE.PerspectiveCamera( 60, w/h, 0.1, 30 );
    camera.position.z = 2;
    camera.lookAt(new THREE.Vector3(0,0,0));

    //Allows you to look around whilst focusing on the center of mass (0,0,0)
    //http://mrdoob.github.com/three.js/examples/js/controls/OrbitControls.js
    //Argh where is the documentation for this?
    var controls = new THREE.OrbitControls( camera , $("#screen")[0]);
    controls.addEventListener('change', render);

    //light at the center of mass
    var light = new THREE.PointLight( 0xffffff, 1, 10 );
    light.position.set( 0, 0, 0 );
    scene.add( light );
    var light2 = new THREE.PointLight( 0xffffff, 0.6, 10 );
    light2.position.set( 0, 0, 1 );
    scene.add( light2 );

    //solutions/starting positions available to simulate
    //[0:14]
    var solution = 3;

    //array of spheres, carries other information like
    //time-step size, trail length
    var bodies = [];
    reset(bodies, scene, solution);

    //simulation parameters
    var step = 0;

    //bind function to dropdown menu for solution selection
    $("#simulationSelection").click(function(x){
        solution = x.target.id;
        reset(bodies, scene, solution);
        camera.position.set(0,0,3);
    });
    var currentFocus = -1;
    //focus point function
    $("#focusRadio").click(function(x){
        var newFocus = x.target.value;
        if (currentFocus != newFocus){
            currentFocus = newFocus;
            reset(bodies, scene, solution);
            camera.position.set(0,0,3);
        }
    });

    function move(){
        for (var i = 0; i < bodies.speed; i++){
            rk4(bodies);
        }
        step++;
        //recenter on the focussed body
        if (currentFocus != -1){
            var adjustment = bodies[currentFocus].position.clone();
            for (var i = 0; i < bodies.length; i++){
                bodies[i].position.sub(adjustment);
            }
        }

        for (var i = 0; i < bodies.length; i++){
            //Lines seem to be fixed length,
            //but we can push and shift to get a trail.
            bodies[i].trail.geometry.vertices.shift();
            bodies[i].trail.geometry.vertices.push(bodies[i].position.clone());
            bodies[i].trail.geometry.verticesNeedUpdate = true;
        }

        if (step % 1000 == 0){
            for (var i = 0; i < bodies.length; i++){
                var v = bodies[i].velocity;
                var p = bodies[i].position;
                if (v.length() > 10 || p.length() > 10){
                    console.log(step);
                    return false
                }
            }
            console.log(step);
        }
        return true;
    }

    function animate(){
        if (!move()){
            reset(bodies, scene, solution);
        }
        requestAnimationFrame( animate );
        controls.update();
        renderer.render( scene, camera );
    }

    function render(){
        renderer.render( scene, camera );
    }

    animate();
});

//https://en.wikipedia.org/wiki/Runge%E2%80%93Kutta_methods#Common_fourth-order_Runge.E2.80.93Kutta_method
//http://home.deds.nl/~infokees/useful/OrbitRungeKutta4.pdf
//Could we improve accuracy by considering all particles at once?
function rk4(bodies){
    var h = bodies.dt;
    var movements= [];
    for (var i = 0; i < bodies.length; i++){
        var r = bodies[i].position;
        var v = bodies[i].velocity;

        //running totals remove need to clone vectors
        //Equations 11 & 12
        var dr = new THREE.Vector3(0,0,0);
        var dv = new THREE.Vector3(0,0,0);

        //Equation 10 is missing a "+"
        var k1v = a(i, r, bodies);
        dv.add(k1v);

        var k1r = v.clone();
        dr.add(k1r);

        var k2v = a(i, k1r.multiplyScalar(h/2).add(r), bodies);
        dv.add(k2v).add(k2v);

        var k2r = k1v.multiplyScalar(h/2).add(v);
        dr.add(k2r).add(k2r);

        var k3v = a(i, k2r.multiplyScalar(h/2).add(r), bodies);
        dv.add(k3v).add(k3v);

        var k3r = k2v.multiplyScalar(h/2).add(v);
        dr.add(k3r).add(k3r);

        var k4v = a(i, k3r.multiplyScalar(h).add(r), bodies);
        dv.add(k4v);

        var k4r = k3v.multiplyScalar(h).add(v);
        dr.add(k4r);

        bodies[i].velocity.add(dv.multiplyScalar(h/6));
        bodies[i].position.add(dr.multiplyScalar(h/6));
    }
}

//calculates the acceleration of body i if it were at position p
function a(i, p, bodies){
    //F = G*m1*m2/r^2
    //G,m = 1
    //F points in the direction of the attractor
    var sum = new THREE.Vector3(0,0,0);
    for (var j = 0; j < bodies.length; j++){
        if (j == i){
            continue;
        }
        var d2 = p.distanceToSquared(bodies[j].position);
        var r = new THREE.Vector3(0,0,0);
        r.subVectors(bodies[j].position, p) //vector to attractor
        .normalize() //unit vector
        .divideScalar(d2);
        sum.add(r);
    }
    return sum;
}

//resets the bodies to the starting positions and velocities given in
//the paper http://arxiv.org/pdf/1303.0181v1.pdf
//solution in [0:14]
function reset(bodies, scene, solution){
    bodies.dt = 0.001;
    bodies.speed = 5;
    //numerical stability is governed by how close the bodies come to each other during an orbit
    //these are derived empically
    var instability = [10,20,10,1,2,10,20,20,50,20,100,10,10,2000,2000];
    bodies.dt /= instability[solution];
    bodies.speed *= instability[solution];

    //period of orbit from paper
    var ts =     [6.2356,  7.0039, 63.5345, 14.8939, 28.6703, 13.8658, 25.8406, 10.4668, 79.4759,  21.2710, 55.5018, 17.3284, 10.9626, 55.7898, 54.2076 ];
    var period = ts[solution];
    //make the trails as long as the orbit
    bodies.segments = period / bodies.dt/bodies.speed ;

    for (var i = 0; i < bodies.length; i++){
        scene.remove(bodies[i].trail);
        scene.remove(bodies[i]);
    }

    //n = 3...
    for (var i = 0; i < 3; i++){
        //size and detail of spheres
        var geometry = new THREE.SphereGeometry(0.1,16,16);
        var material = new THREE.MeshPhongMaterial( { color: 0xff << (i*8)} );
        var body = new THREE.Mesh( geometry, material );
        body.velocity = new THREE.Vector3(0,0,0);

        //trailing lines
        var lineMaterial = new THREE.LineBasicMaterial({ color: body.material.color });
        var lineGeometry = new THREE.Geometry();
        for (var j = 0; j < bodies.segments; j++){
            //lines start at the initial positions of the spheres
            lineGeometry.vertices.push(new THREE.Vector3([-1,1,0][i],0,0));
        }
        body.trail = new THREE.Line(lineGeometry, lineMaterial);
        bodies[i] = body;
    }

    for (var i = 0; i < bodies.length; i++){
        scene.add(bodies[i]);
        scene.add(bodies[i].trail);
    }

    //The paper refers to the particles as 1,2,3
    //I use 0,1,2
    var x1dots = [0.30689, 0.39295, 0.18428, 0.46444, 0.43917, 0.40592, 0.38344, 0.08330, 0.350112, 0.08058, 0.55906, 0.51394, 0.28270, 0.41682, 0.41734];
    var y1dots = [0.12551, 0.09758, 0.58719, 0.39606, 0.45297, 0.23016, 0.37736, 0.12789, 0.079340, 0.58884, 0.34919, 0.30474, 0.32721, 0.33033, 0.31310];

    var x1dot = x1dots[solution];
    var y1dot = y1dots[solution];

    bodies[0].velocity.x = x1dot;
    bodies[1].velocity.x = x1dot;
    bodies[2].velocity.x = -2*x1dot;

    bodies[0].velocity.y = y1dot;
    bodies[1].velocity.y = y1dot;
    bodies[2].velocity.y = -2*y1dot;

    bodies[0].position.x = -1;
    bodies[1].position.x = 1;
    bodies[2].position.x = 0;

    bodies[0].position.y = 0;
    bodies[1].position.y = 0;
    bodies[2].position.y = 0;
}

<|endoftext|>


<commit_before>'use strict';

const Assert = require('chai').assert;
const request = require('../support/request');
const sdapi = require('../support/sdapi');
const github = require('../support/github');
const TIMEOUT = 60 * 1000;

module.exports = function server() {
    // eslint-disable-next-line new-cap
    this.Before({
        tags: ['@gitflow'],
        timeout: TIMEOUT
    }, () => {
        this.branch = 'darrenBranch';
        this.repoOrg = 'screwdriver-cd-test';
        this.repoName = 'functional-git';

        // Reset shared information
        this.pullRequestNumber = null;
        this.pipelineId = null;

        return request({  // TODO : perform this in the before-hook for all func tests
            method: 'GET',
            url: `${this.instance}/${this.namespace}/auth/token?access_key=${this.accessKey}`,
            followAllRedirects: true,
            json: true
        }).then((response) => {
            this.jwt = response.body.token;
        }).then(() =>
            github.cleanUpRepository(this.gitToken, this.branch, this.repoOrg,
                this.repoName)
        );
    });

    this.Given(/^an existing pipeline$/, {
        timeout: TIMEOUT
    }, () =>
        request({
            uri: `${this.instance}/${this.namespace}/pipelines`,
            method: 'POST',
            auth: {
                bearer: this.jwt
            },
            body: {
                checkoutUrl: `git@github.com:${this.repoOrg}/${this.repoName}.git#master`
            },
            json: true
        }).then((response) => {
            Assert.oneOf(response.statusCode, [409, 201]);

            if (response.statusCode === 201) {
                this.pipelineId = response.body.id;
            } else {
                const str = response.body.message;
                const id = str.split(': ')[1];

                this.pipelineId = id;
            }
        })
    );

    this.Given(/^an existing pull request targeting the pipeline's branch$/, {
        timeout: TIMEOUT
    }, () => {
        const branch = this.branch;
        const token = this.gitToken;

        return github.createBranch(token, branch, this.repoOrg, this.repoName)
            .then(() => github.createFile(token, branch, this.repoOrg, this.repoName))
            .then(() =>
                github.createPullRequest(token, branch, this.repoOrg, this.repoName)
            )
            .then((data) => {
                this.pullRequestNumber = data.number;
                this.sha = data.head.sha;
            })
            .catch((err) => {
                // throws an error if a PR already exists, so this is fine
                Assert.strictEqual(err.code, 422);
            });
    });

    this.When(/^a pull request is opened$/, { timeout: TIMEOUT }, () => {
        const branch = this.branch;
        const token = this.gitToken;

        return github.createBranch(token, branch, this.repoOrg, this.repoName)
            .then(() => github.createFile(token, branch, this.repoOrg, this.repoName))
            .then(() =>
                github.createPullRequest(token, branch, this.repoOrg, this.repoName)
            )
            .then((data) => {
                this.pullRequestNumber = data.number;
                this.sha = data.head.sha;
            });
    });

    this.When(/^it is targeting the pipeline's branch$/, () => null);

    this.When(/^the pull request is closed$/, {
        timeout: TIMEOUT
    }, () =>
        this.promiseToWait(3)  // Wait for the build to be enabled before moving forward
        .then(() =>
            sdapi.searchForBuild({
                instance: this.instance,
                pipelineId: this.pipelineId,
                pullRequestNumber: this.pullRequestNumber,
                sha: this.sha,
                desiredStatus: ['RUNNING', 'SUCCESS', 'FAILURE']
            })
        ).then((buildData) => {
            this.previousBuildId = buildData.id;
        }).then(() => github.closePullRequest(this.gitToken, this.repoOrg, this.repoName,
                this.pullRequestNumber)
        )
    );

    this.When(/^new changes are pushed to that pull request$/, {
        timeout: TIMEOUT
    }, () =>
        this.promiseToWait(3)  // Find & save the previous build
        .then(() =>
            sdapi.searchForBuild({
                instance: this.instance,
                pipelineId: this.pipelineId,
                pullRequestNumber: this.pullRequestNumber,
                sha: this.sha,
                desiredStatus: ['QUEUED', 'RUNNING', 'SUCCESS', 'FAILURE']
            }).then((buildData) => {
                this.previousBuildId = buildData.id;
            })
        )
        .then(() => github.createFile(this.gitToken, this.branch, this.repoOrg,
            this.repoName))
    );

    this.When(/^a new commit is pushed$/, () => null);

    this.When(/^it is against the pipeline's branch$/, { timeout: TIMEOUT }, () => {
        this.testBranch = 'master';

        return github.createFile(this.gitToken, this.testBranch, this.repoOrg, this.repoName);
    });

    this.Then(/^a new build from `main` should be created to test that change$/, {
        timeout: TIMEOUT
    }, () =>
        this.promiseToWait(8)
        .then(() => sdapi.searchForBuild({
            instance: this.instance,
            pipelineId: this.pipelineId,
            pullRequestNumber: this.pullRequestNumber
        }))
        .then((data) => {
            const build = data;

            Assert.oneOf(build.status, ['QUEUED', 'RUNNING', 'SUCCESS']);
            this.jobId = build.jobId;
        })
    );

    this.Then(/^the build should know they are in a pull request/, () =>
        request({
            json: true,
            method: 'GET',
            uri: `${this.instance}/${this.namespace}/jobs/${this.jobId}`
        })
        .then((response) => {
            Assert.strictEqual(response.statusCode, 200);
            Assert.match(response.body.name, /^PR-(.*)$/);
        })
    );

    this.Then(/^any existing builds should be stopped$/, {
        timeout: TIMEOUT
    }, () => {
        const desiredStatus = ['ABORTED', 'SUCCESS'];

        return sdapi.waitForBuildStatus({
            buildId: this.previousBuildId,
            instance: this.instance,
            desiredStatus
        }).then((buildData) => {
            // TODO: save the status so the next step can verify the github status
            Assert.oneOf(buildData.status, desiredStatus);
        });
    });

    this.Then(/^the GitHub status should be updated to reflect the build's status$/, () =>
        github.getStatus(this.gitToken, this.repoOrg, this.repoName, this.sha)
        .then((data) => {
            Assert.oneOf(data.state, ['success', 'pending']);
        })
    );
};
<commit_msg>Increase git-flow timeout<commit_after>'use strict';

const Assert = require('chai').assert;
const request = require('../support/request');
const sdapi = require('../support/sdapi');
const github = require('../support/github');
const TIMEOUT = 120 * 1000;

module.exports = function server() {
    // eslint-disable-next-line new-cap
    this.Before({
        tags: ['@gitflow'],
        timeout: TIMEOUT
    }, () => {
        this.branch = 'darrenBranch';
        this.repoOrg = 'screwdriver-cd-test';
        this.repoName = 'functional-git';

        // Reset shared information
        this.pullRequestNumber = null;
        this.pipelineId = null;

        return request({  // TODO : perform this in the before-hook for all func tests
            method: 'GET',
            url: `${this.instance}/${this.namespace}/auth/token?access_key=${this.accessKey}`,
            followAllRedirects: true,
            json: true
        }).then((response) => {
            this.jwt = response.body.token;
        }).then(() =>
            github.cleanUpRepository(this.gitToken, this.branch, this.repoOrg,
                this.repoName)
        );
    });

    this.Given(/^an existing pipeline$/, {
        timeout: TIMEOUT
    }, () =>
        request({
            uri: `${this.instance}/${this.namespace}/pipelines`,
            method: 'POST',
            auth: {
                bearer: this.jwt
            },
            body: {
                checkoutUrl: `git@github.com:${this.repoOrg}/${this.repoName}.git#master`
            },
            json: true
        }).then((response) => {
            Assert.oneOf(response.statusCode, [409, 201]);

            if (response.statusCode === 201) {
                this.pipelineId = response.body.id;
            } else {
                const str = response.body.message;
                const id = str.split(': ')[1];

                this.pipelineId = id;
            }
        })
    );

    this.Given(/^an existing pull request targeting the pipeline's branch$/, {
        timeout: TIMEOUT
    }, () => {
        const branch = this.branch;
        const token = this.gitToken;

        return github.createBranch(token, branch, this.repoOrg, this.repoName)
            .then(() => github.createFile(token, branch, this.repoOrg, this.repoName))
            .then(() =>
                github.createPullRequest(token, branch, this.repoOrg, this.repoName)
            )
            .then((data) => {
                this.pullRequestNumber = data.number;
                this.sha = data.head.sha;
            })
            .catch((err) => {
                // throws an error if a PR already exists, so this is fine
                Assert.strictEqual(err.code, 422);
            });
    });

    this.When(/^a pull request is opened$/, { timeout: TIMEOUT }, () => {
        const branch = this.branch;
        const token = this.gitToken;

        return github.createBranch(token, branch, this.repoOrg, this.repoName)
            .then(() => github.createFile(token, branch, this.repoOrg, this.repoName))
            .then(() =>
                github.createPullRequest(token, branch, this.repoOrg, this.repoName)
            )
            .then((data) => {
                this.pullRequestNumber = data.number;
                this.sha = data.head.sha;
            });
    });

    this.When(/^it is targeting the pipeline's branch$/, () => null);

    this.When(/^the pull request is closed$/, {
        timeout: TIMEOUT
    }, () =>
        this.promiseToWait(3)  // Wait for the build to be enabled before moving forward
        .then(() =>
            sdapi.searchForBuild({
                instance: this.instance,
                pipelineId: this.pipelineId,
                pullRequestNumber: this.pullRequestNumber,
                sha: this.sha,
                desiredStatus: ['RUNNING', 'SUCCESS', 'FAILURE']
            })
        ).then((buildData) => {
            this.previousBuildId = buildData.id;
        }).then(() => github.closePullRequest(this.gitToken, this.repoOrg, this.repoName,
                this.pullRequestNumber)
        )
    );

    this.When(/^new changes are pushed to that pull request$/, {
        timeout: TIMEOUT
    }, () =>
        this.promiseToWait(3)  // Find & save the previous build
        .then(() =>
            sdapi.searchForBuild({
                instance: this.instance,
                pipelineId: this.pipelineId,
                pullRequestNumber: this.pullRequestNumber,
                sha: this.sha,
                desiredStatus: ['QUEUED', 'RUNNING', 'SUCCESS', 'FAILURE']
            }).then((buildData) => {
                this.previousBuildId = buildData.id;
            })
        )
        .then(() => github.createFile(this.gitToken, this.branch, this.repoOrg,
            this.repoName))
    );

    this.When(/^a new commit is pushed$/, () => null);

    this.When(/^it is against the pipeline's branch$/, { timeout: TIMEOUT }, () => {
        this.testBranch = 'master';

        return github.createFile(this.gitToken, this.testBranch, this.repoOrg, this.repoName);
    });

    this.Then(/^a new build from `main` should be created to test that change$/, {
        timeout: TIMEOUT
    }, () =>
        this.promiseToWait(8)
        .then(() => sdapi.searchForBuild({
            instance: this.instance,
            pipelineId: this.pipelineId,
            pullRequestNumber: this.pullRequestNumber
        }))
        .then((data) => {
            const build = data;

            Assert.oneOf(build.status, ['QUEUED', 'RUNNING', 'SUCCESS']);
            this.jobId = build.jobId;
        })
    );

    this.Then(/^the build should know they are in a pull request/, () =>
        request({
            json: true,
            method: 'GET',
            uri: `${this.instance}/${this.namespace}/jobs/${this.jobId}`
        })
        .then((response) => {
            Assert.strictEqual(response.statusCode, 200);
            Assert.match(response.body.name, /^PR-(.*)$/);
        })
    );

    this.Then(/^any existing builds should be stopped$/, {
        timeout: TIMEOUT
    }, () => {
        const desiredStatus = ['ABORTED', 'SUCCESS'];

        return sdapi.waitForBuildStatus({
            buildId: this.previousBuildId,
            instance: this.instance,
            desiredStatus
        }).then((buildData) => {
            // TODO: save the status so the next step can verify the github status
            Assert.oneOf(buildData.status, desiredStatus);
        });
    });

    this.Then(/^the GitHub status should be updated to reflect the build's status$/, () =>
        github.getStatus(this.gitToken, this.repoOrg, this.repoName, this.sha)
        .then((data) => {
            Assert.oneOf(data.state, ['success', 'pending']);
        })
    );
};
<|endoftext|>


<commit_before>var RouterError = require('../errors').RouterError;

/**
 * Dispatch to given `controller` and `action` in `app`.
 *
 * @param {Application} app
 * @param {String} controller
 * @param {String} action
 * @return {Function}
 * @api private
 */
module.exports = function(app, controller, action) {

  return function dispatch(req, res, next) {
    app._controller(controller, function(err, ctrl) {
      if (err) { return next(err); }
      ctrl._init(req, res, next);
      ctrl._invoke(action);
    });
  }
}
<commit_msg>Remove unused require statement.<commit_after>/**
 * Dispatch to given `controller` and `action` in `app`.
 *
 * @param {Application} app
 * @param {String} controller
 * @param {String} action
 * @return {Function}
 * @api private
 */
module.exports = function(app, controller, action) {

  return function dispatch(req, res, next) {
    app._controller(controller, function(err, ctrl) {
      if (err) { return next(err); }
      ctrl._init(req, res, next);
      ctrl._invoke(action);
    });
  }
}
<|endoftext|>


<commit_before>import Color from 'color';

import {Platform} from 'react-native';

export default {

    // Badge
    badgeBg: '#ED1727',
    badgeColor: '#fff',

    // Button
    btnFontFamily: (Platform.OS === 'ios' ) ? 'HelveticaNeue' : 'Roboto_medium',
    btnDisabledBg: '#b5b5b5',
    btnDisabledClr: '#f1f1f1',

    get btnPrimaryBg () {
        return this.brandPrimary;
    },
    get btnPrimaryColor () {
        return this.inverseTextColor;
    },
    get btnInfoBg () {
        return this.brandInfo;
    },
    get btnInfoColor () {
        return this.inverseTextColor;
    },
    get btnSuccessBg () {
        return this.brandSuccess;
    },
    get btnSuccessColor () {
        return this.inverseTextColor;
    },
    get btnDangerBg () {
        return this.brandDanger;
    },
    get btnDangerColor () {
        return this.inverseTextColor;
    },
    get btnWarningBg () {
        return this.brandWarning;
    },
    get btnWarningColor () {
        return this.inverseTextColor;
    },
    get btnTextSize () {
        return (Platform.OS==='ios') ? this.fontSizeBase* 1.1 :
        this.fontSizeBase-1;
    },
    get btnTextSizeLarge () {
        return this.fontSizeBase* 1.5;
    },
    get btnTextSizeSmall () {
        return this.fontSizeBase* .8;
    },
    get borderRadiusLarge () {
        return this.fontSizeBase* 3.8;
    },

    buttonPadding: 6,

    get iconSizeLarge () {
        return this.iconFontSize* 1.5;
    },
    get iconSizeSmall () {
        return this.iconFontSize* .6;
    },

    // Card
    cardDefaultBg: '#fff',

    // Check Box
    checkboxBgColor: '#039BE5',
    checkboxSize: 23,
    checkboxTickColor: '#fff',

    // Color
    brandPrimary : '#5067FF',
    brandInfo: '#5bc0de',
    brandSuccess: '#5cb85c',
    brandDanger: '#d9534f',
    brandWarning: '#f0ad4e',
    brandSidebar: '#252932',

    // Font
    fontFamily: (Platform.OS === 'ios' ) ? 'HelveticaNeue' : 'Roboto',
    fontSizeBase: 15,

    get fontSizeH1 () {
        return this.fontSizeBase*1.8;
    },
    get fontSizeH2 () {
        return this.fontSizeBase* 1.6;
    },
    get fontSizeH3 () {
        return this.fontSizeBase* 1.4;
    },

    // Footer
    footerHeight: 55,
    footerDefaultBg: (Platform.OS === 'ios' ) ? '#F8F8F8' : '#4179F7',

    //FooterTab
    tabBarTextColor: (Platform.OS === 'ios' ) ? '#6b6b6b' : '#b3c7f9',
    tabBarActiveTextColor: (Platform.OS === 'ios' ) ? '#007aff' : '#fff',
    tabActiveBgColor: (Platform.OS=='ios') ? '#cde1f9' : undefined,

    //Tab
    tabDefaultBg: (Platform.OS === 'ios' ) ? '#F8F8F8' : '#4179F7',
    topTabBarTextColor: (Platform.OS === 'ios' ) ? '#6b6b6b' : '#b3c7f9',
    topTabBarActiveTextColor: (Platform.OS === 'ios' ) ? '#007aff' : '#fff',
    topTabActiveBgColor: (Platform.OS=='ios') ? '#cde1f9' : undefined,
    topTabBarBorderColor: (Platform.OS === 'ios' ) ? '#007aff' : '#fff',

    // Header
    iosToolbarBtnColor: '#007aff',
    toolbarDefaultBg: (Platform.OS === 'ios' ) ? '#F8F8F8' : '#4179F7',
    toolbarHeight: (Platform.OS === 'ios' ) ? 64 : 56,
    toolbarIconSize: (Platform.OS === 'ios' ) ? 20 : 22,
    toolbarInputColor: '#CECDD2',
    toolbarInverseBg: '#222',
    toolbarTextColor: (Platform.OS==='ios') ? '#000' : '#fff',
    get statusBarColor() {
        return Color(this.toolbarDefaultBg).darken(0.2).hexString();
    },

    // Icon
    iconFamily: 'Ionicons',
    iconFontSize: (Platform.OS === 'ios' ) ? 30 : 28,
    iconMargin: 7,

    // InputGroup
    inputFontSize: 15,
    inputBorderColor: '#D9D5DC',
    inputSuccessBorderColor: '#2b8339',
    inputErrorBorderColor: '#ed2f2f',

    get inputColor () {
        return this.textColor;
    },
    get inputColorPlaceholder () {
        return '#575757';
    },

    inputGroupMarginBottom: 10,
    inputHeightBase: 40,
    inputPaddingLeft: 5,

    get inputPaddingLeftIcon () {
        return this.inputPaddingLeft* 8;
    },

    // Line Height
    btnLineHeight: 19,
    lineHeightH1: 32,
    lineHeightH2: 27,
    lineHeightH3: 22,
    iconLineHeight: (Platform.OS === 'ios' ) ? 37 : 30,
    lineHeight: (Platform.OS === 'ios' ) ? 20 : 24,

    // List
    listBorderColor: '#ddd',
    listDividerBg: '#ddd',
    listItemHeight: 45,
    listItemPadding: (Platform.OS === 'ios' ) ? 12 : 16,
    listNoteColor: '#808080',
    listNoteSize: 13,

    // Progress Bar
    defaultProgressColor: '#E4202D',
    inverseProgressColor: '#1A191B',

    // Radio Button
    radioBtnSize: (Platform.OS === 'ios') ? 25 : 23,
    radioColor: '#7e7e7e',

    get radioSelectedColor() {
        return Color(this.radioColor).darken(0.2).hexString();
    },

    // Spinner
    defaultSpinnerColor: '#45D56E',
    inverseSpinnerColor: '#1A191B',

    // Tabs
    tabBgColor: '#F8F8F8',
    tabFontSize: 15,
    tabTextColor: '#222222',

    // Text
    textColor: '#000',
    inverseTextColor: '#fff',

    // Title
    titleFontSize: (Platform.OS === 'ios' ) ? 17 : 19,
    subTitleFontSize: (Platform.OS === 'ios' ) ? 12 : 14,
    subtitleColor: '#8e8e93',

    // Other
    borderRadiusBase: (Platform.OS === 'ios' ) ? 5 : 2,
    borderWidth: 1,
    contentPadding: 10,

    get darkenHeader() {
        return Color(this.tabBgColor).darken(0.03).hexString();
    },

    dropdownBg: '#000',
    dropdownLinkColor: '#414142',
    inputLineHeight: 24,
    jumbotronBg: '#C9C9CE',
    jumbotronPadding: 30
}
<commit_msg>Update light.js<commit_after>import Color from 'color';

import {Platform} from 'react-native';

export default {

    // Badge
    badgeBg: '#ED1727',
    badgeColor: '#fff',

    // Button
    btnFontFamily: (Platform.OS === 'ios' ) ? 'HelveticaNeue' : 'Roboto_medium',
    btnDisabledBg: '#b5b5b5',
    btnDisabledClr: '#f1f1f1',

    get btnPrimaryBg () {
        return this.brandPrimary;
    },
    get btnPrimaryColor () {
        return this.inverseTextColor;
    },
    get btnInfoBg () {
        return this.brandInfo;
    },
    get btnInfoColor () {
        return this.inverseTextColor;
    },
    get btnSuccessBg () {
        return this.brandSuccess;
    },
    get btnSuccessColor () {
        return this.inverseTextColor;
    },
    get btnDangerBg () {
        return this.brandDanger;
    },
    get btnDangerColor () {
        return this.inverseTextColor;
    },
    get btnWarningBg () {
        return this.brandWarning;
    },
    get btnWarningColor () {
        return this.inverseTextColor;
    },
    get btnTextSize () {
        return (Platform.OS==='ios') ? this.fontSizeBase* 1.1 :
        this.fontSizeBase-1;
    },
    get btnTextSizeLarge () {
        return this.fontSizeBase* 1.5;
    },
    get btnTextSizeSmall () {
        return this.fontSizeBase* .8;
    },
    get borderRadiusLarge () {
        return this.fontSizeBase* 3.8;
    },

    buttonPadding: 6,

    get iconSizeLarge () {
        return this.iconFontSize* 1.5;
    },
    get iconSizeSmall () {
        return this.iconFontSize* .6;
    },

    // Card
    cardDefaultBg: '#fff',

    // Check Box
    checkboxBgColor: '#039BE5',
    checkboxSize: 23,
    checkboxTickColor: '#fff',

    // Color
    brandPrimary : '#5067FF',
    brandInfo: '#5bc0de',
    brandSuccess: '#5cb85c',
    brandDanger: '#d9534f',
    brandWarning: '#f0ad4e',
    brandSidebar: '#252932',

    // Font
    fontFamily: (Platform.OS === 'ios' ) ? 'HelveticaNeue' : 'Roboto',
    fontSizeBase: 15,

    get fontSizeH1 () {
        return this.fontSizeBase*1.8;
    },
    get fontSizeH2 () {
        return this.fontSizeBase* 1.6;
    },
    get fontSizeH3 () {
        return this.fontSizeBase* 1.4;
    },

    // Footer
    footerHeight: 55,
    footerDefaultBg: (Platform.OS === 'ios' ) ? '#F8F8F8' : '#4179F7',

    //FooterTab
    tabBarTextColor: (Platform.OS === 'ios' ) ? '#6b6b6b' : '#b3c7f9',
    tabBarActiveTextColor: (Platform.OS === 'ios' ) ? '#007aff' : '#fff',
    tabActiveBgColor: (Platform.OS=='ios') ? '#cde1f9' : undefined,
    tabBarBorderRadius: (Platform.OS == 'ios') ? 7 : 0,

    //Tab
    tabDefaultBg: (Platform.OS === 'ios' ) ? '#F8F8F8' : '#4179F7',
    topTabBarTextColor: (Platform.OS === 'ios' ) ? '#6b6b6b' : '#b3c7f9',
    topTabBarActiveTextColor: (Platform.OS === 'ios' ) ? '#007aff' : '#fff',
    topTabActiveBgColor: (Platform.OS=='ios') ? '#cde1f9' : undefined,
    topTabBarBorderColor: (Platform.OS === 'ios' ) ? '#007aff' : '#fff',

    // Header
    iosToolbarBtnColor: '#007aff',
    toolbarDefaultBg: (Platform.OS === 'ios' ) ? '#F8F8F8' : '#4179F7',
    toolbarHeight: (Platform.OS === 'ios' ) ? 64 : 56,
    toolbarIconSize: (Platform.OS === 'ios' ) ? 20 : 22,
    toolbarInputColor: '#CECDD2',
    toolbarInverseBg: '#222',
    toolbarTextColor: (Platform.OS==='ios') ? '#000' : '#fff',
    get statusBarColor() {
        return Color(this.toolbarDefaultBg).darken(0.2).hexString();
    },

    // Icon
    iconFamily: 'Ionicons',
    iconFontSize: (Platform.OS === 'ios' ) ? 30 : 28,
    iconMargin: 7,

    // InputGroup
    inputFontSize: 15,
    inputBorderColor: '#D9D5DC',
    inputSuccessBorderColor: '#2b8339',
    inputErrorBorderColor: '#ed2f2f',

    get inputColor () {
        return this.textColor;
    },
    get inputColorPlaceholder () {
        return '#575757';
    },

    inputGroupMarginBottom: 10,
    inputHeightBase: 40,
    inputPaddingLeft: 5,

    get inputPaddingLeftIcon () {
        return this.inputPaddingLeft* 8;
    },

    // Line Height
    btnLineHeight: 19,
    lineHeightH1: 32,
    lineHeightH2: 27,
    lineHeightH3: 22,
    iconLineHeight: (Platform.OS === 'ios' ) ? 37 : 30,
    lineHeight: (Platform.OS === 'ios' ) ? 20 : 24,

    // List
    listBorderColor: '#ddd',
    listDividerBg: '#ddd',
    listItemHeight: 45,
    listItemPadding: (Platform.OS === 'ios' ) ? 12 : 16,
    listNoteColor: '#808080',
    listNoteSize: 13,

    // Progress Bar
    defaultProgressColor: '#E4202D',
    inverseProgressColor: '#1A191B',

    // Radio Button
    radioBtnSize: (Platform.OS === 'ios') ? 25 : 23,
    radioColor: '#7e7e7e',

    get radioSelectedColor() {
        return Color(this.radioColor).darken(0.2).hexString();
    },

    // Spinner
    defaultSpinnerColor: '#45D56E',
    inverseSpinnerColor: '#1A191B',

    // Tabs
    tabBgColor: '#F8F8F8',
    tabFontSize: 15,
    tabTextColor: '#222222',

    // Text
    textColor: '#000',
    inverseTextColor: '#fff',

    // Title
    titleFontSize: (Platform.OS === 'ios' ) ? 17 : 19,
    subTitleFontSize: (Platform.OS === 'ios' ) ? 12 : 14,
    subtitleColor: '#8e8e93',

    // Other
    borderRadiusBase: (Platform.OS === 'ios' ) ? 5 : 2,
    borderWidth: 1,
    contentPadding: 10,

    get darkenHeader() {
        return Color(this.tabBgColor).darken(0.03).hexString();
    },

    dropdownBg: '#000',
    dropdownLinkColor: '#414142',
    inputLineHeight: 24,
    jumbotronBg: '#C9C9CE',
    jumbotronPadding: 30
}
<|endoftext|>


<commit_before>/**
 * @param {number[]} nums
 * @return {number}
 */
var findDuplicate = function(nums) {
  // 1 2 3 3 4
  // 1 3 3 3 3
  // solution http://keithschwarz.com/interesting/code/?dir=find-duplicate
  var len = nums.length;

  var slow = len -1;
  var fast = len - 1;
  while(true) {
    slow = nums[low] - 1;
    fast = nums[nums[fast] - 1] - 1;

    if (slow === falst) {
       break;
    }
  }

  var finder = l - 1;
  while(true) {
     slow = nums[slow] - 1;
     finder = nums[slow] - 1;

     if (slow === finder) {
       return slow + 1;
     }
  }
};

<commit_msg>Find the Duplicate Number: ac<commit_after>/**
 * @param {number[]} nums
 * @return {number}
 */
var findDuplicate = function(nums) {
  // 1 2 3 3 4
  // 1 3 3 3 3
  // solution http://keithschwarz.com/interesting/code/?dir=find-duplicate
  var len = nums.length;

  var slow = len -1;
  var fast = len - 1;
  while(true) {
    slow = nums[slow] - 1;
    fast = nums[nums[fast] - 1] - 1;

    if (slow === fast) {
       break;
    }
  }

  var finder = len - 1;
  while(true) {
     slow = nums[slow] - 1;
     finder = nums[finder] - 1;

     if (slow === finder) {
       return finder + 1;
     }
  }
};

var eq = require('assert').equal;

eq(findDuplicate([1, 2, 3, 3, 4]), 3);
eq(findDuplicate([2, 1, 1]), 1);
<|endoftext|>


<commit_before>module.exports = {
  entry: './src/index.js',
  output: {
    publicPath: '/assets/',
    filename: 'bundle.js'
  },
  module: {
    loaders: [
      {
        loader: 'babel-loader',
        test: /\.js$/,
        exclude: /node_modules/,
        query: {
          presets: ['es2015', 'stage-2', 'react']
        }
      },
      {
        test: /\.scss$/,
        loaders: ['style', 'css', 'resolve-url?fail', 'sass?sourceMap'],
        exclude: /node_modules/
      },
      {
        test: /\.(jpe?g|png|gif|svg)$/i,
        loaders: [
          'file?hash=sha512&digest=hex&name=img/[name].[ext]',
          'image-webpack?bypassOnDebug&optimizationLevel=7&interlaced=false'
        ],
        exclude: /node_modules/
      },
      {
        test: /\.(eot|woff|woff2|ttf|svg)$/,
        loader: 'url-loader?limit=8192'
      }
    ]
  },
  devServer: {
    publicPath: '/assets',
    filename: 'bundle.js',
    port: 8080,
    host: '0.0.0.0',
    proxy: {
      '/api/*': 'http://localhost:5000'
    }
  },
  devtool: 'source-map'
}
<commit_msg>fix devtools<commit_after>module.exports = {
  entry: './src/index.js',
  output: {
    publicPath: '/assets/',
    filename: 'bundle.js'
  },
  module: {
    loaders: [
      {
        loader: 'babel-loader',
        test: /\.js$/,
        exclude: /node_modules/,
        query: {
          presets: ['es2015', 'stage-2', 'react']
        }
      },
      {
        test: /\.scss$/,
        loaders: ['style', 'css', 'resolve-url?fail', 'sass?sourceMap'],
        exclude: /node_modules/
      },
      {
        test: /\.(jpe?g|png|gif|svg)$/i,
        loaders: [
          'file?hash=sha512&digest=hex&name=img/[name].[ext]',
          'image-webpack?bypassOnDebug&optimizationLevel=7&interlaced=false'
        ],
        exclude: /node_modules/
      },
      {
        test: /\.(eot|woff|woff2|ttf|svg)$/,
        loader: 'url-loader?limit=8192'
      }
    ]
  },
  devServer: {
    publicPath: '/assets',
    filename: 'bundle.js',
    port: 8080,
    host: '0.0.0.0',
    historyApiFallback: true,
    proxy: {
      '/api/*': 'http://localhost:5000'
    }
  },
  devtool: 'source-map'
}
<|endoftext|>


<commit_before>import React, { Component } from 'react'
import { connect } from 'react-redux'
import { Field, reduxForm, formValueSelector } from 'redux-form'
import { RadioButton } from 'material-ui/RadioButton'
import MenuItem from 'material-ui/MenuItem'
import { AutoComplete as MUIAutoComplete } from 'material-ui'
import {
  AutoComplete,
  Checkbox,
  DatePicker,
  TimePicker,
  RadioButtonGroup,
  SelectField,
  Slider,
  TextField,
  Toggle
} from 'redux-form-material-ui'

// validation functions
const required = value => (value == null ? 'Required' : undefined)
const email = value =>
  (value && !/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(value)
    ? 'Invalid email'
    : undefined)
const tooManyPizzas = value => (value > 15 ? 'Are you mad?' : undefined)

class Form extends Component {
  componentDidMount() {
    this.refs.name // the Field
      .getRenderedComponent() // on Field, returns ReduxFormMaterialUITextField
      .getRenderedComponent() // on ReduxFormMaterialUITextField, returns TextField
      .focus() // on TextField
  }

  render() {
    const { handleSubmit, pristine, numPizzas, reset, submitting } = this.props
    return (
      <form onSubmit={handleSubmit}>

          <Field
            name="name"
            component={TextField}
            hintText="Name"
            floatingLabelText="Name"
            validate={required}
            ref="name"
            withRef
          />

          <Field
            name="email"
            component={TextField}
            hintText="Email"
            floatingLabelText="Email"
            validate={[required, email]}
          />

          <Field name="delivery" component={RadioButtonGroup}>
            <RadioButton value="pickup" label="Pickup" />
            <RadioButton value="delivery" label="Delivery" />
          </Field>

How many pizzas do you want?

{numPizzas}

          <Field
            name="pizzas"
            component={Slider}
            defaultValue={0}
            format={null}
            min={0}
            max={20}
            step={1}
            warn={tooManyPizzas}
          />

          <Field
            name="driver"
            component={SelectField}
            hintText="Driver"
            floatingLabelText="Driver"
            validate={required}
          >
            <MenuItem value="alice@redux-pizza.com" primaryText="Alice" />
            <MenuItem value="bob@redux-pizza.com" primaryText="Bob" />
            <MenuItem value="carl@redux-pizza.com" primaryText="Carl" />
          </Field>

          <Field
            name="thinCrust"
            component={Toggle}
            label="Thin Crust"
            labelPosition="right"
          />

          <Field name="pepperoni" component={Checkbox} label="Pepperoni" />

          <Field name="mushrooms" component={Checkbox} label="Mushrooms" />

          <Field name="peppers" component={Checkbox} label="Peppers" />

          <Field
            name="when"
            component={DatePicker}
            format={null}
            hintText="Day of delivery?"
            validate={required}
          />

          <Field
            name="at"
            component={TimePicker}
            format={null}
            defaultValue={null} // TimePicker requires an object,
            // and redux-form defaults to ''
            hintText="At what time?"
            validate={required}
          />

          <Field
            name="notes"
            component={TextField}
            hintText="Notes"
            floatingLabelText="Notes"
            multiLine
            rows={2}
          />

          <Field
            name="cheese"
            component={AutoComplete}
            floatingLabelText="Cheese"
            openOnFocus
            filter={MUIAutoComplete.fuzzyFilter}
            dataSource={['Cheddar', 'Mozzarella', 'Parmesan', 'Provolone']}
          />

          <Field
            name="referral"
            component={AutoComplete}
            floatingLabelText="How did you find us?"
            openOnFocus
            filter={MUIAutoComplete.fuzzyFilter}
            dataSourceConfig={{ text: 'name', value: 'id' }}
            dataSource={[
              { id: 0, name: 'Facebook' },
              { id: 1, name: 'Yelp' },
              { id: 2, name: 'TV Ad' },
              { id: 3, name: 'Friend' },
              { id: 4, name: 'Other' }
            ]}
          />

          <button type="submit" disabled={submitting}>Submit</button>
          <button
            type="button"
            disabled={pristine || submitting}
            onClick={reset}
          >
            Clear
          </button>

      </form>
    )
  }
}

const selector = formValueSelector('example')

Form = connect(state => ({
  numPizzas: selector(state, 'pizzas')
}))(Form)

Form = reduxForm({
  form: 'example',
  initialValues: {
    delivery: 'delivery',
    name: 'Jane Doe',
    cheese: 'Cheddar',
    thinCrust: true,
    pizzas: 1
  }
})(Form)

export default Form
<commit_msg>Removed defaultValue for TimePicker #60 #113<commit_after>import React, { Component } from 'react'
import { connect } from 'react-redux'
import { Field, reduxForm, formValueSelector } from 'redux-form'
import { RadioButton } from 'material-ui/RadioButton'
import MenuItem from 'material-ui/MenuItem'
import { AutoComplete as MUIAutoComplete } from 'material-ui'
import {
  AutoComplete,
  Checkbox,
  DatePicker,
  TimePicker,
  RadioButtonGroup,
  SelectField,
  Slider,
  TextField,
  Toggle
} from 'redux-form-material-ui'

// validation functions
const required = value => (value == null ? 'Required' : undefined)
const email = value =>
  (value && !/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(value)
    ? 'Invalid email'
    : undefined)
const tooManyPizzas = value => (value > 15 ? 'Are you mad?' : undefined)

class Form extends Component {
  componentDidMount() {
    this.refs.name // the Field
      .getRenderedComponent() // on Field, returns ReduxFormMaterialUITextField
      .getRenderedComponent() // on ReduxFormMaterialUITextField, returns TextField
      .focus() // on TextField
  }

  render() {
    const { handleSubmit, pristine, numPizzas, reset, submitting } = this.props
    return (
      <form onSubmit={handleSubmit}>

          <Field
            name="name"
            component={TextField}
            hintText="Name"
            floatingLabelText="Name"
            validate={required}
            ref="name"
            withRef
          />

          <Field
            name="email"
            component={TextField}
            hintText="Email"
            floatingLabelText="Email"
            validate={[required, email]}
          />

          <Field name="delivery" component={RadioButtonGroup}>
            <RadioButton value="pickup" label="Pickup" />
            <RadioButton value="delivery" label="Delivery" />
          </Field>

How many pizzas do you want?

{numPizzas}

          <Field
            name="pizzas"
            component={Slider}
            defaultValue={0}
            format={null}
            min={0}
            max={20}
            step={1}
            warn={tooManyPizzas}
          />

          <Field
            name="driver"
            component={SelectField}
            hintText="Driver"
            floatingLabelText="Driver"
            validate={required}
          >
            <MenuItem value="alice@redux-pizza.com" primaryText="Alice" />
            <MenuItem value="bob@redux-pizza.com" primaryText="Bob" />
            <MenuItem value="carl@redux-pizza.com" primaryText="Carl" />
          </Field>

          <Field
            name="thinCrust"
            component={Toggle}
            label="Thin Crust"
            labelPosition="right"
          />

          <Field name="pepperoni" component={Checkbox} label="Pepperoni" />

          <Field name="mushrooms" component={Checkbox} label="Mushrooms" />

          <Field name="peppers" component={Checkbox} label="Peppers" />

          <Field
            name="when"
            component={DatePicker}
            format={null}
            hintText="Day of delivery?"
            validate={required}
          />

          <Field
            name="at"
            component={TimePicker}
            format={null}
            // and redux-form defaults to ''
            hintText="At what time?"
            validate={required}
          />

          <Field
            name="notes"
            component={TextField}
            hintText="Notes"
            floatingLabelText="Notes"
            multiLine
            rows={2}
          />

          <Field
            name="cheese"
            component={AutoComplete}
            floatingLabelText="Cheese"
            openOnFocus
            filter={MUIAutoComplete.fuzzyFilter}
            dataSource={['Cheddar', 'Mozzarella', 'Parmesan', 'Provolone']}
          />

          <Field
            name="referral"
            component={AutoComplete}
            floatingLabelText="How did you find us?"
            openOnFocus
            filter={MUIAutoComplete.fuzzyFilter}
            dataSourceConfig={{ text: 'name', value: 'id' }}
            dataSource={[
              { id: 0, name: 'Facebook' },
              { id: 1, name: 'Yelp' },
              { id: 2, name: 'TV Ad' },
              { id: 3, name: 'Friend' },
              { id: 4, name: 'Other' }
            ]}
          />

          <button type="submit" disabled={submitting}>Submit</button>
          <button
            type="button"
            disabled={pristine || submitting}
            onClick={reset}
          >
            Clear
          </button>

      </form>
    )
  }
}

const selector = formValueSelector('example')

Form = connect(state => ({
  numPizzas: selector(state, 'pizzas')
}))(Form)

Form = reduxForm({
  form: 'example',
  initialValues: {
    delivery: 'delivery',
    name: 'Jane Doe',
    cheese: 'Cheddar',
    thinCrust: true,
    pizzas: 1
  }
})(Form)

export default Form
<|endoftext|>


<commit_before>/* eslint-disable padded-blocks */

import React from 'react';
import { Card, CardHeader, CardTitle, CardText } from 'material-ui/Card';
import styled from 'styled-components';
import Icons from 'components/Icons';
import RoomIcon from 'material-ui/svg-icons/action/room';
import ZoomIcon from 'material-ui/svg-icons/action/zoom-in';

const IncidentWrap = styled.div`
  .incident-card {
    margin: 0 0 20px;
    display: flex;
  }

  .incident-media {
    max-height: 100px;
    overflow: hidden;
    cursor: pointer;
    background: #fafafa;
    display: flex;
    align-items: center;
    justify-content: center;

    img {
      opacity: 0.5;
      width: 100%;
    }
  }

  .incident-subtitle {
    display: flex;
    font-weight: 700;
  }

  .incident-title {
    font-size: 24px;
  }

  .incident-header-icon {
    background: #5F288D;
    padding: 5px;
    border-radius: 50%;
    color: white;
    width: 30px;
    height: 30px;
  }

  .svg-icon {
    color: #5F288D;
    width: 32px;
    height: 32px;
    margin-right: 10px;
  }
`;

const imageContainerIcon = {
  color: '#5F288D',
  cursor: 'pointer',
  position: 'absolute',
  width: '32px',
  height: '32px',
};

function IncidentItem(props) {

  const Subtitle = (

      <RoomIcon style={{ color: 'rgba(45, 45, 45, 0.5)', width: '20px', height: '20px', marginRight: '5px' }} />
      {props.city ? props.city.name : ''}, {props.county ? props.county.name : ''}

);
  const icon = props.incidentType ? props.incidentType.label.toLowerCase() : '';

  return (
    <IncidentWrap>

      <Card className="incident-card">

        <CardHeader
          title={props.incidentType ? props.incidentType.name : ''}
          avatar={<Icons icon={icon} />}
          textStyle={{ verticalAlign: 'middle' }}
          titleStyle={{ color: '#5F288D' }}
        />

        { props.image ?

            <ZoomIcon style={imageContainerIcon} />

          : null
        }

        <CardTitle
          className="incident-title"
          title={`Sectia ${props.precinct.precinctNumber}`}
          subtitle={Subtitle}
          style={{ paddingBottom: 0 }}
        />

        <CardText>
          {props.description}
        </CardText>

      </Card>
    </IncidentWrap>
  );
}

IncidentItem.propTypes = {
  description: React.PropTypes.string,
  city: React.PropTypes.object,
  name: React.PropTypes.string,
  image: React.PropTypes.string,
  incidentType: React.PropTypes.object,
  county: React.PropTypes.object,
  precinct: React.PropTypes.object,
  precinctNumber: React.PropTypes.number,
};

export default IncidentItem;
<commit_msg>Do not show section name if missing<commit_after>/* eslint-disable padded-blocks */

import React from 'react';
import { Card, CardHeader, CardTitle, CardText } from 'material-ui/Card';
import styled from 'styled-components';
import Icons from 'components/Icons';
import RoomIcon from 'material-ui/svg-icons/action/room';
import ZoomIcon from 'material-ui/svg-icons/action/zoom-in';

const IncidentWrap = styled.div`
  .incident-card {
    margin: 0 0 20px;
    display: flex;
  }

  .incident-media {
    max-height: 100px;
    overflow: hidden;
    cursor: pointer;
    background: #fafafa;
    display: flex;
    align-items: center;
    justify-content: center;

    img {
      opacity: 0.5;
      width: 100%;
    }
  }

  .incident-subtitle {
    display: flex;
    font-weight: 700;
  }

  .incident-title {
    font-size: 24px;
  }

  .incident-header-icon {
    background: #5F288D;
    padding: 5px;
    border-radius: 50%;
    color: white;
    width: 30px;
    height: 30px;
  }

  .svg-icon {
    color: #5F288D;
    width: 32px;
    height: 32px;
    margin-right: 10px;
  }
`;

const imageContainerIcon = {
  color: '#5F288D',
  cursor: 'pointer',
  position: 'absolute',
  width: '32px',
  height: '32px',
};

function IncidentItem(props) {

  const Subtitle = (

      <RoomIcon style={{ color: 'rgba(45, 45, 45, 0.5)', width: '20px', height: '20px', marginRight: '5px' }} />
      {props.city ? props.city.name : ''}, {props.county ? props.county.name : ''}

);
  const icon = props.incidentType ? props.incidentType.label.toLowerCase() : '';

  return (
    <IncidentWrap>

      <Card className="incident-card">

        <CardHeader
          title={props.incidentType ? props.incidentType.name : ''}
          avatar={<Icons icon={icon} />}
          textStyle={{ verticalAlign: 'middle' }}
          titleStyle={{ color: '#5F288D' }}
        />

        { props.image ?

            <ZoomIcon style={imageContainerIcon} />

          : null
        }

        { props.precinct.precinctNumber
          ? <CardTitle
            className="incident-title"
            title={`Sectia ${props.precinct.precinctNumber}`}
            subtitle={Subtitle}
            style={{ paddingBottom: 0 }}
          />
          : <CardTitle
            className="incident-title"
            subtitle={Subtitle}
            style={{ paddingBottom: 0 }}
          />
        }

        <CardText>
          {props.description}
        </CardText>

      </Card>
    </IncidentWrap>
  );
}

IncidentItem.propTypes = {
  description: React.PropTypes.string,
  city: React.PropTypes.object,
  name: React.PropTypes.string,
  image: React.PropTypes.string,
  incidentType: React.PropTypes.object,
  county: React.PropTypes.object,
  precinct: React.PropTypes.object,
  precinctNumber: React.PropTypes.number,
};

export default IncidentItem;
<|endoftext|>


<commit_before>var debug 						= require('debug')('venn'),
	zeroPush 					= require("nzero-push"),
	MessagingServiceProvider 	= require("../../messaging_service_provider"),
	MessagingServiceStatus 		= require('../../messaging_service_status'),
	MessagingUserStatus 		= require('../../messaging_user_status');

/*=============================================================================

Define ZeroPush Service Provider

=============================================================================*/
function ZeroPush(keys){
  if (!keys) return
  this.name = "zeropush"
  this.keys = keys

  this.initialize = function() {
    this.client = new zeroPush(this.keys.server_token);
  }

  this.send = function(data, callback) {
    var context = this;
	var deviceType = getType(data.deviceType);
	var notification = getNotificationObject(deviceType, data.message);

	context.client.register([data.deviceToken], function(err, response) {
		var zeropushStat;

		if (err) {
			zeropushStat = new ZeroPushErrorStatus(err);
			debug("-_-_ FAILED with zeropush _-_-");
            debug(zeropushStat);
            return callback(zeropushStat);
		}

		context.client.notify(deviceType, [data.deviceToken], notification, function (err, result) {

	        if (err) {
	          zeropushStat = new ZeroPushErrorStatus(err);
	          debug("-_-_ FAILED with zeropush _-_-");
	          debug(zeropushStat);
	          return callback(zeropushStat);
	        }
	        else {
	          zeropushStat = new ZeroPushSuccessStatus(result);
	          debug("-_-_ sent with zeropush _-_-");
	          result.service = context;
	          result.status = zeropushStat;
	          debug(result);
	          return callback(null, result);
	        }
		});
    });
  }

  debug("zeropush initing")
  this.initialize()
}

ZeroPush.prototype = new MessagingServiceProvider()

/*=============================================================================

Define Zero Push Service Status Handlers

=============================================================================*/

/*
Success Status

@param response     JSON response object from Zero Push service
*/
function ZeroPushSuccessStatus(response) {
  MessagingServiceStatus.call(this, 'zeropush');

  // Message successfully sent
  this.state.message = 'Sent: ' +  response.sent_count;
  this.state.code = this.StatusCodes.SUCCESS;
}

ZeroPushSuccessStatus.prototype = Object.create(MessagingServiceStatus.prototype);
ZeroPushSuccessStatus.prototype.constructor = ZeroPushSuccessStatus;

/*
Error Status

@param response     JSON response object from Zero Push service
*/
function ZeroPushErrorStatus(response) {
  MessagingServiceStatus.call(this, 'zeropush');

  // There was an error when attempting to send message
  this.state.message = response.name + ': ' + response.message;

  if (response.name === 'InvalidPayloadError') this.state.code = this.StatusCodes.DATA_REJECTED;
  else this.state.code = this.StatusCodes.DEFAULT;
}

ZeroPushErrorStatus.prototype = Object.create(MessagingServiceStatus.prototype);
ZeroPushErrorStatus.prototype.constructor = ZeroPushErrorStatus;

/*=============================================================================

Define ZeroPush User Status Handler

=============================================================================*/
function ZeroPushUserStatus(message, code) {
  MessagingUserStatus.call(this, 'zeropush');

  // Put logic here for handling any possible user errors
}

ZeroPushUserStatus.prototype = Object.create(MessagingUserStatus.prototype);
ZeroPushUserStatus.prototype.constructor = ZeroPushUserStatus;

/*=============================================================================

Define ZeroPush Helper Functions

=============================================================================*/

getType = function (deviceTypeString) {
	var type = null;

	// See https://github.com/linitix/nzero-push/wiki/notify for options (look for platform)
	switch (deviceTypeString.toLowerCase()) {
		case 'ios':
			type = 'ios_macos';
			break;
		case 'safari':
			type = 'safari';
			break;
		case 'android':
			type = 'android';
			break;
		default:
			type = 'invalid_device_type';
			break;
	}

	return type;
}

getNotificationObject = function (deviceType, message) {
	var notification = {}

	// See https://github.com/linitix/nzero-push/wiki/notify for options
	switch (deviceType.toLowerCase()) {
		case 'ios_macos':
			notification.alert = message;
			break;
		case 'safari':
			notification.body = message;
			break;
		case 'android':
			notification.data = {};
			notification.data.message = message;
			break;
		default:
			// Nothing to do
			break;
	}

	return notification;
}

module.exports = ZeroPush<commit_msg>Refactor. for #54<commit_after>var debug 						= require('debug')('venn'),
	zeroPush 					= require("nzero-push"),
	MessagingServiceProvider 	= require("../../messaging_service_provider"),
	MessagingServiceStatus 		= require('../../messaging_service_status'),
	MessagingUserStatus 		= require('../../messaging_user_status');

/*=============================================================================

Define ZeroPush Service Provider

=============================================================================*/
function ZeroPush(keys){
  if (!keys) return
  this.name = "zeropush"
  this.keys = keys

  this.initialize = function() {
    this.client = new zeroPush(this.keys.server_token);
  }

  this.send = function(data, callback) {
    var context = this;
    var zeropushStat;
	var deviceType = getType(data.deviceType);
	var notification = getNotificationObject(deviceType, data.message);

	context.client.register([data.deviceToken], function(err, response) {

		if (err) {
			zeropushStat = new ZeroPushErrorStatus(err);
			debug("-_-_ FAILED with zeropush _-_-");
            debug(zeropushStat);
            return callback(zeropushStat);
		}

		context.client.notify(deviceType, [data.deviceToken], notification, function (err, result) {

	        if (err) {
	          zeropushStat = new ZeroPushErrorStatus(err);
	          debug("-_-_ FAILED with zeropush _-_-");
	          debug(zeropushStat);
	          return callback(zeropushStat);
	        }
	        else {
	          zeropushStat = new ZeroPushSuccessStatus(result);
	          debug("-_-_ sent with zeropush _-_-");
	          result.service = context;
	          result.status = zeropushStat;
	          debug(result);
	          return callback(null, result);
	        }
		});
    });
  }

  debug("zeropush initing")
  this.initialize()
}

ZeroPush.prototype = new MessagingServiceProvider()

/*=============================================================================

Define Zero Push Service Status Handlers

=============================================================================*/

/*
Success Status

@param response     JSON response object from Zero Push service
*/
function ZeroPushSuccessStatus(response) {
  MessagingServiceStatus.call(this, 'zeropush');

  // Message successfully sent
  this.state.message = 'Sent: ' +  response.sent_count;
  this.state.code = this.StatusCodes.SUCCESS;
}

ZeroPushSuccessStatus.prototype = Object.create(MessagingServiceStatus.prototype);
ZeroPushSuccessStatus.prototype.constructor = ZeroPushSuccessStatus;

/*
Error Status

@param response     JSON response object from Zero Push service
*/
function ZeroPushErrorStatus(response) {
  MessagingServiceStatus.call(this, 'zeropush');

  // There was an error when attempting to send message
  this.state.message = response.name + ': ' + response.message;

  if (response.name === 'InvalidPayloadError') this.state.code = this.StatusCodes.DATA_REJECTED;
  else this.state.code = this.StatusCodes.DEFAULT;
}

ZeroPushErrorStatus.prototype = Object.create(MessagingServiceStatus.prototype);
ZeroPushErrorStatus.prototype.constructor = ZeroPushErrorStatus;

/*=============================================================================

Define ZeroPush User Status Handler

=============================================================================*/
function ZeroPushUserStatus(message, code) {
  MessagingUserStatus.call(this, 'zeropush');

  // Put logic here for handling any possible user errors
}

ZeroPushUserStatus.prototype = Object.create(MessagingUserStatus.prototype);
ZeroPushUserStatus.prototype.constructor = ZeroPushUserStatus;

/*=============================================================================

Define ZeroPush Helper Functions

=============================================================================*/

getType = function (deviceTypeString) {
	var type = null;

	// See https://github.com/linitix/nzero-push/wiki/notify for options (look for platform)
	switch (deviceTypeString.toLowerCase()) {
		case 'ios':
			type = 'ios_macos';
			break;
		case 'safari':
			type = 'safari';
			break;
		case 'android':
			type = 'android';
			break;
		default:
			type = 'invalid_device_type';
			break;
	}

	return type;
}

getNotificationObject = function (deviceType, message) {
	var notification = {}

	// See https://github.com/linitix/nzero-push/wiki/notify for options
	switch (deviceType.toLowerCase()) {
		case 'ios_macos':
			notification.alert = message;
			break;
		case 'safari':
			notification.body = message;
			break;
		case 'android':
			notification.data = {};
			notification.data.message = message;
			break;
		default:
			// Nothing to do
			break;
	}

	return notification;
}

module.exports = ZeroPush<|endoftext|>