<commit_before>// third party imports
import MediaQuery from 'mediaquery'
import transform from 'lodash/transform'
import reduce from 'lodash/reduce'
// local imports
import CALCULATE_RESPONSIVE_STATE from '../actions/types/CALCULATE_RESPONSIVE_STATE'

// default breakpoints
const defaultBreakpoints = {
    extraSmall: 480,
    small: 768,
    medium: 992,
    large: 1200,
}
// media type to default to when no `window` present
const defaultMediaType = 'infinity'
// orientation to default to when no `window` present
const defaultOrientation = null

/**
 * Compute the `lessThan` object based on the browser width.
 * @arg {number} browserWidth - Width of the browser.
 * @arg {object} breakpoints - The breakpoints object.
 * @returns {object} The `lessThan` object.  Its keys are the same as the
 * keys of the breakpoints object.  The value for each key indicates whether
 * or not the browser width is less than the breakpoint.
 */
function getLessThan(browserWidth, breakpoints, currentMediaType) {
    return transform(breakpoints, (result, breakpoint, mediaType) => {
        // if the breakpoint is a number
        if (typeof breakpoint === 'number') {
            // store wether or not it is less than the breakpoint
            result[mediaType] = browserWidth < breakpoint && mediaType !== currentMediaType
        // handle non numerical breakpoints specially
        } else {
            result[mediaType] = false
        }
    })
}

/**
 * Compute the `greaterThan` object based on the browser width.
 * @arg {number} browserWidth - Width of the browser.
 * @arg {object} breakpoints - The breakpoints object.
 * @returns {object} The `greaterThan` object.  Its keys are the same as the
 * keys of the breakpoints object.  The value for each key indicates whether
 * or not the browser width is greater than the breakpoint.
 */
function getGreaterThan(browserWidth, breakpoints) {
    return transform(breakpoints, (result, breakpoint, mediaType) => {
        // if the breakpoint is a number
        if (typeof breakpoint === 'number') {
            // store wether or not it is greater than the breakpoint
            result[mediaType] = browserWidth > breakpoint
        } else {
            result[mediaType] = false
        }
    })
}

/**
 * Gets the current media type from the global `window`.
 * @arg {object} mediaQueries - The media queries object.
 * @arg {string} infinityMediaType - The infinity media type.
 * @returns {string} The window's current media type.  This is the key of the
 * breakpoint that is the next breakpoint larger than the window.
 */
function getMediaType(matchMedia, mediaQueries, infinityMediaType) {
    // if there's no window
    if (typeof matchMedia === 'undefined') {
        // return the infinity media type
        return infinityMediaType
    }

    // there is a window, so compute the true media type
    return reduce(mediaQueries, (result, query, type) => {
        // return the new type if the query matches otherwise the previous one
        return matchMedia(query).matches ? type : result
    // use the infinity media type
    }, infinityMediaType)
}

/**
 * Gets the current media type from the global `window`.
 * @arg {object} mediaQueries - The media queries object.
 * @returns {string} The window's current media type.  This is the key of the
 * breakpoint that is the next breakpoint larger than the window.
 */
function getOrientation(matchMedia) {
    // if there's no window
    if (typeof matchMedia === 'undefined') {
        // return the default
        return defaultOrientation
    }

    const mediaQueries = {
        portrait: '(orientation: portrait)',
        landscape: '(orientation: landscape)',
    }

    // there is a window, so compute the true orientation
    return reduce(mediaQueries, (result, query, type) => {
        // return the new type if the query matches otherwise the previous one
        return matchMedia(query).matches ? type : result
    // use the default orientation
    }, defaultOrientation)
}

// export the reducer factory
export default (breakpoints = defaultBreakpoints, infinityMediaType = defaultMediaType, customVariableFactory = () => {}) => {
    // add `infinity` breakpoint for upper bound
    breakpoints[infinityMediaType] = Infinity
    // media queries associated with the breakpoints
    const mediaQueries = MediaQuery.asObject(breakpoints)

    // return reducer for handling the responsive state
    return (state, {type, matchMedia, innerWidth, innerHeight}) => {
        // if told to recalculate state or state has not yet been initialized
        if (type === CALCULATE_RESPONSIVE_STATE || typeof state === 'undefined') {
            // the current media type
            const mediaType = getMediaType(matchMedia, mediaQueries, infinityMediaType)
            // the current orientation
            const orientation = getOrientation(matchMedia)
            // return calculated state
            return {
                _responsiveState: true,
                width: innerWidth,
                height: innerHeight,
                lessThan: getLessThan(innerWidth, breakpoints, mediaType),
                greaterThan: getGreaterThan(innerWidth, breakpoints),
                mediaType,
                orientation,
                breakpoints,
                ...customVariableFactory({matchMedia, mediaQueries, breakpoints, innerWidth, innerHeight, mediaType, orientation}),
            }
        }
        // otherwise return the previous state
        return state
    }
}
<commit_msg>cleaned up way the customVariableFactory is used<commit_after>// third party imports
import MediaQuery from 'mediaquery'
import transform from 'lodash/transform'
import reduce from 'lodash/reduce'
// local imports
import CALCULATE_RESPONSIVE_STATE from '../actions/types/CALCULATE_RESPONSIVE_STATE'

// default breakpoints
const defaultBreakpoints = {
    extraSmall: 480,
    small: 768,
    medium: 992,
    large: 1200,
}
// media type to default to when no `window` present
const defaultMediaType = 'infinity'
// orientation to default to when no `window` present
const defaultOrientation = null

/**
 * Compute the `lessThan` object based on the browser width.
 * @arg {number} browserWidth - Width of the browser.
 * @arg {object} breakpoints - The breakpoints object.
 * @returns {object} The `lessThan` object.  Its keys are the same as the
 * keys of the breakpoints object.  The value for each key indicates whether
 * or not the browser width is less than the breakpoint.
 */
function getLessThan(browserWidth, breakpoints, currentMediaType) {
    return transform(breakpoints, (result, breakpoint, mediaType) => {
        // if the breakpoint is a number
        if (typeof breakpoint === 'number') {
            // store wether or not it is less than the breakpoint
            result[mediaType] = browserWidth < breakpoint && mediaType !== currentMediaType
        // handle non numerical breakpoints specially
        } else {
            result[mediaType] = false
        }
    })
}

/**
 * Compute the `greaterThan` object based on the browser width.
 * @arg {number} browserWidth - Width of the browser.
 * @arg {object} breakpoints - The breakpoints object.
 * @returns {object} The `greaterThan` object.  Its keys are the same as the
 * keys of the breakpoints object.  The value for each key indicates whether
 * or not the browser width is greater than the breakpoint.
 */
function getGreaterThan(browserWidth, breakpoints) {
    return transform(breakpoints, (result, breakpoint, mediaType) => {
        // if the breakpoint is a number
        if (typeof breakpoint === 'number') {
            // store wether or not it is greater than the breakpoint
            result[mediaType] = browserWidth > breakpoint
        } else {
            result[mediaType] = false
        }
    })
}

/**
 * Gets the current media type from the global `window`.
 * @arg {object} mediaQueries - The media queries object.
 * @arg {string} infinityMediaType - The infinity media type.
 * @returns {string} The window's current media type.  This is the key of the
 * breakpoint that is the next breakpoint larger than the window.
 */
function getMediaType(matchMedia, mediaQueries, infinityMediaType) {
    // if there's no window
    if (typeof matchMedia === 'undefined') {
        // return the infinity media type
        return infinityMediaType
    }

    // there is a window, so compute the true media type
    return reduce(mediaQueries, (result, query, type) => {
        // return the new type if the query matches otherwise the previous one
        return matchMedia(query).matches ? type : result
    // use the infinity media type
    }, infinityMediaType)
}

/**
 * Gets the current media type from the global `window`.
 * @arg {object} mediaQueries - The media queries object.
 * @returns {string} The window's current media type.  This is the key of the
 * breakpoint that is the next breakpoint larger than the window.
 */
function getOrientation(matchMedia) {
    // if there's no window
    if (typeof matchMedia === 'undefined') {
        // return the default
        return defaultOrientation
    }

    const mediaQueries = {
        portrait: '(orientation: portrait)',
        landscape: '(orientation: landscape)',
    }

    // there is a window, so compute the true orientation
    return reduce(mediaQueries, (result, query, type) => {
        // return the new type if the query matches otherwise the previous one
        return matchMedia(query).matches ? type : result
    // use the default orientation
    }, defaultOrientation)
}

// export the reducer factory
export default (breakpoints = defaultBreakpoints, infinityMediaType = defaultMediaType, customVariableFactory = () => {}) => {
    // add `infinity` breakpoint for upper bound
    breakpoints[infinityMediaType] = Infinity
    // media queries associated with the breakpoints
    const mediaQueries = MediaQuery.asObject(breakpoints)

    // return reducer for handling the responsive state
    return (state, {type, matchMedia, innerWidth, innerHeight}) => {
        // if told to recalculate state or state has not yet been initialized
        if (type === CALCULATE_RESPONSIVE_STATE || typeof state === 'undefined') {
            // the current media type
            const mediaType = getMediaType(matchMedia, mediaQueries, infinityMediaType)
            // the current orientation
            const orientation = getOrientation(matchMedia)
            // build the responsive state
            const responsiveState = {
                _responsiveState: true,
                width: innerWidth,
                height: innerHeight,
                lessThan: getLessThan(innerWidth, breakpoints, mediaType),
                greaterThan: getGreaterThan(innerWidth, breakpoints),
                mediaType,
                orientation,
                breakpoints,
            }

            // return calculated state
            return {
                ...responsiveState,
                ...customVariableFactory(responsiveState),
            }
        }
        // otherwise return the previous state
        return state
    }
}
<|endoftext|>


<commit_before>/**
* Porsche.js is licensed under the MIT license. If a copy of the
* MIT-license was not distributed with this file, You can obtain one at:
* http://opensource.org/licenses/mit-license.html.
*
* @author: Yang Yang (compking@gmail.com)
* @license MIT
* @copyright Yang Yang, 2015
*/

"use strict";
var Class = require("../class");
var YObject = require("../yobject");

/**
 * Base struct for rectangle
 * @class Rectangle
 * @extends YObject
 */
Class.define("framework.ui.Rectangle", YObject, {
    /**
     * Constructor
     * @method Button#initialize
     * @param {Number} x left edge of rectangle, in pixels.
     * @param {Number} y top edge of rectangle, in pixels.
     * @param {Number} width width edge of rectangle, in pixels.
     * @param {Number} height height edge of rectangle, in pixels.
     */
    initialize: function(left, top, width, height) {
        YObject.prototype.initialize.apply(this, arguments);
        this._left = left;
        this._top = top;
        this._width = width;
        this._height = height;
    },

    /**
     * @name Rectangle#left
     * @type {Number}
     * @description x-axis value.
     */
    get left() {
        return this._left;
    },

    set left(value) {
        this._left = value;
    },

    /**
     * @name Rectangle#top
     * @type {Number}
     * @description y-axis value.
     */
    get top() {
        return this._top;
    },

    set top(value) {
        this._top = value;
    },

    get right() {
        return this._left + this._width;
    },

    set right(value) {
        this._left = value - this._width;
    },

    get bottom() {
        return this._top + this._height;
    },

    set bottom(value) {
        this._top = value - this._height;
    },

    get width() {
        return this._width;
    },

    set width(value) {
        this._width = value;
    },

    get height() {
        return this._height;
    },

    set height(value) {
        this._height = value;
    },

    empty: function() {
        this._left = 0;
        this._top = 0;
        this._width = 0;
        this._height = 0;
    },

    assign: function(left, top, width, height) {
        this._left = left;
        this._top = top;
        this._width = width;
        this._height = height;
    },

    offset: function(dx, dy) {
        this._left += dx;
        this._top += dy;
    },

    offsetTo: function(left, top) {
        this._left = left;
        this._top = top;
    },

    /**
     * Returns a new rectangle representing the union of this rectangle with the
     * specified rectangle.
     * @method Rectangle#unite
     * @param {Rectangle} rect the rectangle to be combined with this rectangle
     * @return {Rectangle} the smallest rectangle containing both the specified
     *                     rectangle and this rectangle.
     */
    unite: function(rect) {
        if (this._width === 0 && this._height === 0) {
            this._left = rect.left;
            this._top = rect.top;
            this._width = rect.width;
            this._height = rect.height;
            return;
        }
        var x1 = Math.min(this._left, rect.left);
        var y1 = Math.min(this._top, rect.top);
        var x2 = Math.max(this._left + this._width, rect.left + rect.width);
        var y2 = Math.max(this._top + this._height, rect.top + rect.height);
        this._left = x1;
        this._top = y1;
        this._width = x2 - x1;
        this._height = y2 - y1;
    },

    /**
     * Returns a new rectangle representing the intersection of this rectangle
     * with the specified rectangle.
     * @method Rectangle#intersect
     * @param {Rectangle} rect The rectangle to be intersected with this
     *                         rectangle
     * @return {Rectangle} the largest rectangle contained in both the specified
     *                     rectangle and in this rectangle
     */
    intersect: function(rect) {
        var x1 = Math.max(this._left, rect.left);
        var y1 = Math.max(this._top, rect.top);
        var x2 = Math.min(this._left + this._width, rect.right);
        var y2 = Math.min(this._top + this._height, rect.bottom);

        this._left = x1;
        this._top = y1;
        this._width = x2 - x1;
        this._height = y2 - y1;
    },

    isEmpty: function() {
        return this._left === 0 && this._top === 0 && this._width === 0 && this._height === 0;
    },

    intersects: function(rect) {
        return rect.right > this._left && rect.bottom > this._top &&
            rect.left < this._left + this._width && rect.top < this._top + this._height;
    },

    touches: function(rect) {
        return rect.right >= this._left && rect.bottom >= this._top &&
            rect.left <= this._left + this._width && rect.top <= this._top + this._height;
    },

    /**
     * Returns true if this rectangle fully encloses the described point or rectangle.
     * @method Rectangle#contains
     * @param {Rectangle} rect The rectangle to be intersected with this
     *                         rectangle
     * @return {Boolean} True if the described point or rectangle is contained within this rectangle.
    */
    contains: function(rect) {
        return rect.left >= this._left && rect.right <= this._left + this._width &&
            rect.top >= this._top && rect.bottom <= this._top + this._height;
    },

    containsXY: function(x, y) {
        return x >= this._left && y >= this._top && x <= this._left + this._width && y <= this._top + this._height;
    },

    containsPoint: function(point) {
        return point.x >= this._left && point.y >= this._top && point.x <= this._left + this._width && point.y <= this._top + this._height;
    },

    /**
     * copy this rectangle to a new object.
     * @return {Rectangle} rect other rectangle to be checked with.
     * @method Rectangle#clone
     */
    clone: function() {
        return new this.constructor(this._left, this._top, this._width, this._height);
    },

    /**
     * Check the point equal with current or not.
     * @method Rectangle#equals
     * @param {Rectangle} rect the rectangle to be checked.
     * @return {boolean} whether equal
     */
    equals: function(rect) {
        return this._left === rect.left && this._top === rect.top &&
            this._width === rect.width && this._height === rect.height;
    },

    toString: function() {
        return this.className + "(" + this._left + "," + this._top + " - " + this._width + "," + this._height + ")";
    }
}, module);
<commit_msg>refined rectangle jsdoc<commit_after>/**
* Porsche.js is licensed under the MIT license. If a copy of the
* MIT-license was not distributed with this file, You can obtain one at:
* http://opensource.org/licenses/mit-license.html.
*
* @author: Yang Yang (compking@gmail.com)
* @license MIT
* @copyright Yang Yang, 2015
*/

"use strict";
var Class = require("../class");
var YObject = require("../yobject");

/**
 * Rectangle that represents by the coordinates of its 4 edges (left, top, right bottom).
 * These fields can be accessed directly. Use width and height to retrieve the rectangle's width and height.
 * Note that most methods do not check to see that the coordinates are sorted correctly (i.e. left <= right and top <= bottom).
 * @class Rectangle
 * @extends YObject
 */
Class.define("framework.ui.Rectangle", YObject, {
    /**
     * Constructor that create a rectangle.
     * @method Rectangle#initialize
     * @param {Number} left - the X coordinate of the left side of the rectangle.
     * @param {Number} top - the Y coordinate of the top of the rectangle
     * @param {Number} right - the X coordinate of the right side of the rectangle
     * @param {Number} bottom - the Y coordinate of the bottom of the rectangle
     */
    initialize: function(left, top, right, bottom) {
        YObject.prototype.initialize.apply(this, arguments);

        this._left = left;
        this._top = top;
        this._right = right;
        this._bottom = bottom;
    },

    /**
     * Destructor that destroy this rectangle.
     * @method Rectangle#destroy
     */
    destroy: function() {
        YObject.prototype.destroy.apply(this, arguments);
    },

    /**
     * @name Rectangle#left
     * @type {Number}
     * @description the X coordinate of the left side of the rectangle.
     */
    get left() {
        return this._left;
    },

    set left(value) {
        this._left = value;
    },

    /**
     * @name Rectangle#top
     * @type {Number}
     * @description the Y coordinate of the top side of the rectangle.
     */
    get top() {
        return this._top;
    },

    set top(value) {
        this._top = value;
    },

    /**
     * @name Rectangle#right
     * @type {Number}
     * @description the X coordinate of the right side of the rectangle.
     */
    get right() {
        return this._right;
    },

    set right(value) {
        this._right = value;
    },

    /**
     * @name Rectangle#top
     * @type {Number}
     * @description the Y coordinate of the bottom side of the rectangle.
     */
    get bottom() {
        return this._bottom;
    },

    set bottom(value) {
        this._bottom = value;
    },

    /**
     * @name Rectangle#width
     * @type {Number}
     * @description the rectangle's width.
     * This does not check for a valid rectangle (i.e. left <= right) so the result may be negative.
     */
    get width() {
        return this._right - this._left;
    },

    /**
     * @name Rectangle#height
     * @type {Number}
     * @description the rectangle's height.
     * This does not check for a valid rectangle (i.e. top <= bottom) so the result may be negative.
     */
    get height() {
        return this._bottom - this._top;
    },

    /**
     * Set the rectangle to an empty rectangle (0,0,0,0).
     * @method Rectangle#empty
     */
    empty: function() {
        this._left = 0;
        this._top = 0;
        this._right = 0;
        this._bottom = 0;
    },

    /**
     * Set the rectangle's coordinates to the specified values.
     * Note that no range checking is performed, so it is up to the caller to ensure that left <= right and top <= bottom.
     * @method Rectangle#assign
     * @param {Number} left - the X coordinate of the left side of the rectangle.
     * @param {Number} top - the Y coordinate of the top of the rectangle.
     * @param {Number} right - the X coordinate of the right side of the rectangle.
     * @param {Number} bottom - the Y coordinate of the bottom of the rectangle.
     */
    assign: function(left, top, right, bottom) {
        this._left = left;
        this._top = top;
        this._right = right;
        this._bottom = bottom;
    },

    /**
     * Offset the rectangle by adding dx to its left and right coordinates,
     * and adding dy to its top and bottom coordinates.
     * @method Rectangle#offset
     * @param {Number} dx - the amount to add to the rectangle's left and right coordinates.
     * @param {Number} dy - the amount to add to the rectangle's top and bottom coordinates.
     */
    offset: function(dx, dy) {
        this._left += dx;
        this._top += dy;
    },

    /**
     * Offset the rectangle to a specific (left, top) position,
     * keeping its width and height the same.
     * @method Rectangle#offsetTo
     * @param {Number} left - the new left coordinate for the rectangle.
     * @param {Number} top  - the new top coordinate for the rectangle.
     */
    offsetTo: function(left, top) {
        this._left = left;
        this._top = top;
    },

    /**
     * Update this rectangle to enclose itself and the specified rectangle.
     * If the specified rectangle is empty, nothing is done. If this rectangle is empty it is set to the specified rectangle.
     * @method Rectangle#unite
     * @param {Rectangle} rect - the rectangle to be combined with this rectangle.
     */
    unite: function(rect) {
        if (this._right - this._top === 0 && this._bottom - this._top === 0) {
            this._left = rect.left;
            this._top = rect.top;
            this._right = rect.right;
            this._bottom = rect.bottom;
            return;
        }
        this._left = Math.min(this._left, rect.left);
        this._top = Math.min(this._top, rect.top);
        this._right = Math.max(this._right, rect.right);
        this._bottom = Math.max(this._bottom, rect.bottom);
    },

    /**
     * Update this rectangle to the intersection of this rectangle with the specified rectangle.
     * @method Rectangle#intersect
     * @param {Rectangle} rect - the rectangle to be intersected with this rectangle.
     */
    intersect: function(rect) {
        this._left = Math.max(this._left, rect.left);
        this._top = Math.max(this._top, rect.top);
        this._right = Math.min(this._right, rect.right);
        this._bottom = Math.min(this._bottom, rect.bottom);
    },

    /**
     * Indicates whether the rectangle is empty.
     * @method Rectangle#isEmpty
     * @return {Boolean} true if the rectangle is empty (left >= right or top >= bottom).
     */
    isEmpty: function() {
        return this._left === 0 && this._top === 0 && this._right === 0 && this._bottom === 0;
    },

    /**
     * Indicates whether this rectangle intersects the specified rectangle.
     * @method Rectangle#intersects
     * @param {Rectangle} rect - the rectangle being intersected with this rectangle.
     * @return {Boolean} true if this rectangle intersects the specified rectangle, otherwise false.
     */
    intersects: function(rect) {
        return rect.right > this._left && rect.bottom > this._top &&
            rect.left < this._right && rect.top < this._bottom;
    },

    /**
     * Indicates whether this rectangle touches the specified rectangle.
     * @method Rectangle#touches
     * @param {Rectangle} rect - the rectangle being touched with this rectangle.
     * @return {Boolean} true if this rectangle touches the specified rectangle, otherwise false.
     */
    touches: function(rect) {
        return rect.right >= this._left && rect.bottom >= this._top &&
            rect.left <= this._right && rect.top <= this._bottom;
    },

    /**
     * Indicates whether the specified rectangle is inside or equal to this rectangle.
     * An empty rectangle never contains another rectangle.
     * @method Rectangle#contains
     * @param {Rectangle} rect - the rectangle being tested for containment.
     * @return {Boolean} true if the specified rectangle is inside or equal to this rectangle, otherwise false.
    */
    contains: function(rect) {
        return rect.left >= this._left && rect.right <= this._left + this._width &&
            rect.top >= this._top && rect.bottom <= this._top + this._height;
    },

    /**
     * Indicates whether the specified point is inside this rectangle.
     * The left and top are considered to be inside, while the right and bottom are not.
     * This means that for a x,y to be contained: left <= x < right and top <= y < bottom.
     * An empty rectangle never contains any point.
     * @method Rectangle#containsXY
     * @param {Number} x - the X coordinate of the point being tested for containment.
     * @param {Number} y - the Y coordinate of the point being tested for containment.
     * @return {Boolean} true if (x,y) is inside the rectangle, otherwise false.
     */
    containsXY: function(x, y) {
        return x >= this._left && y >= this._top && x <= this._right && y <= this._bottom;
    },

    /**
     * Indicates whether the specified point is inside this rectangle.
     * The left and top are considered to be inside,
     * while the right and bottom are not.
     * This means that for a x,y to be contained: left <= x < right and top <= y < bottom.
     * An empty rectangle never contains any point.
     * @method Rectangle#containsXY
     * @param {Point} point - the point being tested for containment.
     * @return {Boolean} true if the point is inside the rectangle, otherwise false.
     */
    containsPoint: function(point) {
        return point.x >= this._left && point.y >= this._top && point.x <= this._left + this._width && point.y <= this._top + this._height;
    },

    /**
     * Clone a new rectangle from this rectangle.
     * @method Rectangle#clone
     * @return {Rectangle} a new rectangle that has the same left, top, right and bottom value with this rectangle.
     * @protected
     * @override
     */
    clone: function() {
        return new this.constructor(this._left, this._top, this._right, this._bottom);
    },

    /**
     * Check whether this rectangle equals a specified rectangle.
     * @method Rectangle#equals
     * @param {Rectangle} rect - the specified rectangle.
     * @return {Boolean} true means equal, otherwise false.
     * @protected
     * @override
     */
    equals: function(rect) {
        return this._left === rect.left && this._top === rect.top &&
            this._right === rect.right && this._bottom === rect.bottom;
    },

    /**
     * Returns a human-readable rectangle string.
     * @method Rectangle#toString
     * @return {String} the rectangle string.
     * @protected
     * @override
     */
    toString: function() {
        return this.className + "(" + this._left + "," + this._top + " - " + this._right + "," + this._bottom + ")";
    }
}, module);
<|endoftext|>


<commit_before>#!/usr/bin/env node

var p = require('child_process');
var fs = require('fs');
var path = require('path');

var config = {
  cwd: __dirname,
  encoding: 'utf8',
  stdio: [0, 1, 2],
  shell: true
};

function e(cmd) {
  console.log(`>>>>>> running command: ${cmd}`)
  //p.execSync(cmd, config)
  console.log(`<<<<<<`)
}

var node_modules = '../node_modules';

var includes = ['reason-react'].map(x => path.join(__dirname, node_modules, x, 'lib/ocaml')).map(x => `-I ${x}`).join(' ');

var cmi_files =
  [
  'reactDOMRe', 'reactDOMServerRe', 'reactEventRe', 'reasonReact'
].map(x => `${x}.cmi:/cmis/${x}.cmi`).map(x => `--file ${x}`).join(' ');

e(`js_of_ocaml --toplevel +weak.js ./polyfill.js jsc.byte ${includes} ${cmi_files} -o ./libs.js`);

<commit_msg>Remove regenerateLibs.js<commit_after><|endoftext|>


<commit_before><commit_msg>array+1<commit_after>// Given a non-negative number represented as an array of digits, plus one to the number.
// The digits are stored such that the most significant digit is at the head of the list.

function plusOne(arr){
	var n = arr.length;
	if(arr[n-1] !== 9){
		arr[n-1]++;
	} else {

		var q = n-1;
		while(arr[q] === 9 && q>0){
			arr[q] = 0; //find all the connected 9s
			q--;
		}
		arr[q]++;

		if(arr[0] === 10){
			//expand array
			arr[0] = 1;
			arr.push(0);
		}

	}
	return arr;
}

arr = [1,9,9,9];
console.log(plusOne(arr));

<|endoftext|>


<commit_before>function iiAESEncrypt(text, key) {
  return CryptoJS.AES.encrypt(text, key).toString();
}

function iiAESDecrypt(text, key) {
  return CryptoJS.AES.decrypt(text, key).toString(CryptoJS.enc.Utf8);
}<commit_msg>Catch javascript errors<commit_after>function iiAESEncrypt(text, key) {
  try {
    return CryptoJS.AES.encrypt(text, key).toString();
  }
  catch(err) {
    return '';
  }
}

function iiAESDecrypt(text, key) {
  try {
    return CryptoJS.AES.decrypt(text, key).toString(CryptoJS.enc.Utf8);
  }
  catch(err) {
    return '';
  }
}<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

// @see http://mxr.mozilla.org/mozilla-central/source/js/src/xpconnect/loader/mozJSComponentLoader.cpp

'use strict';

// IMPORTANT: Avoid adding any initialization tasks here, if you need to do
// something before add-on is loaded consider addon/runner module instead!

const { classes: Cc, Constructor: CC, interfaces: Ci, utils: Cu,
        results: Cr, manager: Cm } = Components;
const ioService = Cc['@mozilla.org/network/io-service;1'].
                  getService(Ci.nsIIOService);
const resourceHandler = ioService.getProtocolHandler('resource').
                        QueryInterface(Ci.nsIResProtocolHandler);
const systemPrincipal = CC('@mozilla.org/systemprincipal;1', 'nsIPrincipal')();
const scriptLoader = Cc['@mozilla.org/moz/jssubscript-loader;1'].
                     getService(Ci.mozIJSSubScriptLoader);
const prefService = Cc['@mozilla.org/preferences-service;1'].
                    getService(Ci.nsIPrefService).
                    QueryInterface(Ci.nsIPrefBranch);
const appInfo = Cc["@mozilla.org/xre/app-info;1"].
                getService(Ci.nsIXULAppInfo);
const vc = Cc["@mozilla.org/xpcom/version-comparator;1"].
           getService(Ci.nsIVersionComparator);

const REASON = [ 'unknown', 'startup', 'shutdown', 'enable', 'disable',
                 'install', 'uninstall', 'upgrade', 'downgrade' ];

const bind = Function.call.bind(Function.bind);

let loader = null;
let unload = null;
let loaderSandbox = null;
let nukeTimer = null;

// Utility function that synchronously reads local resource from the given
// `uri` and returns content string.
function readURI(uri) {
  let ioservice = Cc['@mozilla.org/network/io-service;1'].
    getService(Ci.nsIIOService);
  let channel = ioservice.newChannel(uri, 'UTF-8', null);
  let stream = channel.open();

  let cstream = Cc['@mozilla.org/intl/converter-input-stream;1'].
    createInstance(Ci.nsIConverterInputStream);
  cstream.init(stream, 'UTF-8', 0, 0);

  let str = {};
  let data = '';
  let read = 0;
  do {
    read = cstream.readString(0xffffffff, str);
    data += str.value;
  } while (read != 0);

  cstream.close();

  return data;
}

// We don't do anything on install & uninstall yet, but in a future
// we should allow add-ons to cleanup after uninstall.
function install(data, reason) {}
function uninstall(data, reason) {}

function startup(data, reasonCode) {
  try {
    let reason = REASON[reasonCode];
    // URI for the root of the XPI file.
    // 'jar:' URI if the addon is packed, 'file:' URI otherwise.
    // (Used by l10n module in order to fetch `locale` folder)
    let rootURI = data.resourceURI.spec;

    // TODO: Maybe we should perform read harness-options.json asynchronously,
    // since we can't do anything until 'sessionstore-windows-restored' anyway.
    let manifest, options;
    let isNative = false;
    try {
      options = JSON.parse(readURI(rootURI + './harness-options.json'));
      manifest = options.manifest;
    } catch (e) {
      manifest = JSON.parse(readURI(rootURI + './package.json'));
      try {
        options = JSON.parse(readURI(rootURI + './config.json'));
      } catch (e) {
        options = {};
      }
      isNative = true;
    }

    let id = isNative ?
      (manifest.id || (~manifest.name.indexOf('@') ?
        manifest.name :
        manifest.name + '@jetpack')) :
      options.jetpackID;
    let name = isNative ? manifest.name : options.name;

    if (!isNative) {
      // Clean the metadata
      options.metadata[name]['permissions'] = options.metadata[name]['permissions'] || {};

      // freeze the permissionss
      Object.freeze(options.metadata[name]['permissions']);
      // freeze the metadata
      Object.freeze(options.metadata[name]);
    }

    // Register a new resource 'domain' for this addon which is mapping to
    // XPI's `resources` folder.
    // Generate the domain name by using jetpack ID, which is the extension ID
    // by stripping common characters that doesn't work as a domain name:
    let uuidRe =
      /^\{([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\}$/;

    let domain = id.
      toLowerCase().
      replace(/@/g, '-at-').
      replace(/\./g, '-dot-').
      replace(uuidRe, '$1');

    let prefixURI = 'resource://' + domain + '/';
    let resourcesURIPath = isNative ? rootURI + '/' : rootURI + '/resources/';
    let resourcesURI = ioService.newURI(resourcesURIPath, null, null);
    resourceHandler.setSubstitution(domain, resourcesURI);

    // Create path to URLs mapping supported by loader.
    let addonPath = isNative ? prefixURI : prefixURI + name + '/lib/';
    let testPath = isNative ? prefixURI : prefixURI + name + '/tests/';
    let paths = {
      // Relative modules resolve to add-on package lib
      './': addonPath,
      './tests/': testPath,
      '': 'resource://gre/modules/commonjs/'
    };

    // Maps addon lib and tests ressource folders for each package
    if (!isNative) {
      paths = Object.keys(options.metadata).reduce(function(result, name) {
        result[name + '/'] = prefixURI + name + '/lib/'
        result[name + '/tests/'] = prefixURI + name + '/tests/'
        return result;
      }, paths);
    }

    // We need to map tests folder when we run sdk tests whose package name
    // is stripped
    if (name == 'addon-sdk')
      paths['tests/'] = prefixURI + name + '/tests/';

    let useBundledSDK = options['force-use-bundled-sdk'];
    if (!useBundledSDK) {
      try {
        useBundledSDK = prefService.getBoolPref("extensions.addon-sdk.useBundledSDK");
      }
      catch (e) {
        // Pref doesn't exist, allow using Firefox shipped SDK
      }
    }

    // Starting with Firefox 21.0a1, we start using modules shipped into firefox
    // Still allow using modules from the xpi if the manifest tell us to do so.
    // And only try to look for sdk modules in xpi if the xpi actually ship them
    if (options['is-sdk-bundled'] &&
        (vc.compare(appInfo.version, '21.0a1') < 0 || useBundledSDK)) {
      // Maps sdk module folders to their resource folder
      paths[''] = prefixURI + 'addon-sdk/lib/';
      // test.js is usually found in root commonjs or SDK_ROOT/lib/ folder,
      // so that it isn't shipped in the xpi. Keep a copy of it in sdk/ folder
      // until we no longer support SDK modules in XPI:
      paths['test'] = prefixURI + 'addon-sdk/lib/sdk/test.js';
    }

    // Retrieve list of module folder overloads based on preferences in order to
    // eventually used a local modules instead of files shipped into Firefox.
    let branch = prefService.getBranch('extensions.modules.' + id + '.path');
    paths = branch.getChildList('', {}).reduce(function (result, name) {
      // Allows overloading of any sub folder by replacing . by / in pref name
      let path = name.substr(1).split('.').join('/');
      // Only accept overloading folder by ensuring always ending with `/`
      if (path) path += '/';
      let fileURI = branch.getCharPref(name);

      // On mobile, file URI has to end with a `/` otherwise, setSubstitution
      // takes the parent folder instead.
      if (fileURI[fileURI.length-1] !== '/')
        fileURI += '/';

      // Maps the given file:// URI to a resource:// in order to avoid various
      // failure that happens with file:// URI and be close to production env
      let resourcesURI = ioService.newURI(fileURI, null, null);
      let resName = 'extensions.modules.' + domain + '.commonjs.path' + name;
      resourceHandler.setSubstitution(resName, resourcesURI);

      result[path] = 'resource://' + resName + '/';
      return result;
    }, paths);

    let loaderURI;

    if (isNative) {
      let toolkitLoaderPath = 'toolkit/loader.js';
      let toolkitLoaderURI = 'resource://gre/modules/commonjs/' + toolkitLoaderPath;
      if (paths['sdk/']) { // sdk folder has been overloaded
                           // (from pref, or cuddlefish is still in the xpi)
        loaderURI = paths['sdk/'] + '../' + toolkitLoaderPath;
      }
      else if (paths['']) { // root modules folder has been overloaded
        loaderURI = paths[''] + toolkitLoaderPath;
      } else {
        loaderURI = toolkitLoaderURI;
      }
    } else {
      // Import `cuddlefish.js` module using a Sandbox and bootstrap loader.
      let cuddlefishPath = 'loader/cuddlefish.js';
      let cuddlefishURI = 'resource://gre/modules/commonjs/sdk/' + cuddlefishPath;
      if (paths['sdk/']) { // sdk folder has been overloaded
                           // (from pref, or cuddlefish is still in the xpi)
        loaderURI = paths['sdk/'] + cuddlefishPath;
      }
      else if (paths['']) { // root modules folder has been overloaded
        loaderURI = paths[''] + 'sdk/' + cuddlefishPath;
      } else {
        loaderURI = cuddlefishURI;
      }
    }

    loaderSandbox = loadSandbox(loaderURI);
    let loaderModule = loaderSandbox.exports;

    unload = loaderModule.unload;
    let loaderOptions = {
      // Flag to determine whether or not to use native-style loader or not
      // If false, will be using Cuddlefish Loader, and otherwise will be
      // using toolkit/loader with `isNative` flag true
      isNative: isNative,

      paths: paths,
      // modules manifest.
      manifest: manifest,

      // Add-on ID used by different APIs as a unique identifier.
      id: id,
      // Add-on name.
      name: name,
      // Add-on version.
      // Use `version` if available (native loader), or fall back to
      // metadata[name].version
      version: isNative ? options.version : options.metadata[name].version,
      // Add-on package descriptor.
      // Use `options` if native-loader, or metadata otherwise
      metadata: isNative ? options : options.metadata[name],
      // Add-on load reason.
      loadReason: reason,

      prefixURI: prefixURI,
      // Add-on URI.
      rootURI: isNative ? addonPath : rootURI,
      // options used by system module.
      // File to write 'OK' or 'FAIL' (exit code emulation).
      resultFile: options.resultFile,
      // Arguments passed as --static-args
      staticArgs: options.staticArgs,

      // Arguments related to test runner.
      modules: {
        '@test/options': {
          allTestModules: options.allTestModules,
          iterations: options.iterations,
          filter: options.filter,
          profileMemory: options.profileMemory,
          stopOnError: options.stopOnError,
          verbose: options.verbose,
          parseable: options.parseable,
          checkMemory: options.check_memory,
          paths: paths
        }
      }
    };

    // Manually set the loader's module cache to include itself;
    // this is due to several modules requiring 'toolkit/loader',
    // which fails due to lack of `Components`
    if (isNative)
      loaderOptions.modules['toolkit/loader'] = loaderSandbox.exports;

    let loader = loaderModule.Loader(loaderOptions);
    let { console } = Cu.import('resource://gre/modules/devtools/Console.jsm', {});
    ['rootURI', 'mapping', 'manifest', 'main'].forEach((key) => {
      console.log(key, loader[key]);
    });

    let module = loaderModule.Module(isNative ? 'toolkit/loader' : 'sdk/loader/cuddlefish', loaderURI);
    let require = loaderModule.Require(loader, module);

    // Normalize `options.mainPath` so that it looks like one that will come
    // in a new version of linker.
    //
    // For native loader, the sdk/addon/runner will call loaderModule.main
    // on loader, which will resolve the main file based off of manifest
    let main = options.mainPath;

    // Only specify prefsURI if a native-flagged addon specified it
    // in the manifest, other wise, use the default path which
    // was created by CFX
    let prefsURI = isNative ?
      (manifest.prefs ? rootURI + manifest.prefs : undefined) :
      rootURI + '/defaults/preferences/prefs.js';

    require('sdk/addon/runner').startup(reason, {
      loader: loader,
      main: main,
      prefsURI: prefsURI
    });
  } catch (error) {
    dump('Bootstrap error: ' +
         (error.message ? error.message : String(error)) + '\n' +
         (error.stack || error.fileName + ': ' + error.lineNumber) + '\n');
    throw error;
  }
};

function loadSandbox(uri) {
  let proto = {
    sandboxPrototype: {
      loadSandbox: loadSandbox,
      ChromeWorker: ChromeWorker
    }
  };
  let sandbox = Cu.Sandbox(systemPrincipal, proto);
  // Create a fake commonjs environnement just to enable loading loader.js
  // correctly
  sandbox.exports = {};
  sandbox.module = { uri: uri, exports: sandbox.exports };
  sandbox.require = function (id) {
    if (id !== "chrome")
      throw new Error("Bootstrap sandbox `require` method isn't implemented.");

    return Object.freeze({ Cc: Cc, Ci: Ci, Cu: Cu, Cr: Cr, Cm: Cm,
      CC: bind(CC, Components), components: Components,
      ChromeWorker: ChromeWorker });
  };
  scriptLoader.loadSubScript(uri, sandbox, 'UTF-8');
  return sandbox;
}

function unloadSandbox(sandbox) {
  if ("nukeSandbox" in Cu)
    Cu.nukeSandbox(sandbox);
}

function setTimeout(callback, delay) {
  let timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
  timer.initWithCallback({ notify: callback }, delay,
                         Ci.nsITimer.TYPE_ONE_SHOT);
  return timer;
}

function shutdown(data, reasonCode) {
  let reason = REASON[reasonCode];
  if (loader) {
    unload(loader, reason);
    unload = null;

    // Don't waste time cleaning up if the application is shutting down
    if (reason != "shutdown") {
      // Avoid leaking all modules when something goes wrong with one particular
      // module. Do not clean it up immediatly in order to allow executing some
      // actions on addon disabling.
      // We need to keep a reference to the timer, otherwise it is collected
      // and won't ever fire.
      nukeTimer = setTimeout(nukeModules, 1000);
    }
  }
};

function nukeModules() {
  nukeTimer = null;
  // module objects store `exports` which comes from sandboxes
  // We should avoid keeping link to these object to avoid leaking sandboxes
  for (let key in loader.modules) {
    delete loader.modules[key];
  }
  // Direct links to sandboxes should be removed too
  for (let key in loader.sandboxes) {
    let sandbox = loader.sandboxes[key];
    delete loader.sandboxes[key];
    // Bug 775067: From FF17 we can kill all CCW from a given sandbox
    unloadSandbox(sandbox);
  }
  loader = null;

  // both `toolkit/loader` and `system/xul-app` are loaded as JSM's via
  // `cuddlefish.js`, and needs to be unloaded to avoid memory leaks, when
  // the addon is unload.

  unloadSandbox(loaderSandbox.loaderSandbox);
  unloadSandbox(loaderSandbox.xulappSandbox);

  // Bug 764840: We need to unload cuddlefish otherwise it will stay alive
  // and keep a reference to this compartment.
  unloadSandbox(loaderSandbox);
  loaderSandbox = null;
}
<commit_msg>Update bootstrap.<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

// @see http://mxr.mozilla.org/mozilla-central/source/js/src/xpconnect/loader/mozJSComponentLoader.cpp

'use strict';

// IMPORTANT: Avoid adding any initialization tasks here, if you need to do
// something before add-on is loaded consider addon/runner module instead!

const { classes: Cc, Constructor: CC, interfaces: Ci, utils: Cu,
        results: Cr, manager: Cm } = Components;
const ioService = Cc['@mozilla.org/network/io-service;1'].
                  getService(Ci.nsIIOService);
const resourceHandler = ioService.getProtocolHandler('resource').
                        QueryInterface(Ci.nsIResProtocolHandler);
const systemPrincipal = CC('@mozilla.org/systemprincipal;1', 'nsIPrincipal')();
const scriptLoader = Cc['@mozilla.org/moz/jssubscript-loader;1'].
                     getService(Ci.mozIJSSubScriptLoader);
const prefService = Cc['@mozilla.org/preferences-service;1'].
                    getService(Ci.nsIPrefService).
                    QueryInterface(Ci.nsIPrefBranch);
const appInfo = Cc["@mozilla.org/xre/app-info;1"].
                getService(Ci.nsIXULAppInfo);
const vc = Cc["@mozilla.org/xpcom/version-comparator;1"].
           getService(Ci.nsIVersionComparator);
const { console } = Cu.import('resource://gre/modules/devtools/Console.jsm', {});
const { NetUtil } = Cu.import("resource://gre/modules/NetUtil.jsm", {});
const { Promise: { defer } } = Cu.import("resource://gre/modules/Promise.jsm", {});
const { Task: { spawn } } = Cu.import("resource://gre/modules/Task.jsm", {});

const REASON = [ 'unknown', 'startup', 'shutdown', 'enable', 'disable',
                 'install', 'uninstall', 'upgrade', 'downgrade' ];

const bind = Function.call.bind(Function.bind);

let loader = null;
let unload = null;
let loaderSandbox = null;
let nukeTimer = null;

const readPref = type => path => {
  try {
    return prefService["get" + type + "Pref"](path);
  }
  catch (_) {
    return null;
  }
}

const readBoolPref = readPref("Bool");

// Utility function reads URI async. Returns promise for the read
// content.
const readURI = (uri, charset="utf-8") => {
  const channel = NetUtil.newChannel(uri, charset, null);
  const { promise, resolve, reject } = defer();

  try {
    NetUtil.asyncFetch(channel, (stream, result) => {
      if (Components.isSuccessCode(result)) {
        const count = stream.available();
        const data = NetUtil.readInputStreamToString(stream, count, {charset : charset});

        resolve(data);
      } else {
        reject(Error("Failed to read: '" + uri + "' (Error Code: " + result + ")"));
      }
    });
  }
  catch ({message}) {
    reject(Error("Failed to read: '" + uri + "' (Error: " + message + ")"));
  }

  return promise;
}

// We don't do anything on install & uninstall yet, but in a future
// we should allow add-ons to cleanup after uninstall.
const install = (data, reason) => {}
const uninstall = (data, reason) => {}

// Reads run configuration asynchronously, returns promise
// for the config JSON.
const readConfig = (rootURI) => {
  const { resolve, reject, promise } = defer();
  spawn(function () {
    let config = null;
    try {
      const options = JSON.parse(yield (readURI(rootURI + "./harness-options.json")));
      config = {
        options: options,
        metadata: options.metadata[options.name],
        isNative: false
      };
    }
    catch (_) {
      try {
        config = {
          isNative: true,
          options: {},
          metadata: JSON.parse(yield readURI(rootURI + './package.json'))
        };
      }
      catch(_) {}
    }
    resolve(config);
  });

  return promise;
}

const UUID_PATTERN = /^\{([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\}$/;
// Takes add-on ID and normalizes it to a domain name so that add-on
// can be mapped to resource://domain/
const readDomain = id =>
  // If only `@` character is the first one, than just substract it,
  // otherwise fallback to legacy normalization code path. Note: `.`
  // is valid character for resource substitutaiton & we intend to
  // make add-on URIs intuitive, so it's best to just stick to an
  // add-on author typed input.
  id.lastIndexOf("@") === 0 ? id.substr(1).toLowerCase() :
  id.toLowerCase().
     replace(/@/g, "-at-").
     replace(/\./g, "-dot-").
     replace(UUID_PATTERN, "$1");

const readPaths = (options, id, name, domain, baseURI, isNative=false) => {
  let paths = {
    "": "resource://gre/modules/commonjs/",
    "./": isNative ? baseURI : baseURI + name + '/lib/',
    "./tests/": isNative ? baseURI : baseURI + name + '/tests/'
  };

  Object.keys(options.manifest || {}).reduce((paths, prefix) => {
    paths[prefix + "/"] = baseURI + prefix + "/lib/";
    paths[prefix + "tests/"] = baseURI + prefix + "/tests/";
    return paths;
  }, paths);

  if (name == "addon-sdk")
    paths["tests/"] = baseURI + "addon-sdk/tests/";

  // If SDK is bundled and it is required to use bundled version
  // of the SDK setup paths to do so.
  const isSDKBundled = options["is-sdk-bundled"];
  const useBundledSDK = options["force-use-bundled-sdk"] ||
                        readBoolPref("extensions.addon-sdk.useBundledSDK");

  if (isSDKBundled && useBundledSDK) {
    paths[""] = baseURI + "addon-sdk/lib/";
    paths["test"] = baseURI + "addon-sdk/lib/sdk/test.js";
  }

  const branch = prefService.getBranch("extensions.modules." + id + ".path");
  branch.getChildList("", {}).reduce((paths, name) => {
    const path = name.substr(1).split(".").join("/");
    const prefix = path.length ? path + "/" : path;
    const value = branch.getCharPref(name);
    const fileURI = value[value.length - 1] === "/" ? value :
                    value + "/";
    const key = "extensions.modules." + domain + ".commonjs.path" + name;
    const uri = ioService.newURI(fileURI, null, null);
    resourceHandler.setSubstitution(key, uri);

    paths[prefix] = "resource://" + key + "/";
    return paths;
  }, paths);

  return paths;
}

// Takes JSON `options` and sets prefs for each key under
// the given `root`. Given `options` may contain nested
// objects.
const setPrefs = (root, options) =>
  void Object.keys(options).forEach(id => {
    const key = root + "." + id;
    const value = options[id]
    const type = typeof(value);

    value === null ? void(0) :
    value === undefined ? void(0) :
    type === "boolean" ? prefService.setBoolPref(key, value) :
    type === "string" ? prefService.setCharPref(key, value) :
    type === "number" ? prefService.setIntPref(key, value) :
    type === "object" ? setPrefs(key, value) :
    void(0);
  });

const startup = (addon, reasonCode) => {
  const { id, version, resourceURI: { spec: rootURI } } = addon;
  spawn(function() {
    try {
      const config = readConfig(rootURI);

      const { metadata, options, isNative } = (yield config);
      const permissions = Object.freeze(metadata.permissions || {});
      const domain = readDomain(id);
      const name = metadata.name;

      console.log("ROOT:", rootURI);

      console.log("DOMAIN:", domain);

      const baseURI = "resource://" + domain + "/";

      console.log("BASE", baseURI);

      const prefsURI = baseURI + "defaults/preferences/prefs.js";

      console.log("PREFS", prefsURI);

      const mappedURI = isNative ? rootURI + '/' : rootURI + '/resources/';
      resourceHandler.setSubstitution(domain, ioService.newURI(mappedURI, null, null));

      console.log("MAPPED", mappedURI);

      // TODO: Remove this hack
      setPrefs("extensions.modules." + id + ".path", {
        "": "file:///Users/gozala/Projects/addon-sdk/lib/"
      });

      const paths = readPaths(options, id, name, domain, baseURI, isNative);
      console.log("PATHS", paths);

      const loaderID = isNative ? "toolkit/loader" : "sdk/loader/cuddlefish";
      const loaderURI = paths[""] + loaderID + ".js";

      console.log("LOADER", loaderURI);

      loaderSandbox = loadSandbox(loaderURI);
      const loaderModule = loaderSandbox.exports;
      unload = loaderModule.unload;

      setPrefs("extensions." + id + ".sdk", {
        id: id,
        version: version,
        domain: domain,
        mainPath: options.mainPath,
        baseURI: baseURI,
        rootURI: rootURI,
        load: {
          reason: reasonCode
        },
        input: {
          staticArgs: JSON.stringify(options.staticArgs)
        },
        output: {
          resultFile: options.resultFile,
          style: options.parseable ? "tbpl" : null,
          logLevel: options.verbose ? "verbose" : null,
        },
        test: {
          stop: options.stopOnError ? 1 : null,
          filter: options.filter,
          iterations: parseInt(options.iterations),
        },
        profile: {
          memory: options.profileMemory,
          leaks: options.check_memory ? "refcount" : null
        }
      });

      const modules = {};

      // Manually set the loader's module cache to include itself;
      // which otherwise fails due to lack of `Components`.
      modules[loaderID] = loaderModule;
      modules["@test/options"] = Object.freeze({
        allTestModules: options.allTestModules
      });

      loader = loaderModule.Loader({
        id: id,
        isNative: isNative,
        rootURI: baseURI,
        paths: paths,
        manifest: options.manifest || metadata,
        metadata: metadata,
        modules: modules
      });

      console.log("LOADER", loader);

      const module = loaderModule.Module(loaderID, loaderURI);
      const require = loaderModule.Require(loader, module);

      console.log("REQUIRE", require);

      require("sdk/addon/runner").startup(reasonCode, {
        loader: loader,
        prefsURI: prefsURI,
        main: options.mainPath
      });
    }
    catch (error) {
      console.error("Failed to bootstrap addon: ", id, error);
      throw error;
    }
  });
};

const loadSandbox = (uri) => {
  let proto = {
    sandboxPrototype: {
      loadSandbox: loadSandbox,
      ChromeWorker: ChromeWorker
    }
  };
  let sandbox = Cu.Sandbox(systemPrincipal, proto);
  // Create a fake commonjs environnement just to enable loading loader.js
  // correctly
  sandbox.exports = {};
  sandbox.module = { uri: uri, exports: sandbox.exports };
  sandbox.require = function (id) {
    if (id !== "chrome")
      throw new Error("Bootstrap sandbox `require` method isn't implemented.");

    return Object.freeze({ Cc: Cc, Ci: Ci, Cu: Cu, Cr: Cr, Cm: Cm,
      CC: bind(CC, Components), components: Components,
      ChromeWorker: ChromeWorker });
  };
  scriptLoader.loadSubScript(uri, sandbox, 'UTF-8');
  return sandbox;
}

const unloadSandbox = sandbox =>
  Cu.nukeSandbox && sandbox && Cu.nukeSandbox(sandbox);

const setTimeout = (callback, delay=0) => {
  const timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
  timer.initWithCallback({ notify: callback },
                         delay,
                         Ci.nsITimer.TYPE_ONE_SHOT);
  return timer;
}

const shutdown = (data, reasonCode) => {
  let reason = REASON[reasonCode];
  if (loader) {
    unload(loader, reason);
    unload = null;

    // Don't waste time cleaning up if the application is shutting down
    if (reason != "shutdown") {
      // Avoid leaking all modules when something goes wrong with one particular
      // module. Do not clean it up immediatly in order to allow executing some
      // actions on addon disabling.
      // We need to keep a reference to the timer, otherwise it is collected
      // and won't ever fire.
      nukeTimer = setTimeout(nukeModules, 1000);
    }
  }
};

function nukeModules() {
  nukeTimer = null;
  // module objects store `exports` which comes from sandboxes
  // We should avoid keeping link to these object to avoid leaking sandboxes
  for (let id in loader.modules) {
    delete loader.modules[id];
  }

  // Direct links to sandboxes should be removed too
  for (let id in loader.sandboxes) {
    let sandbox = loader.sandboxes[id];
    delete loader.sandboxes[id];
    // Bug 775067: From FF17 we can kill all CCW from a given sandbox
    unloadSandbox(sandbox);
  }
  loader = null;

  // both `toolkit/loader` and `system/xul-app` are loaded as JSM's via
  // `cuddlefish.js`, and needs to be unloaded to avoid memory leaks, when
  // the addon is unload.

  unloadSandbox(loaderSandbox.loaderSandbox);
  unloadSandbox(loaderSandbox.xulappSandbox);

  // Bug 764840: We need to unload cuddlefish otherwise it will stay alive
  // and keep a reference to this compartment.
  unloadSandbox(loaderSandbox);
  loaderSandbox = null;
}
<|endoftext|>


<commit_before>import MockRequest from './mocks/mock-request'
import MockResource from './mocks/mock-resource'
import MockGateway from './gateway/mock'
import { configs } from './mappersmith'
import { toQueryString } from './utils'

let store = []
let ids = 1
let originalGateway = null

/**
 * High level abstraction, it works directly on your client mocking
 * the resources and their methods.
 * @param {Object} client - the client generated by {@link forge}
 *
 * @return {MockAssert}
 */
export const mockClient = (client) => {
  const entry = new MockResource(ids++, client)
  store.push(entry)
  return entry
}

/**
 * Low level abstraction, very useful for automations
 * @param {Object} props
 *   @param {String} props.method - request method (get, post, etc)
 *   @param {String} props.url - request url (http://example.com)
 *   @param {String} props.body - request body
 *   @param {String} props.response
 *     @param {String} props.response.status
 *     @param {String} props.response.headers
 *     @param {String} props.response.body
 *
 * @return {MockAssert}
 */
export const mockRequest = (props) => {
  const entry = new MockRequest(ids++, props)
  store.push(entry)
  return entry.assertObject()
}

/**
 * Setup the test library
 */
export const install = () => {
  originalGateway = configs.gateway
  configs.gateway = MockGateway
}

/**
 * Teardown the test library
 */
export const uninstall = () => {
  clear()
  if (originalGateway) {
    configs.gateway = originalGateway
    originalGateway = null
  }
}

/**
 * Cleans up all mocks
 */
export const clear = () => {
  store = []
}

/**
 * @param {Request} request
 * @return {Response}
 * @throws Will throw an error if it doesn't find a mock to match the given request
 */
export const lookupResponse = (request) => {
  const mocks = store.map((mock) => mock.toMockRequest())

  const exactMatch = mocks
    .filter((mock) => mock.isExactMatch(request))
    .pop()

  if (exactMatch) {
    return exactMatch.call(request)
  }

  const partialMatch = mocks
    .filter((mock) => mock.isPartialMatch(request))
    .pop()

  if (partialMatch) {
    throw new Error(
      `[Mappersmith Test] No exact match found for ${requestToLog(request)}, partial match with ${mockToLog(partialMatch)}, check your mock definition`
    )
  }

  throw new Error(
    `[Mappersmith Test] No match found for ${requestToLog(request)}, check your mock definition`
  )
}

/**
 * List of match functions
 */
export const m = {
  stringMatching: (regexp) => {
    if (!(regexp instanceof RegExp)) {
      throw new Error(`[Mappersmith Test] "stringMatching" received an invalid regexp (${regexp})`)
    }
    return (string) => regexp.test(string)
  },

  stringContaining: (sample) => {
    if (typeof sample !== 'string') {
      throw new Error(`[Mappersmith Test] "stringContaining" received an invalid string (${sample})`)
    }

    return (string) => stringIncludes(string, sample)
  },

  uuid4: () => {
    // NOTE: based on https://github.com/chriso/validator.js/blob/3443132beccddf06c3f0a5e88c1dd2ee6513b612/src/lib/isUUID.js
    const uuid4Rx = /^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i

    return string => uuid4Rx.test(string)
  },

  anything: () => () => true
}

const requestToLog = (request) => (
  `"${request.method().toUpperCase()} ${request.url()}" (body: "${toQueryString(request.body())}")`
)
const mockToLog = (requestMock) => (
  `"${requestMock.method.toUpperCase()} ${requestMock.url}" (body: "${requestMock.body}")`
)

const stringIncludes = (str, search, start) => {
  if (typeof start !== 'number') {
    start = 0
  }

  if (typeof str.includes === 'function') {
    return str.includes(search, start)
  }

  if (start + search.length > str.length) {
    return false
  }

  return str.indexOf(search, start) !== -1
}
<commit_msg>Require index.js instead of mappersmith.js in test.js<commit_after>import MockRequest from './mocks/mock-request'
import MockResource from './mocks/mock-resource'
import MockGateway from './gateway/mock'
import { configs } from './index'
import { toQueryString } from './utils'

let store = []
let ids = 1
let originalGateway = null

/**
 * High level abstraction, it works directly on your client mocking
 * the resources and their methods.
 * @param {Object} client - the client generated by {@link forge}
 *
 * @return {MockAssert}
 */
export const mockClient = (client) => {
  const entry = new MockResource(ids++, client)
  store.push(entry)
  return entry
}

/**
 * Low level abstraction, very useful for automations
 * @param {Object} props
 *   @param {String} props.method - request method (get, post, etc)
 *   @param {String} props.url - request url (http://example.com)
 *   @param {String} props.body - request body
 *   @param {String} props.response
 *     @param {String} props.response.status
 *     @param {String} props.response.headers
 *     @param {String} props.response.body
 *
 * @return {MockAssert}
 */
export const mockRequest = (props) => {
  const entry = new MockRequest(ids++, props)
  store.push(entry)
  return entry.assertObject()
}

/**
 * Setup the test library
 */
export const install = () => {
  originalGateway = configs.gateway
  configs.gateway = MockGateway
}

/**
 * Teardown the test library
 */
export const uninstall = () => {
  clear()
  if (originalGateway) {
    configs.gateway = originalGateway
    originalGateway = null
  }
}

/**
 * Cleans up all mocks
 */
export const clear = () => {
  store = []
}

/**
 * @param {Request} request
 * @return {Response}
 * @throws Will throw an error if it doesn't find a mock to match the given request
 */
export const lookupResponse = (request) => {
  const mocks = store.map((mock) => mock.toMockRequest())

  const exactMatch = mocks
    .filter((mock) => mock.isExactMatch(request))
    .pop()

  if (exactMatch) {
    return exactMatch.call(request)
  }

  const partialMatch = mocks
    .filter((mock) => mock.isPartialMatch(request))
    .pop()

  if (partialMatch) {
    throw new Error(
      `[Mappersmith Test] No exact match found for ${requestToLog(request)}, partial match with ${mockToLog(partialMatch)}, check your mock definition`
    )
  }

  throw new Error(
    `[Mappersmith Test] No match found for ${requestToLog(request)}, check your mock definition`
  )
}

/**
 * List of match functions
 */
export const m = {
  stringMatching: (regexp) => {
    if (!(regexp instanceof RegExp)) {
      throw new Error(`[Mappersmith Test] "stringMatching" received an invalid regexp (${regexp})`)
    }
    return (string) => regexp.test(string)
  },

  stringContaining: (sample) => {
    if (typeof sample !== 'string') {
      throw new Error(`[Mappersmith Test] "stringContaining" received an invalid string (${sample})`)
    }

    return (string) => stringIncludes(string, sample)
  },

  uuid4: () => {
    // NOTE: based on https://github.com/chriso/validator.js/blob/3443132beccddf06c3f0a5e88c1dd2ee6513b612/src/lib/isUUID.js
    const uuid4Rx = /^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i

    return string => uuid4Rx.test(string)
  },

  anything: () => () => true
}

const requestToLog = (request) => (
  `"${request.method().toUpperCase()} ${request.url()}" (body: "${toQueryString(request.body())}")`
)
const mockToLog = (requestMock) => (
  `"${requestMock.method.toUpperCase()} ${requestMock.url}" (body: "${requestMock.body}")`
)

const stringIncludes = (str, search, start) => {
  if (typeof start !== 'number') {
    start = 0
  }

  if (typeof str.includes === 'function') {
    return str.includes(search, start)
  }

  if (start + search.length > str.length) {
    return false
  }

  return str.indexOf(search, start) !== -1
}
<|endoftext|>


<commit_before>const Discord = require('discord.js');
const Subiex = require('../bot.js');
const oneLinerJoke = require('one-liner-joke');

Subiex.registerCommand('joke', 'default', (message) => {

  var joke = oneLinerJoke.getRandomJoke();
  message.channel.send({embed: {
  color: yellow,
  description: joke.body
}});

}, ['emoji', 'funny', 'hilarious'], 'Get a random joke!', '[]')
<commit_msg>:zap: Changes for testing<commit_after>const Discord = require('discord.js');
const Subiex = require('../bot.js');
const oneLinerJoke = require('one-liner-joke');

Subiex.registerCommand('joke', 'default', (message) => {

  var joke = oneLinerJoke.getRandomJoke();
  message.channel.send({embed: {
  color: AE00FF,
  description: joke.body
}});

}, ['emoji', 'funny', 'hilarious'], 'Get a random joke!', '[]')
<|endoftext|>


<commit_before>var iam = require('./../lib/iam');

var sampleIam = {
    "Statement": [
        {
            "Effect": "Allow",
            "Action": ["sm:*"],
            "Resource": [
                "ssrn:ss:sm::200:integration/9999"
            ]
        },
        {
            "Effect": "Deny",
            "Action": ["sm:SearchResults"],
            "Resource": [
                "ssrn:ss:sm::200:assessment/99"
            ]
        }
    ]
};

console.log(JSON.stringify(iam.getActionCriteria('sm:ViewUsers', iam.processIamData(sampleIam))));

/*
* S3
*
*
*
*
*
* EC2
*
*
* IAM
*
*
*   SmarterServices
*
*
*
*
* */

<commit_msg>Updated sample.<commit_after>var iam = require('./../lib/iam');

var sampleIam = {
    "Statement": [
        {
            "Effect": "Allow",
            "Action": ["sm:*"],
            "Resource": [
                "ssrn:ss:sm::200:integration/9999",
                "ssrn:ss:sm::100:assessment/500"
            ]
        },
        {
            "Effect": "Deny",
            "Action": ["sm:SearchResults"],
            "Resource": [
                "ssrn:ss:sm::200:assessment/99"
            ]
        }
    ]
};

console.log(JSON.stringify(iam.getActionCriteria('sm:SearchResults', iam.processIamData(sampleIam))));

/*
* S3
*
*
*
*
*
* EC2
*
*
* IAM
*
*
*   SmarterServices
*
*
*
*
* */

<|endoftext|>


<commit_before>class Test {
  constructor(arg = {abc: "abc"}) {
    this.abc = options.abc;
  }
}
<commit_msg>Removing test file<commit_after><|endoftext|>


<commit_before>var Command = require('ronin').Command
var fs = require('fs')
var path = require('path')
var webshot = require('webshot')
var ipfsAPI = require('ipfs-api')
var open = require('open')

module.exports = Command.extend({
  desc: 'View or generate screenshots for your application',

  options: {
    gen: 'boolean'
  },

  run: function (gen, name) {
    try {
      var configPath = path.resolve(process.cwd() + '/ipscend.json')
      fs.statSync(configPath)
      snapshot()
    } catch (err) {
      // console.log(err)
      console.log('Project must be initiated first, run `ipscend init`')
    }

    function snapshot () {
      var config = JSON.parse(fs.readFileSync(configPath))
      if (config.versions.length === 0) {
        return console.log('You need to publish at least once with <ipscend publish>')
      }

      var ipfs = ipfsAPI('localhost', '5001')

      if (!gen) {
        ipfs.add(new Buffer(JSON.stringify(config.versions)), function (err, res) {
          if (err || !res) {
            return console.error('err', err)
          }
          var previewAppHash = 'QmWSdGhfB6CbgvKzksaUSumjKyc5QWtoTiZciWSoNBNJcw'
          var versionsHash = res[0].Hash
          var base = 'http://localhost:8080/ipfs/'
          open(base + previewAppHash + '/#' + versionsHash)
        })
        return
      }

      if (gen) {
        var len = config.versions.length
        config.versions.forEach(function (version) {
          if (!version.snapshot) {
            webshot('http://localhost:8080/ipfs/' + version.hash,
                '/tmp/' + version.hash + '.png', {
                  shotSize: {
                    width: 'all',
                    height: 'all'
                  }
                }, function (err) {
              if (err) {
                return console.log(err)
              }

              ipfs.add('/tmp/' + version.hash + '.png', function (err, res) {
                if (err || !res) {
                  return console.error('err', err)
                }
                version.snapshot = res[0].Hash
                len--
                if (len === 0) {
                  var fd = fs.openSync(configPath, 'w')
                  fs.writeSync(fd, JSON.stringify(config, null, '  '), 0, 'utf-8')
                }
              })
            })
          } else {
            len--
          }
        })
      }
    }
  }
})
<commit_msg>add latest ipscend-preview-vizualizer hash<commit_after>var Command = require('ronin').Command
var fs = require('fs')
var path = require('path')
var webshot = require('webshot')
var ipfsAPI = require('ipfs-api')
var open = require('open')

module.exports = Command.extend({
  desc: 'View or generate screenshots for your application',

  options: {
    gen: 'boolean'
  },

  run: function (gen, name) {
    try {
      var configPath = path.resolve(process.cwd() + '/ipscend.json')
      fs.statSync(configPath)
      snapshot()
    } catch (err) {
      // console.log(err)
      console.log('Project must be initiated first, run `ipscend init`')
    }

    function snapshot () {
      var config = JSON.parse(fs.readFileSync(configPath))
      if (config.versions.length === 0) {
        return console.log('You need to publish at least once with <ipscend publish>')
      }

      var ipfs = ipfsAPI('localhost', '5001')

      if (!gen) {
        ipfs.add(new Buffer(JSON.stringify(config.versions)), function (err, res) {
          if (err || !res) {
            return console.error('err', err)
          }
          var previewAppHash = 'QmaJtFXp1ft4hLznscpRjEufZLTT8YuFn82vWFPeT2rprC'
          var versionsHash = res[0].Hash
          var base = 'http://localhost:8080/ipfs/'
          open(base + previewAppHash + '/#' + versionsHash)
        })
        return
      }

      if (gen) {
        var len = config.versions.length
        config.versions.forEach(function (version) {
          if (!version.snapshot) {
            webshot('http://localhost:8080/ipfs/' + version.hash,
                '/tmp/' + version.hash + '.png', {
                  shotSize: {
                    width: 'all',
                    height: 'all'
                  }
                }, function (err) {
              if (err) {
                return console.log(err)
              }

              ipfs.add('/tmp/' + version.hash + '.png', function (err, res) {
                if (err || !res) {
                  return console.error('err', err)
                }
                version.snapshot = res[0].Hash
                len--
                if (len === 0) {
                  var fd = fs.openSync(configPath, 'w')
                  fs.writeSync(fd, JSON.stringify(config, null, '  '), 0, 'utf-8')
                }
              })
            })
          } else {
            len--
          }
        })
      }
    }
  }
})
<|endoftext|>


<commit_before>"use strict";
var $ = function(id) { return document.getElementById(id); };

/*
 * processEntries
 * Process all the entries provided via standard input
 *
 */
var processEntries = function() {

    // Variables declaration. Parsing a string to a integer is necessary
    var score1 = parseInt($("score1").value);
    var score2 = parseInt($("score2").value);
    var score3 = parseInt($("score3").value);

    // Function call based on each input provided, creating an error message if necessary
    $("score1_error").textContent = checkConstraints( score1, 1 );
    $("score2_error").textContent = checkConstraints( score2, 2 );
    $("score3_error").textContent = checkConstraints( score3, 3 );

    if ( ($("score1_error").textContent.length === 0) && ($("score2_error").textContent.length === 0) && ($("score3_error").textContent.length === 0) ) {
        // This is the only acceptable condition of the errors's 'span' element
        // If the 'length' property is 0, then there is no error with the input
        // Hence, the results should be calculated
        var results = calculateFinalGrade( score1, score2, score3 );

        // Display the results
        $("scoreTotal").value = results[0];
        $("scoreFinal").value = results[1];
    }
    else {
        $("scoreTotal").value = "";
        $("scoreFinal").value = "";
    }

};

/*
 * checkConstraints
 * Create a error message based on the 'score' value
 *
 * @param score input provided by the user
 * @returns created error message. It will be empty if the input is correct
 *
 */
function checkConstraints( score, option ) {

    var errorMessage = "";

    if ( isNaN(score) ) {
        errorMessage = "Test-" + option + " must be a non-negative number!";
    }
    else if ( score < 0 ) {
        errorMessage = "Test-" + option + " must be non-negative!";
    }
    else if ( score > 100 ) {
        errorMessage = "Test-" + option + " must be in the closed interval [0, 100].";
    }

    return errorMessage;

}

/*
 * calculateFinalGrade
 * Calculates the total points and then generates final letter grade
 *
 * @param score1 first score provided by the user
 * @param score2 second score provided by the user
 * @param score3 third score provided by the user
 * @returns total points and final letter grade
 *
 */
function calculateFinalGrade( score1, score2, score3 ) {

    var results = [];
    results[0] = score1 + score2 + score3;

    if ( results[0] >= 270 ) {
        results[1] = 'A';
    }
    else if ( results[0] >= 240 ) {
        results[1] = 'B';
    }
    else if ( results[0] >= 210 ) {
        results[1] = 'C';
    }
    else if ( results[0] >= 180 ) {
        results[1] = 'D';
    }
    else {
        results[1] = 'F';
    }

    return results;

}

window.onload = function() {

    $("calculate").onclick = processEntries;
    $("score1").focus();

};<commit_msg>Commented the output erasing part of the code<commit_after>"use strict";
var $ = function(id) { return document.getElementById(id); };

/*
 * processEntries
 * Process all the entries provided via standard input
 *
 */
var processEntries = function() {

    // Variables declaration. Parsing a string to a integer is necessary
    var score1 = parseInt($("score1").value);
    var score2 = parseInt($("score2").value);
    var score3 = parseInt($("score3").value);

    // Function call based on each input provided, creating an error message if necessary
    $("score1_error").textContent = checkConstraints( score1, 1 );
    $("score2_error").textContent = checkConstraints( score2, 2 );
    $("score3_error").textContent = checkConstraints( score3, 3 );

    if ( ($("score1_error").textContent.length === 0) && ($("score2_error").textContent.length === 0) && ($("score3_error").textContent.length === 0) ) {
        // This is the only acceptable condition of the errors's 'span' element
        // If the 'length' property is 0, then there is no error with the input
        // Hence, the results should be calculated
        var results = calculateFinalGrade( score1, score2, score3 );

        // Display the results
        $("scoreTotal").value = results[0];
        $("scoreFinal").value = results[1];
    }
    else {
        // There is some error with the input. The output fields should be erased
        $("scoreTotal").value = "";
        $("scoreFinal").value = "";
    }

};

/*
 * checkConstraints
 * Create a error message based on the 'score' value
 *
 * @param score input provided by the user
 * @returns created error message. It will be empty if the input is correct
 *
 */
function checkConstraints( score, option ) {

    var errorMessage = "";

    if ( isNaN(score) ) {
        errorMessage = "Test-" + option + " must be a non-negative number!";
    }
    else if ( score < 0 ) {
        errorMessage = "Test-" + option + " must be non-negative!";
    }
    else if ( score > 100 ) {
        errorMessage = "Test-" + option + " must be in the closed interval [0, 100].";
    }

    return errorMessage;

}

/*
 * calculateFinalGrade
 * Calculates the total points and then generates final letter grade
 *
 * @param score1 first score provided by the user
 * @param score2 second score provided by the user
 * @param score3 third score provided by the user
 * @returns total points and final letter grade
 *
 */
function calculateFinalGrade( score1, score2, score3 ) {

    var results = [];
    results[0] = score1 + score2 + score3;

    if ( results[0] >= 270 ) {
        results[1] = 'A';
    }
    else if ( results[0] >= 240 ) {
        results[1] = 'B';
    }
    else if ( results[0] >= 210 ) {
        results[1] = 'C';
    }
    else if ( results[0] >= 180 ) {
        results[1] = 'D';
    }
    else {
        results[1] = 'F';
    }

    return results;

}

window.onload = function() {

    $("calculate").onclick = processEntries;
    $("score1").focus();

};<|endoftext|>


<commit_before>const path = require('path');
const { Builder, ui } = require(`denali-cli`);
const { exec } = require('child_process');
const { sync: resolveSync } = require('resolve');

module.exports = class DenaliBuilder extends Builder {

  processParent(tree, dir) {
    tree = this.transpileTree(tree, dir);
    return tree;
  }

  transpileTree(tree) {
    const Funnel = require('broccoli-funnel');
    const MergeTree = require('broccoli-merge-trees');
    const Plugin = require('broccoli-plugin');
    class TypescriptTree extends Plugin {
      constructor(tree, options) {
        return super([tree], options);
      }
      build() {
        return new Promise((resolve, reject) => {
          let tscPath = resolveSync('typescript', { cwd: __dirname });
          exec(path.join(tscPath, '..', '..', 'bin', 'tsc') + ' --outDir ' + this.outputPath, {
            cwd: this.inputPaths[0],
            stdio: 'inherit'
          }, (err, stdout, stderr) => {
            if (err) {
              if (stdout.match(/error TS\d+/)) {
                ui.warn(`\n===> ${ stdout.split('\n').length } Typescript Errors:`);
                ui.warn(stdout.replace(/^\.\.\/\.\.\//mg, ''));
              } else {
                return reject(err);
              }
            }
            resolve();
          });
        });
      }
    }
    let tsconfig = require(path.join(process.cwd(), 'tsconfig.json'));
    let transpiled = new TypescriptTree(tree, { tsconfig });
    let withoutTS = new Funnel(tree, {
      exclude: [ '**/*.ts' ]
    });
    return new MergeTree([ withoutTS, transpiled ], { overwrite: true, annotation: 'merge typescript outptu' });
  }

};
<commit_msg>fix: build output location (#2)<commit_after>const path = require('path');
const { Builder, ui } = require(`denali-cli`);
const { exec } = require('child_process');
const { sync: resolveSync } = require('resolve');

module.exports = class DenaliBuilder extends Builder {

  processParent(tree, dir) {
    tree = this.transpileTree(tree, dir);
    return tree;
  }

  transpileTree(tree, dir) {
    const Funnel = require('broccoli-funnel');
    const MergeTree = require('broccoli-merge-trees');
    const Plugin = require('broccoli-plugin');
    class TypescriptTree extends Plugin {
      constructor(tree, options) {
        return super([tree], options);
      }
      build() {
        return new Promise((resolve, reject) => {
          let tscPath = resolveSync('typescript', { cwd: __dirname });
          exec(path.join(tscPath, '..', '..', 'bin', 'tsc') + ' --rootDir ' + dir + ' --outDir ' + this.outputPath, {
            cwd: this.inputPaths[0],
            stdio: 'inherit'
          }, (err, stdout, stderr) => {
            if (err) {
              if (stdout.match(/error TS\d+/)) {
                ui.warn(`\n===> ${ stdout.split('\n').length } Typescript Errors:`);
                ui.warn(stdout.replace(/^\.\.\/\.\.\//mg, ''));
              } else {
                return reject(err);
              }
            }
            resolve();
          });
        });
      }
    }
    let tsconfig = require(path.join(process.cwd(), 'tsconfig.json'));
    let transpiled = new TypescriptTree(tree, { tsconfig });
    let withoutTS = new Funnel(tree, {
      exclude: [ '**/*.ts' ]
    });
    return new MergeTree([ withoutTS, transpiled ], { overwrite: true, annotation: 'merge typescript outptu' });
  }

};
<|endoftext|>


<commit_before>/* Copyright (c) 2012-2013 The TagSpaces Authors. All rights reserved.
 * Use of this source code is governed by a AGPL3 license that
 * can be found in the LICENSE file. */
//var LOG = debug ? console.log : function () {};
// the value of this var is replaced to "true" by the build script
var PRODUCTION = "@@PRODUCTION";

// Disabling all output to console in production mode
if (PRODUCTION == "true") {
    console = console || {};
    console.log = function(){};
    console.error = function(){};
    console.log = function(){};
}

var isFirefox = document.URL.indexOf( 'resource://' ) === 0;
var isFirefoxOS = document.URL.indexOf( 'app://' ) === 0;
//var isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0;
var isChrome =  document.URL.indexOf( 'chrome-extension://' ) === 0;
var isNode;
var isCordova = document.URL.indexOf( 'file:///android_asset' ) === 0;
var isWeb = document.URL.indexOf( 'http' ) === 0;
var isOSX = navigator.appVersion.indexOf("Mac")!==-1;
var isWin = navigator.appVersion.indexOf("Win")!==-1;

// Check for running in node-webkit
try {
    var fs = require('fs');
    var pathUtils = require('path');
    var gui = require('nw.gui');
    isNode = true;
} catch(e) {
    isNode = false;
    console.log("node-webkit not foundt!");
}

// Setting up the IO functionality according to the platform
var IO_JS;
if( isFirefox ) {
    IO_JS = "mozilla/mozilla.api";
} else if ( isFirefoxOS ) {
    IO_JS = "mozilla/firefoxos.api";
} else if ( isChrome ) {
    IO_JS = "chrome/chrome.api";
} else if (isNode){
    IO_JS = "node-webkit/node-webkit.api";
} else if (isCordova){
    IO_JS = "cordova/cordova.api";
} else if (isWeb){
    IO_JS = "web/web.api";
} else {
    IO_JS = "web/web.api";
}

//IO_JS = "js/ioapi.dropbox";

console.log("Loading Loader - Firefox: "+isFirefox+" | ChromeExt: "+isChrome+" | Node: "+isNode+" | Cordova: "+isCordova);

requirejs.config({
    map: {
      '*': {
        'css':  'libs/requirecss/css',
        'text':  'libs/requiretext/text'
      }
    },
    paths: {
        jquery:                 'libs/jquery/jquery-2.0.1',
        jqueryui:               'libs/jqueryui/jquery.ui.core',
        jqueryuiwidget:         'libs/jqueryui/jquery.ui.widget',
        jqueryuimouse:          'libs/jqueryui/jquery.ui.mouse',
        jqueryuiposition:       'libs/jqueryui/jquery.ui.position',
        jqueryuiselectable:     'libs/jqueryui/jquery.ui.selectable',
        jqueryuisortable:       'libs/jqueryui/jquery.ui.sortable',
        jqueryuiresizable:      'libs/jqueryui/jquery.ui.resizable',
        jqueryuidraggable:      'libs/jqueryui/jquery.ui.draggable',
        jqueryuidroppable:      'libs/jqueryui/jquery.ui.droppable',
        jqueryuiautocomplete:   'libs/jqueryui/jquery.ui.autocomplete',
        jqueryuidatepicker:     'libs/jqueryui/jquery.ui.datepicker',

        bootstrap:              'libs/bootstrap/js/bootstrap.min',
        bootstrap3xeditable:    'libs/bootstrap3xeditable/js/bootstrap-editable.min',
        jquerysimplecolorpicker:'libs/jquery-simplecolorpicker/jquery.simplecolorpicker',
        jquerylayout:           'libs/jquerylayout/jquery.layout-latest',
        underscore:             'libs/underscore/underscore',
        d3:                     'libs/d3/d3.v3',
        dropbox:                'libs/dropbox/dropbox.0.10.2',
        i18next:                'libs/i18next/i18next.amd.withJQuery-1.7.1',
        mousetrap:              'libs/mousetrap/mousetrap.min',
        select2:                'libs/select2/select2.min',
        hammerjs:               'libs/hammerjs/jquery.hammer.min',
        handlebarsjs:           'libs/handlebars.js/handlebars-v1.1.2',
        webdavlib:              'web/webdavlib',
        fastclick:              'cordova/fastclick.min',

        tscore:                 'js/core.api',
        tssetting:              'js/settings.api',
        tssettingsdefault:      'js/settings.default',
        tsoptions:              'js/options.ui',
        tspersmanager:          'js/perspective.manager',
        tstagutils:             'js/tagutils',
        tssearch:               'js/search',
        tsfileopener:           'js/fileopener',
        tstagsui:               'js/tags.ui',
        tsdirectoriesui:        'js/directories.ui',
        tscoreui:               'js/core.ui',
        tspostioapi:            'js/postioapi',
        tsioapi:                IO_JS,
        tsioapidropbox:         'js/ioapi.dropbox',
        tsdirectorybrowser:     'js/directorybrowser'
    },
    shim: {
        'underscore':               { exports: '_' },
        'bootstrap':                { deps: ['jquery'] },
        'jquerysimplecolorpicker':  { deps: ['jquery','bootstrap'] },
        'jqueryui':                 { deps: ['jquery'] },
        'jqueryuiwidget':           { deps: ['jqueryui'] },
        'jqueryuimouse':            { deps: ['jqueryui','jqueryuiwidget'] },
        'jqueryuiposition':         { deps: ['jqueryui'] },
        'jqueryuiselectable':       { deps: ['jqueryui','jqueryuiwidget','jqueryuimouse'] },
        'jqueryuisortable':         { deps: ['jqueryui','jqueryuiwidget','jqueryuimouse'] },
        'jqueryuidatepicker':       { deps: ['jqueryui'] },
        'jqueryuidroppable':        { deps: ['jqueryui','jqueryuiwidget','jqueryuimouse','jqueryuidraggable'] },
        'jqueryuidraggable':        { deps: ['jqueryui','jqueryuiwidget','jqueryuimouse'] },
        'jqueryuiresizable':        { deps: ['jqueryui','jqueryuiwidget','jqueryuimouse'] },
        'jquerylayout':             { deps: ['jquery','jqueryuidraggable' ] },
        'jquerydropdown':           { deps: ['jquery','bootstrap'] },
        'bootstrap3xeditable':      { deps: ['jquery','jqueryui','bootstrap'] },
        'jquerynanoscroller':       { deps: ['jquery'] },
        'select2':                  { deps: ['jquery'] },
        'hammerjs':                 { deps: ['jquery'] },
        'tscore':                   { deps: [
                'jquery',
                'jqueryui',
                'jqueryuidraggable',
                'jqueryuidroppable',
                'jqueryuiresizable',
                'jqueryuiposition',
                'jqueryuiselectable',
                'jqueryuisortable',
                'hammerjs',
                'bootstrap',
                'bootstrap3xeditable',
                'jquerysimplecolorpicker',
                'jquerylayout',
                'i18next',
                'mousetrap',
                'select2',
                'handlebarsjs',
                'tssettingsdefault'
            ] }
    }
});

define(function (require, exports, module) {
"use strict";

	if(isCordova) {
	    require(["cordova.js"]);
	}

    var TSCORE;
    requirejs(['tscore','underscore'], function (core,_) {
        TSCORE = core;
        TSCORE.initApp();
    });
});<commit_msg>jshinting<commit_after>/* Copyright (c) 2012-2013 The TagSpaces Authors. All rights reserved.
 * Use of this source code is governed by a AGPL3 license that
 * can be found in the LICENSE file. */
//var LOG = debug ? console.log : function () {};
// the value of this var is replaced to "true" by the build script
var PRODUCTION = "@@PRODUCTION";

// Disabling all output to console in production mode
if (PRODUCTION == "true") {
    console = console || {};
    console.log = function(){};
    console.error = function(){};
    console.log = function(){};
}

var isFirefox = document.URL.indexOf( 'resource://' ) === 0;
var isFirefoxOS = document.URL.indexOf( 'app://' ) === 0;
//var isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0;
var isChrome =  document.URL.indexOf( 'chrome-extension://' ) === 0;
var isNode;
var isCordova = document.URL.indexOf( 'file:///android_asset' ) === 0;
var isWeb = document.URL.indexOf( 'http' ) === 0;
var isOSX = navigator.appVersion.indexOf("Mac")!==-1;
var isWin = navigator.appVersion.indexOf("Win")!==-1;

// Check for running in node-webkit
try {
    var fs = require('fs');
    var pathUtils = require('path');
    var gui = require('nw.gui');
    isNode = true;
} catch(e) {
    isNode = false;
    console.log("node-webkit not foundt!");
}

// Setting up the IO functionality according to the platform
var IO_JS;
if( isFirefox ) {
    IO_JS = "mozilla/mozilla.api";
} else if ( isFirefoxOS ) {
    IO_JS = "mozilla/firefoxos.api";
} else if ( isChrome ) {
    IO_JS = "chrome/chrome.api";
} else if (isNode){
    IO_JS = "node-webkit/node-webkit.api";
} else if (isCordova){
    IO_JS = "cordova/cordova.api";
} else if (isWeb){
    IO_JS = "web/web.api";
} else {
    IO_JS = "web/web.api";
}

//IO_JS = "js/ioapi.dropbox";

console.log("Loading Loader - Firefox: "+isFirefox+" | ChromeExt: "+isChrome+" | Node: "+isNode+" | Cordova: "+isCordova);

requirejs.config({
    map: {
      '*': {
        'css':  'libs/requirecss/css',
        'text':  'libs/requiretext/text'
      }
    },
    paths: {
        jquery:                 'libs/jquery/jquery-2.0.1',
        jqueryui:               'libs/jqueryui/jquery.ui.core',
        jqueryuiwidget:         'libs/jqueryui/jquery.ui.widget',
        jqueryuimouse:          'libs/jqueryui/jquery.ui.mouse',
        jqueryuiposition:       'libs/jqueryui/jquery.ui.position',
        jqueryuiselectable:     'libs/jqueryui/jquery.ui.selectable',
        jqueryuisortable:       'libs/jqueryui/jquery.ui.sortable',
        jqueryuiresizable:      'libs/jqueryui/jquery.ui.resizable',
        jqueryuidraggable:      'libs/jqueryui/jquery.ui.draggable',
        jqueryuidroppable:      'libs/jqueryui/jquery.ui.droppable',
        jqueryuiautocomplete:   'libs/jqueryui/jquery.ui.autocomplete',
        jqueryuidatepicker:     'libs/jqueryui/jquery.ui.datepicker',

        bootstrap:              'libs/bootstrap/js/bootstrap.min',
        bootstrap3xeditable:    'libs/bootstrap3xeditable/js/bootstrap-editable.min',
        jquerysimplecolorpicker:'libs/jquery-simplecolorpicker/jquery.simplecolorpicker',
        jquerylayout:           'libs/jquerylayout/jquery.layout-latest',
        underscore:             'libs/underscore/underscore',
        d3:                     'libs/d3/d3.v3',
        dropbox:                'libs/dropbox/dropbox.0.10.2',
        i18next:                'libs/i18next/i18next.amd.withJQuery-1.7.1',
        mousetrap:              'libs/mousetrap/mousetrap.min',
        select2:                'libs/select2/select2.min',
        hammerjs:               'libs/hammerjs/jquery.hammer.min',
        handlebarsjs:           'libs/handlebars.js/handlebars-v1.1.2',
        webdavlib:              'web/webdavlib',
        fastclick:              'cordova/fastclick.min',

        tscore:                 'js/core.api',
        tssetting:              'js/settings.api',
        tssettingsdefault:      'js/settings.default',
        tsoptions:              'js/options.ui',
        tspersmanager:          'js/perspective.manager',
        tstagutils:             'js/tagutils',
        tssearch:               'js/search',
        tsfileopener:           'js/fileopener',
        tstagsui:               'js/tags.ui',
        tsdirectoriesui:        'js/directories.ui',
        tscoreui:               'js/core.ui',
        tspostioapi:            'js/postioapi',
        tsioapi:                IO_JS,
        tsioapidropbox:         'js/ioapi.dropbox',
        tsdirectorybrowser:     'js/directorybrowser'
    },
    shim: {
        'underscore':               { exports: '_' },
        'bootstrap':                { deps: ['jquery'] },
        'jquerysimplecolorpicker':  { deps: ['jquery','bootstrap'] },
        'jqueryui':                 { deps: ['jquery'] },
        'jqueryuiwidget':           { deps: ['jqueryui'] },
        'jqueryuimouse':            { deps: ['jqueryui','jqueryuiwidget'] },
        'jqueryuiposition':         { deps: ['jqueryui'] },
        'jqueryuiselectable':       { deps: ['jqueryui','jqueryuiwidget','jqueryuimouse'] },
        'jqueryuisortable':         { deps: ['jqueryui','jqueryuiwidget','jqueryuimouse'] },
        'jqueryuidatepicker':       { deps: ['jqueryui'] },
        'jqueryuidroppable':        { deps: ['jqueryui','jqueryuiwidget','jqueryuimouse','jqueryuidraggable'] },
        'jqueryuidraggable':        { deps: ['jqueryui','jqueryuiwidget','jqueryuimouse'] },
        'jqueryuiresizable':        { deps: ['jqueryui','jqueryuiwidget','jqueryuimouse'] },
        'jquerylayout':             { deps: ['jquery','jqueryuidraggable' ] },
        'jquerydropdown':           { deps: ['jquery','bootstrap'] },
        'bootstrap3xeditable':      { deps: ['jquery','jqueryui','bootstrap'] },
        'jquerynanoscroller':       { deps: ['jquery'] },
        'select2':                  { deps: ['jquery'] },
        'hammerjs':                 { deps: ['jquery'] },
        'tscore':                   { deps: [
                'jquery',
                'jqueryui',
                'jqueryuidraggable',
                'jqueryuidroppable',
                'jqueryuiresizable',
                'jqueryuiposition',
                'jqueryuiselectable',
                'jqueryuisortable',
                'hammerjs',
                'bootstrap',
                'bootstrap3xeditable',
                'jquerysimplecolorpicker',
                'jquerylayout',
                'i18next',
                'mousetrap',
                'select2',
                'handlebarsjs',
                'tssettingsdefault'
            ] }
    }
});

define(function (require, exports, module) {
"use strict";

    if(isCordova) {
	    require(["cordova.js"]);
	}

    var TSCORE;
    requirejs(['tscore','underscore'], function (core,_) {
        TSCORE = core;
        TSCORE.initApp();
    });
});<|endoftext|>