<commit_before>/*
 * Basic $ components
 * @module $
 */

var $ = function (selector, context) {
    return new $.fn.init(selector, context);
};

$.fn = $.prototype = {
    constructor: $,

    selector: '',

    length: 0,

    splice: Array.prototype.splice,

    isDollar: true,

    // Get the Nth element in the matched element set OR
    // Get the whole matched element set as a clean array
    get: function (num) {

        var res = [];

        return (num || num === 0) ?

            // Return just the one element from the set
            (num < 0 ? this[num + this.length] : this[num]) :

            // Return all the elements in a clean array
            Array.prototype.push.apply(res, this), res;
        // https://jsperf.com/appending-to-an-array-push-apply-vs-loop/14
        // slice.call is much slower than push.apply for DOM elements
    }
};

// Ops/sec  ~ 6/13/15
// selector - dollar   -   jQuery
// id         1,318,890    1,493,964
// tag        316,465      234,686
// class      344,837      242,628
// pseudo     21,448       23,246

// http://jsperf.com/intent-media-dollarjs-vs-jquery-init
var init = $.fn.init = function (selector, context) {

    context = context || document;

    // HANDLE: $(""), $(null), $(undefined), $(false)
    if (!selector) {
        return this;
    }

    // HANDLE: strings
    if (typeof selector === 'string') {

        this.selector = selector;
        this.context = context;
        return $.merge(this, $.fn.findBySelector(selector, context));

    // HANDLE: $(DOM Element)
    } else if (selector.nodeType) {

        this.context = this[0] = selector;
        this.length = 1;
        return this;

    // HANDLE: dollar instance
    } else if (selector.isDollar) {

        this.selector = selector.selector;
        this.context = selector.context;
        return $.merge(this, selector.get());

    // HANDLE: dom ready
    } else if (typeof selector === 'function') {
        if (document.readyState === 'complete') {
            setTimeout(domReady);
        } else {
            $.fn.on.call(document, 'DOMContentLoaded', domReady);
        }
    }

    function domReady () {
        if ($.domReadyFnInvoked) {
            return;
        }

        $.domReadyFnInvoked = true;
        selector($);
    }
};

// Ops/sec  ~ 6/13/15
// selector - dollar   -   Sizzle
// id         3,773k       984k
// tag        487k         447k
// class      484k         423k
// complex    56k          50k
$.fn.findBySelector = function (selector, context) {

    // get selector as string
    selector = selector.isDollar ? selector.selector : selector;

    // exit early for improper selectors
    if (!selector || typeof selector !== 'string') {
        return [];
    }

    // normalize context to node or document
    context = context || (this.isDollar && this[0]) || (this.nodeType && this) || document;

    // exit early for improper context
    if (context.nodeType !== 1 && context.nodeType !== 9) {
        return [];
    }

    var push = Array.prototype.push,
        results = [];

    var selectorsMap = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/.exec(selector);
    // selectorsMap will return:
    // if id => ['#foo', 'foo', undefined, undefined]
    // node  => ['body', undefined, body, undefined']
    // class => ['.bar', undefined, undefined, 'bar']
    // else  => null

    if (selectorsMap) {

        // HANDLE: $('#id')
        if (selector = selectorsMap[1]) {
            results.push(context.getElementById(selector));

        // HANDLE: $('tag')
        } else if (selector = selectorsMap[2]) {
            push.apply(results, context.getElementsByTagName(selector));

        // HANDLE: $('.class')
        } else if (selector = selectorsMap[3]) {
            // push.apply(results, context.getElementsByClassName(selector));

            // // ie8 polyfill
            push.apply(results, polyfillGetClass(context, selector));
        }

    // HANDLE: pseudo-selectors, chained classes, etc.
    } else {
        push.apply(results, context.querySelectorAll(selector));
    }

    // HANDLE: $('#id') returns null
    return results[0] ? results : [];

    function polyfillGetClass (con, sel) { // wtf this is so hacky
        return con.getElementsByClassName ?
            con.getElementsByClassName(sel) :
            con.querySelectorAll('.' + sel);
    }
};

$.fn.matchesSelector = function (selector) {

    // get element
    var node = this.isDollar ? this[0] : this;

    // take only DOM nodes,
    // reject doc.frags, text, document, etc.
    if (node.nodeType !== 1) {
        return false;
    }

    // stringify selector
    if (selector.isDollar) {
        selector = selector.selector;
    }

    // normalise browser nonsense
    var matches = node.matches || node.webkitMatchesSelector || node.mozMatchesSelector || node.msMatchesSelector;

    // return matches.call(node, selector);

    // IE8 polyfill
    return matches ?
        matches.call(node, selector) :
        polyfillMatches(selector);

    function polyfillMatches (sel) {
        var allMatches = document.querySelectorAll(sel);
        return Array.prototype.indexOf.call(allMatches, node) > -1;
    }
};

$.merge = function (first, second) {
    var len = +second.length,
        j = 0,
        i = first.length;

    for (; j < len; j++) {
        first[i++] = second[j];
    }

    first.length = i;

    return first;
};

$.unique = function (jumbled) {

    var jumbled = jumbled,
        iterable = Object(jumbled),
        distinct = [];

    if (!iterable.length) {
        return jumbled;
    }

    for (var i = 0, len = iterable.length; i < len; i++) {
        if (distinct.indexOf(iterable[i]) === -1) {
            distinct.push(iterable[i]);
        }
    }

    return distinct;
};

// Give the init function the $ prototype for later instantiation
init.prototype = $.fn;

/*
 * Submodules to add...
 *
 * CORE
 * - init(), [], .length, get(), DOMContentLoaded handler
 * - events = .on(), .off()
 * - selectors = .find(), .closest()
 * - filters = .filter(), unique()
 *
 * FILTERS
 * - .is(), .not()
 * - .add()
 *
 * DOM
 * - traversal = .has(), .parent(), .children()
 * - reading = .val(), .text(), .attr()
 *
 * Styles
 * - .css()
 * - .hasClass()
 * - .addClass(), .removeClass()
 *
 * Data
 * - .data(), .removeData()
 *
 * Triggers
 * - .focus(), .blur()
 *
 * Mutation
 * - .empty(), .remove()
 * - .append(), .html(), .prepend()
 *
 * Animation
 * (use css transform if possible)
 *
 */

/////////////////////////////////////

/* BASE
 * - selectors = .find(), .closest()
 * - filters = .filter(), .unique(), .eq()
 * - events = .on()
 */
$.fn.on = function (types, handler) {

    if (!types || typeof handler !== 'function') {
        return this;
    }

    // normalize context to [element]
    // separate events
    var context = this.isDollar ? this.get() : this.length ? this : [this],
        events = types.split(' ');

    for (var i = 0, len = context.length; i < len; i++) {
        for (var j = 0, eventLen = events.length; j < eventLen; j++) {
            addEventListener(context[i], events[j], handler);
        }
    }

    return this;

    function addEventListener (context, event, callback) {
        if (Element.prototype.addEventListener) {
            context.addEventListener(event, callback);
        } else {
            // IE8 Polyfill
            if (event === 'DOMContentLoaded') {
                var event = new Event();
                event.srcElement = window;
                addEventPolyfillWrapper(event);
            } else {
                context.attachEvent('on' + event, addEventPolyfillWrapper);
            }
        }

        function addEventPolyfillWrapper (e) {
            e.target = e.srcElement;
            e.currentTarget = context;
            if (callback.handleEvent) {
                callback.handleEvent(e);
            } else {
                listener.call(context, e);
            }
        }
    }
};

$.fn.off = function (types, handler) {

};

// Ops/sec  ~  6/13/15
// dollar   -   jQuery
// 116,602      48,145
$.fn.find = function (selector) {

    if (!selector) {
        return $.merge($(), []);
    }

    var matches = [],
        targetLen = this.length;

    selector = selector.isDollar ? selector.selector : selector;

    if (this.isDollar && targetLen > 1) {

        var allMatches = $.fn.findBySelector(selector),
            _this = this;

        matches = $.fn.filter.call(allMatches, function () {
            // keep where context contains instance of allMatches
            for (var i = 0; i < _this.length; i++) {
                if (_this[i] !== this && _this[i].contains(this)) {
                    return true;
                }
            }
        });
    } else {
        matches = $.fn.findBySelector.call(this, selector);
    }

    return $.merge($(), $.unique(matches));
};

// Ops/sec  ~  6/13/15
// dollar   -   jQuery
// 205,279      81,851
$.fn.closest = function (selector, context) {

    if (!selector) {
        return $.merge($(), []);
    }

    var matches = [];
    // if is dollar instance & context was provided, re-wrap the selector in the context
    var foundBySelector = selector.isDollar && (context && $(selector, context) || selector);

    for (var i = 0, len = this.length; i < len; i++) {
        var node = this[i];
        while (node && node !== context) {

            var nodeMatchesSelector = foundBySelector ?
                Array.prototype.indexOf.call(foundBySelector, node) > -1 :
                this.matchesSelector.call(node, selector, context);

            if (this.matchesSelector.call(node, selector, context)) {
                matches.push(node);
                break;
            }

            node = node.parentNode;
        }
    }

    return $.merge($(), $.unique(matches));
};

// Ops/sec  ~  6/13/15
// dollar   -   jQuery   -  type
// 115,512      67,194      string
// 221,728      145,560     fn
$.fn.filter = function (criteria) {

    if (!this.length) {
        return [];
    }

    if (!criteria) {
        return this;
    }

    var filterFn;

    // HANDLE: function
    if (typeof criteria === 'function') {

        filterFn = criteria;

        // HANDLE: 'selector' || node
    } else if (typeof criteria === 'string' || criteria.isDollar) {

        filterFn = function () {
            return $.fn.matchesSelector.call(this, criteria);
        };

    } else {

        return this;
    }

    var result = [];

    for (var i = 0, len = this.length; i < len; i++) {
        if (filterFn.call(this[i], i, this[i])) {
            result.push(this[i]);
        }
    }

    return $.merge($(), result.length > 1 ? $.unique(result) : result);
};

$.fn.eq = function (index) {
    if (this[index]) {
        return $(this[index]);
    }
};<commit_msg>IW: update requirements<commit_after>/*
 * Basic $ components
 * @module $
 */

var $ = function (selector, context) {
    return new $.fn.init(selector, context);
};

$.fn = $.prototype = {
    constructor: $,

    selector: '',

    length: 0,

    splice: Array.prototype.splice,

    isDollar: true,

    // Get the Nth element in the matched element set OR
    // Get the whole matched element set as a clean array
    get: function (num) {

        var res = [];

        return (num || num === 0) ?

            // Return just the one element from the set
            (num < 0 ? this[num + this.length] : this[num]) :

            // Return all the elements in a clean array
            Array.prototype.push.apply(res, this), res;
        // https://jsperf.com/appending-to-an-array-push-apply-vs-loop/14
        // slice.call is much slower than push.apply for DOM elements
    }
};

// Ops/sec  ~ 6/13/15
// selector - dollar   -   jQuery
// id         1,318,890    1,493,964
// tag        316,465      234,686
// class      344,837      242,628
// pseudo     21,448       23,246

// http://jsperf.com/intent-media-dollarjs-vs-jquery-init
var init = $.fn.init = function (selector, context) {

    context = context || document;

    // HANDLE: $(""), $(null), $(undefined), $(false)
    if (!selector) {
        return this;
    }

    // HANDLE: strings
    if (typeof selector === 'string') {

        this.selector = selector;
        this.context = context;
        return $.merge(this, $.fn.findBySelector(selector, context));

    // HANDLE: $(DOM Element)
    } else if (selector.nodeType) {

        this.context = this[0] = selector;
        this.length = 1;
        return this;

    // HANDLE: dollar instance
    } else if (selector.isDollar) {

        this.selector = selector.selector;
        this.context = selector.context;
        return $.merge(this, selector.get());

    // HANDLE: dom ready
    } else if (typeof selector === 'function') {
        if (document.readyState === 'complete') {
            setTimeout(domReady);
        } else {
            $.fn.on.call(document, 'DOMContentLoaded', domReady);
        }
    }

    function domReady () {
        if ($.domReadyFnInvoked) {
            return;
        }

        $.domReadyFnInvoked = true;
        selector($);
    }
};

// Ops/sec  ~ 6/13/15
// selector - dollar   -   Sizzle
// id         3,773k       984k
// tag        487k         447k
// class      484k         423k
// complex    56k          50k
$.fn.findBySelector = function (selector, context) {

    // get selector as string
    selector = selector.isDollar ? selector.selector : selector;

    // exit early for improper selectors
    if (!selector || typeof selector !== 'string') {
        return [];
    }

    // normalize context to node or document
    context = context || (this.isDollar && this[0]) || (this.nodeType && this) || document;

    // exit early for improper context
    if (context.nodeType !== 1 && context.nodeType !== 9) {
        return [];
    }

    var push = Array.prototype.push,
        results = [];

    var selectorsMap = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/.exec(selector);
    // selectorsMap will return:
    // if id => ['#foo', 'foo', undefined, undefined]
    // node  => ['body', undefined, body, undefined']
    // class => ['.bar', undefined, undefined, 'bar']
    // else  => null

    if (selectorsMap) {

        // HANDLE: $('#id')
        if (selector = selectorsMap[1]) {
            results.push(context.getElementById(selector));

        // HANDLE: $('tag')
        } else if (selector = selectorsMap[2]) {
            push.apply(results, context.getElementsByTagName(selector));

        // HANDLE: $('.class')
        } else if (selector = selectorsMap[3]) {
            // push.apply(results, context.getElementsByClassName(selector));

            // // ie8 polyfill
            push.apply(results, polyfillGetClass(context, selector));
        }

    // HANDLE: pseudo-selectors, chained classes, etc.
    } else {
        push.apply(results, context.querySelectorAll(selector));
    }

    // HANDLE: $('#id') returns null
    return results[0] ? results : [];

    function polyfillGetClass (con, sel) { // wtf this is so hacky
        return con.getElementsByClassName ?
            con.getElementsByClassName(sel) :
            con.querySelectorAll('.' + sel);
    }
};

$.fn.matchesSelector = function (selector) {

    // get element
    var node = this.isDollar ? this[0] : this;

    // take only DOM nodes,
    // reject doc.frags, text, document, etc.
    if (node.nodeType !== 1) {
        return false;
    }

    // stringify selector
    if (selector.isDollar) {
        selector = selector.selector;
    }

    // normalise browser nonsense
    var matches = node.matches || node.webkitMatchesSelector || node.mozMatchesSelector || node.msMatchesSelector;

    // return matches.call(node, selector);

    // IE8 polyfill
    return matches ?
        matches.call(node, selector) :
        polyfillMatches(selector);

    function polyfillMatches (sel) {
        var allMatches = document.querySelectorAll(sel);
        return Array.prototype.indexOf.call(allMatches, node) > -1;
    }
};

$.merge = function (first, second) {
    var len = +second.length,
        j = 0,
        i = first.length;

    for (; j < len; j++) {
        first[i++] = second[j];
    }

    first.length = i;

    return first;
};

$.unique = function (jumbled) {

    var jumbled = jumbled,
        iterable = Object(jumbled),
        distinct = [];

    if (!iterable.length) {
        return jumbled;
    }

    for (var i = 0, len = iterable.length; i < len; i++) {
        if (distinct.indexOf(iterable[i]) === -1) {
            distinct.push(iterable[i]);
        }
    }

    return distinct;
};

// Give the init function the $ prototype for later instantiation
init.prototype = $.fn;

/*
 * Submodules to add...
 *
 * CORE
 * - init(), [], .length, get(), DOMContentLoaded handler
 * - events = .on() / .bind(), .off() / .unbind()
 * - selectors = .find(), .closest()
 * - filters = .filter(), unique(), .each()
 *
 * FILTERS
 * - .is(), .not(), .has()
 * - .add()
 *
 * DOM
 * - traversal = .has(), .parent(), .children(), .siblings(), .first(), .last(), .next()
 * - reading = .val(), .text(), .attr(), .prop()
 *
 * Styles
 * - .css()
 * - .hasClass()
 * - .addClass(), .removeClass()
 * - .show(), .hide()
 *
 * Data
 * - .data(), .removeData()
 *
 * Triggers
 * - .focus(), .blur(), .change(), .click(), .resize(), .trigger()
 *
 * Mutation
 * - .empty(), .remove()
 * - .append(), after(), .html(), .prepend(), before()
 *
 * Animation
 * (use css transform if possible)
 *
 */

/////////////////////////////////////

/* BASE
 * - selectors = .find(), .closest()
 * - filters = .filter(), .unique(), .eq()
 * - events = .on()
 */
$.fn.on = function (types, handler) {

    if (!types || typeof handler !== 'function') {
        return this;
    }

    // normalize context to [element]
    // separate events
    var context = this.isDollar ? this.get() : this.length ? this : [this],
        events = types.split(' ');

    for (var i = 0, len = context.length; i < len; i++) {
        for (var j = 0, eventLen = events.length; j < eventLen; j++) {
            addEventListener(context[i], events[j], handler);
        }
    }

    return this;

    function addEventListener (context, event, callback) {
        if (Element.prototype.addEventListener) {
            context.addEventListener(event, callback);
        } else {
            // IE8 Polyfill
            if (event === 'DOMContentLoaded') {
                var event = new Event();
                event.srcElement = window;
                addEventPolyfillWrapper(event);
            } else {
                context.attachEvent('on' + event, addEventPolyfillWrapper);
            }
        }

        function addEventPolyfillWrapper (e) {
            e.target = e.srcElement;
            e.currentTarget = context;
            if (callback.handleEvent) {
                callback.handleEvent(e);
            } else {
                listener.call(context, e);
            }
        }
    }
};

$.fn.off = function (types, handler) {

};

// Ops/sec  ~  6/13/15
// dollar   -   jQuery
// 116,602      48,145
$.fn.find = function (selector) {

    if (!selector) {
        return $.merge($(), []);
    }

    var matches = [],
        targetLen = this.length;

    selector = selector.isDollar ? selector.selector : selector;

    if (this.isDollar && targetLen > 1) {

        var allMatches = $.fn.findBySelector(selector),
            _this = this;

        matches = $.fn.filter.call(allMatches, function () {
            // keep where context contains instance of allMatches
            for (var i = 0; i < _this.length; i++) {
                if (_this[i] !== this && _this[i].contains(this)) {
                    return true;
                }
            }
        });
    } else {
        matches = $.fn.findBySelector.call(this, selector);
    }

    return $.merge($(), $.unique(matches));
};

// Ops/sec  ~  6/13/15
// dollar   -   jQuery
// 205,279      81,851
$.fn.closest = function (selector, context) {

    if (!selector) {
        return $.merge($(), []);
    }

    var matches = [];
    // if is dollar instance & context was provided, re-wrap the selector in the context
    var foundBySelector = selector.isDollar && (context && $(selector, context) || selector);

    for (var i = 0, len = this.length; i < len; i++) {
        var node = this[i];
        while (node && node !== context) {

            var nodeMatchesSelector = foundBySelector ?
                Array.prototype.indexOf.call(foundBySelector, node) > -1 :
                this.matchesSelector.call(node, selector, context);

            if (this.matchesSelector.call(node, selector, context)) {
                matches.push(node);
                break;
            }

            node = node.parentNode;
        }
    }

    return $.merge($(), $.unique(matches));
};

// Ops/sec  ~  6/13/15
// dollar   -   jQuery   -  type
// 115,512      67,194      string
// 221,728      145,560     fn
$.fn.filter = function (criteria) {

    if (!this.length) {
        return [];
    }

    if (!criteria) {
        return this;
    }

    var filterFn;

    // HANDLE: function
    if (typeof criteria === 'function') {

        filterFn = criteria;

        // HANDLE: 'selector' || node
    } else if (typeof criteria === 'string' || criteria.isDollar) {

        filterFn = function () {
            return $.fn.matchesSelector.call(this, criteria);
        };

    } else {

        return this;
    }

    var result = [];

    for (var i = 0, len = this.length; i < len; i++) {
        if (filterFn.call(this[i], i, this[i])) {
            result.push(this[i]);
        }
    }

    return $.merge($(), result.length > 1 ? $.unique(result) : result);
};

$.fn.eq = function (index) {
    if (this[index]) {
        return $(this[index]);
    }
};<|endoftext|>


<commit_before>/*
 * Paper.js - The Swiss Army Knife of Vector Graphics Scripting.
 * http://paperjs.org/
 *
 * Copyright (c) 2011 - 2013, Juerg Lehni & Jonathan Puckey
 * http://lehni.org/ & http://jonathanpuckey.com/
 *
 * Distributed under the MIT license. See LICENSE file for details.
 *
 * All rights reserved.
 */

// Node.js emulation layer of browser based environment, based on node-canvas
// and jsdom.

// console.log(__dirname);

var jsdom = require('jsdom'),
	domToHtml = require('jsdom/lib/jsdom/browser/domtohtml').domToHtml,
	// Node Canvas library: https://github.com/learnboost/node-canvas
	Canvas = require('canvas');

// Expose global browser variables and create a document and a window using
// jsdom, e.g. for import/exportSVG()
var document = jsdom.jsdom(''),
	window = document.createWindow(),
	navigator = window.navigator,
	HTMLCanvasElement = Canvas,
	Image = Canvas.Image;

// Define XMLSerializer and DOMParser shims, to emulate browser behavior.
// TODO: Put this into a simple node module, with dependency on jsdom?
function XMLSerializer() {
}

XMLSerializer.prototype.serializeToString = function(node) {
	var text = domToHtml(node);
	// Fix a jsdom issue where all SVG tagNames are lowercased:
	// https://github.com/tmpvar/jsdom/issues/620
	var tagNames = ['linearGradient', 'radialGradient', 'clipPath'];
	for (var i = 0, l = tagNames.length; i < l; i++) {
		var tagName = tagNames[i];
		text = text.replace(
			new RegExp('(<|</)' + tagName.toLowerCase() + '\\b', 'g'),
			function(all, start) {
				return start + tagName;
			});
	}
	return text;
};

function DOMParser() {
}

DOMParser.prototype.parseFromString = function(string, contenType) {
	var div = doc.createElement('div');
	div.innerHTML = string;
	return div.firstChild;
};
<commit_msg>correct reference to document in importSVG<commit_after>/*
 * Paper.js - The Swiss Army Knife of Vector Graphics Scripting.
 * http://paperjs.org/
 *
 * Copyright (c) 2011 - 2013, Juerg Lehni & Jonathan Puckey
 * http://lehni.org/ & http://jonathanpuckey.com/
 *
 * Distributed under the MIT license. See LICENSE file for details.
 *
 * All rights reserved.
 */

// Node.js emulation layer of browser based environment, based on node-canvas
// and jsdom.

// console.log(__dirname);

var jsdom = require('jsdom'),
	domToHtml = require('jsdom/lib/jsdom/browser/domtohtml').domToHtml,
	// Node Canvas library: https://github.com/learnboost/node-canvas
	Canvas = require('canvas');

// Expose global browser variables and create a document and a window using
// jsdom, e.g. for import/exportSVG()
var document = jsdom.jsdom(''),
	window = document.createWindow(),
	navigator = window.navigator,
	HTMLCanvasElement = Canvas,
	Image = Canvas.Image;

// Define XMLSerializer and DOMParser shims, to emulate browser behavior.
// TODO: Put this into a simple node module, with dependency on jsdom?
function XMLSerializer() {
}

XMLSerializer.prototype.serializeToString = function(node) {
	var text = domToHtml(node);
	// Fix a jsdom issue where all SVG tagNames are lowercased:
	// https://github.com/tmpvar/jsdom/issues/620
	var tagNames = ['linearGradient', 'radialGradient', 'clipPath'];
	for (var i = 0, l = tagNames.length; i < l; i++) {
		var tagName = tagNames[i];
		text = text.replace(
			new RegExp('(<|</)' + tagName.toLowerCase() + '\\b', 'g'),
			function(all, start) {
				return start + tagName;
			});
	}
	return text;
};

function DOMParser() {
}

DOMParser.prototype.parseFromString = function(string, contenType) {
	var div = document.createElement('div');
	div.innerHTML = string;
	return div.firstChild;
};
<|endoftext|>


<commit_before>var createPage = require('./util').createPage;
var difference = require('mout/array/difference');
var forEach = require('mout/array/forEach');
var forOwn = require('mout/object/forOwn');
var keys = require('mout/object/keys');
var moment = require('moment');
var processMagazine = require('./magazine');
var Workflow = require('./workflow');
var sort = require('mout/array/sort');
var system = require('system');
var util = require('./util');

var magazineAccessArray = [];
var magazineAccess = util.getMagazineAccess();
var magazines = [];
var workflow = new Workflow(createPage());

forOwn(magazineAccess, function (val, key) {
  magazineAccessArray.push({
    name: key,
    lastProcessed: moment(val)
  });
});
magazineAccessArray = sort(magazineAccessArray, function (a, b) {
  return b.lastProcessed < a.lastProcessed;
});

var systemArgs = util.parseSystemArgs(system.args);
systemArgs.exclude = systemArgs.exclude ? systemArgs.exclude.split(',') : [];
systemArgs.mags = systemArgs.mags ? systemArgs.mags.split(',') : [];
systemArgs.output = systemArgs.output || 'images/';

if (!/\/$/.test(systemArgs.output)) {
  systemArgs.output += '/';
}

function validateRequested(name) {
  var lowerName = name.toLowerCase();
  var isExcluded = systemArgs.exclude.indexOf(lowerName) > -1;

  if (!systemArgs.mags.length && !isExcluded) {
    return true;
  }
  if (isExcluded) {
    return false;
  }
  return systemArgs.mags.indexOf(lowerName) > -1;
}

workflow.addStep('Load signin page', function (done) {
  var page = workflow._page;
  page.open('https://flipboard.com/signin', function (status) {
    if (status !== 'success') {
      return;
    }
    if (page.injectJs('node_modules/jquery/dist/jquery.min.js')) {
      setTimeout(done, 5000);
    }
  });
});

workflow.addStep('Log in', function (done) {
  workflow._page.evaluate(function(user, pass) {
    var $form = $('.login-form-content');
    var $fields = $form.find('.fields');
    $fields.find('input[type=text]').val(user);
    $fields.find('input[type=password]').val(pass);
    $form.find('button.button').click();
  }, systemArgs.user, systemArgs.pass);
  setTimeout(done, 5000);
});

workflow.addStep('Load magazines', function (done) {
  var page = workflow._page;
  page.open('https://flipboard.com/profile', function (status) {
    if (status !== 'success') {
      return;
    }
    if (page.injectJs('node_modules/jquery/dist/jquery.min.js')) {
      setTimeout(done, 5000);
    }
  });
});

workflow.addStep('Compile magazines', function () {
  var page = workflow._page;

  var mags = page.evaluate(function (magazineAccess) {
    var items = {};
    var name;
    var path;

    /**
     * Convert the magazine path to the edit path that will be used.
     * @param {string} path - The magazine path to convert.
     * @return {string}
     */
    function getMagPath(path) {
      return path.replace(/@([^\/]*).*-([^-]*)$/, 'editor/sid%252F$2%252F$1');
    }

    $('.magazine-tile').each(function (idx, mag) {
      name = $(mag).find('h3.truncated-text').html();
      path = $(mag).find('.section-link').attr('href');

      items[name] = {
        lastProcessed: magazineAccess[name],
        name: name,
        url: 'https://flipboard.com' + getMagPath(path)
      };
    });
    return items;
  }, magazineAccess);

  // Check if any are in mags and not magazineAccess
  forEach(difference(keys(mags), keys(magazineAccess)), function (val) {
    magazines.push(mags[val]);
  });

  var name;
  forEach(magazineAccessArray, function (val) {
    name = val.name;
    // Name isn't in the access list, so it must be new. Add to the front.
    if (!(name in mags)) {
      return;
    }
    magazines.push(mags[name]);
  });
});

workflow.addStep('Process magazines', function (done) {
  var _path;
  var idx = 0;
  var item;
  var processing = false;

  function callback(skipped) {
    skipped || util.updateProcessTime(item.name, moment().toISOString());
    processing = false;
    idx++;
  }

  var interval = setInterval(function () {
    if (processing) {
      return;
    }

    if (idx === magazines.length) {
      clearInterval(interval);
      return done();
    }

    item = magazines[idx];
    console.log(item.name + ':', unescape(item.url));

    if (!validateRequested(item.name)) {
      return callback(true);
    }
    processing = true;
    processMagazine({
      dest: systemArgs.output,
      done: callback,
      mag: item
    });
  }, 1000);
});

workflow.addStep('Donezo', function () {
  phantom.exit();
});

workflow.process();
<commit_msg>Don't include create magazine tile<commit_after>var createPage = require('./util').createPage;
var difference = require('mout/array/difference');
var forEach = require('mout/array/forEach');
var forOwn = require('mout/object/forOwn');
var keys = require('mout/object/keys');
var moment = require('moment');
var processMagazine = require('./magazine');
var Workflow = require('./workflow');
var sort = require('mout/array/sort');
var system = require('system');
var util = require('./util');

var magazineAccessArray = [];
var magazineAccess = util.getMagazineAccess();
var magazines = [];
var workflow = new Workflow(createPage());

forOwn(magazineAccess, function (val, key) {
  magazineAccessArray.push({
    name: key,
    lastProcessed: moment(val)
  });
});
magazineAccessArray = sort(magazineAccessArray, function (a, b) {
  return b.lastProcessed < a.lastProcessed;
});

var systemArgs = util.parseSystemArgs(system.args);
systemArgs.exclude = systemArgs.exclude ? systemArgs.exclude.split(',') : [];
systemArgs.mags = systemArgs.mags ? systemArgs.mags.split(',') : [];
systemArgs.output = systemArgs.output || 'images/';

if (!/\/$/.test(systemArgs.output)) {
  systemArgs.output += '/';
}

function validateRequested(name) {
  var lowerName = name.toLowerCase();
  var isExcluded = systemArgs.exclude.indexOf(lowerName) > -1;

  if (!systemArgs.mags.length && !isExcluded) {
    return true;
  }
  if (isExcluded) {
    return false;
  }
  return systemArgs.mags.indexOf(lowerName) > -1;
}

workflow.addStep('Load signin page', function (done) {
  var page = workflow._page;
  page.open('https://flipboard.com/signin', function (status) {
    if (status !== 'success') {
      return;
    }
    if (page.injectJs('node_modules/jquery/dist/jquery.min.js')) {
      setTimeout(done, 5000);
    }
  });
});

workflow.addStep('Log in', function (done) {
  workflow._page.evaluate(function(user, pass) {
    var $form = $('.login-form-content');
    var $fields = $form.find('.fields');
    $fields.find('input[type=text]').val(user);
    $fields.find('input[type=password]').val(pass);
    $form.find('button.button').click();
  }, systemArgs.user, systemArgs.pass);
  setTimeout(done, 5000);
});

workflow.addStep('Load magazines', function (done) {
  var page = workflow._page;
  page.open('https://flipboard.com/profile', function (status) {
    if (status !== 'success') {
      return;
    }
    if (page.injectJs('node_modules/jquery/dist/jquery.min.js')) {
      setTimeout(done, 5000);
    }
  });
});

workflow.addStep('Compile magazines', function () {
  var page = workflow._page;

  var mags = page.evaluate(function (magazineAccess) {
    var items = {};
    var name;
    var path;

    /**
     * Convert the magazine path to the edit path that will be used.
     * @param {string} path - The magazine path to convert.
     * @return {string}
     */
    function getMagPath(path) {
      return path.replace(/@([^\/]*).*-([^-]*)$/, 'editor/sid%252F$2%252F$1');
    }

    $('.magazine-tile').each(function (idx, mag) {
      name = $(mag).find('h3.truncated-text').html();
      path = $(mag).find('.section-link').attr('href');

      if (name === "Create Magazine") {
        return;
      }

      items[name] = {
        lastProcessed: magazineAccess[name],
        name: name,
        url: 'https://flipboard.com' + getMagPath(path)
      };
    });
    return items;
  }, magazineAccess);

  // Check if any are in mags and not magazineAccess
  forEach(difference(keys(mags), keys(magazineAccess)), function (val) {
    magazines.push(mags[val]);
  });

  var name;
  forEach(magazineAccessArray, function (val) {
    name = val.name;
    // Name isn't in the access list, so it must be new. Add to the front.
    if (!(name in mags)) {
      return;
    }
    magazines.push(mags[name]);
  });
});

workflow.addStep('Process magazines', function (done) {
  var _path;
  var idx = 0;
  var item;
  var processing = false;

  function callback(skipped) {
    skipped || util.updateProcessTime(item.name, moment().toISOString());
    processing = false;
    idx++;
  }

  var interval = setInterval(function () {
    if (processing) {
      return;
    }

    if (idx === magazines.length) {
      clearInterval(interval);
      return done();
    }

    item = magazines[idx];
    console.log(item.name + ':', unescape(item.url));

    if (!validateRequested(item.name)) {
      return callback(true);
    }
    processing = true;
    processMagazine({
      dest: systemArgs.output,
      done: callback,
      mag: item
    });
  }, 1000);
});

workflow.addStep('Donezo', function () {
  phantom.exit();
});

workflow.process();
<|endoftext|>


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

var DspGraph = {};

var internal = {};

internal.createConstant = function (audioCtx, audioTargetNode, graphAst) {
    audioTargetNode.set(graphAst.value, audioCtx);
    return {
        paramNames: []
    };
};

internal.createParam = function (audioCtx, audioTargetNode, graphAst) {
    var paramName = graphAst.name;
    var defaultValue = graphAst.defaultValue;
    audioTargetNode.set(defaultValue, audioCtx);
    var paramParams = {};
    paramParams.params = {}; // worst name evar
    paramParams.paramNames = [paramName];
    paramParams.params[paramName] = [
        function (newValue) {
            audioTargetNode.set(newValue, audioCtx);
        }
    ];
    return paramParams;
};

internal.createInput = function (audioCtx, audioTargetNode, graphAst) {
    var inputName = graphAst.name;

    var inputParams = {};
    inputParams.params = {};
    inputParams.paramNames = ['connect'];
    inputParams.params.connect = [
        function (sourceNode) {
            sourceNode.connect(audioTargetNode);
        }
    ];
    return inputParams;
};

internal.createOscillator = function (audioCtx, audioTargetNode, graphAst) {
    var oscillator = audioCtx.createOscillator();
    oscillator.start();

    var waveParam = DspGraph.evaluate(
        audioCtx,
        oscillator.getWaveParam(),
        graphAst.waveshape
    );

    var freqParam = DspGraph.evaluate(
        audioCtx,
        oscillator.frequency,
        graphAst.frequency
    );

    oscillator.connect(audioTargetNode);

    return util.mergeNodeParams([waveParam, freqParam]);
};

internal.createEnvelope = function (audioCtx, audioTargetNode, graphAst) {

    var envParams = {};
    envParams.attack = {
        value: 0,
        set: function (newValue, audioCtx) {
            envParams.attack.value = newValue;
        },
        get: function () {
            return envParams.attack.value;
        }
    };
    envParams.decay = {
        value: 0,
        set: function (newValue, audioCtx) {
            envParams.decay.value = newValue;
        },
        get: function () {
            return envParams.decay.value;
        }
    };

    var attackParams = DspGraph.evaluate(
        audioCtx,
        envParams.attack,
        graphAst.attack
    );

    var decayParams = DspGraph.evaluate(
        audioCtx,
        envParams.decay,
        graphAst.decay
    );

    var trigger = function () {
        var t = audioCtx.currentTime + envParams.attack.value;
        audioTargetNode.linearRampToValueAtTime(
            1.0, t
        );
    };
    var stop = function () {
        var t = audioCtx.currentTime + envParams.decay.value;
        audioTargetNode.linearRampToValueAtTime(
            0.0, t
        );
    };
    var triggerParams = {
        paramNames: ['trigger', 'stop'],
        params: {
            trigger: [trigger],
            stop: [stop]
        }
    };

    return util.mergeNodeParams([attackParams, decayParams, triggerParams]);
};

internal.createFilter = function (audioCtx, audioTargetNode, graphAst) {
    var filter = audioCtx.createBiquadFilter();

    var sourceParams = DspGraph.evaluate(
        audioCtx,
        filter,
        graphAst.source
    );

    var filterTypeParam = DspGraph.evaluate(
        audioCtx,
        filter.getFilterTypeParam(),
        graphAst.filterType
    );

    var freqParam = DspGraph.evaluate(
        audioCtx,
        filter.frequency,
        graphAst.frequency
    );

    var resonanceParam = DspGraph.evaluate(
        audioCtx,
        filter.Q,
        graphAst.resonance
    );

    filter.connect(audioTargetNode);

    return util.mergeNodeParams([sourceParams, filterTypeParam, freqParam, resonanceParam]);
};

internal.createAmp = function (audioCtx, audioTargetNode, graphAst) {
    var amp = audioCtx.createGain();
    amp.gain.value = 0;

    var sourceParams = DspGraph.evaluate(
        audioCtx,
        amp,
        graphAst.source
    );

    var volumeParams = DspGraph.evaluate(
        audioCtx,
        amp.gain,
        graphAst.volume
    );
    amp.connect(audioTargetNode);

    return util.mergeNodeParams([sourceParams, volumeParams]);
};

internal.createDelay = function (audioCtx, audioTargetNode, graphAst) {
    var feedbackAmp = audioCtx.createGain();
    var mainAmp = audioCtx.createGain();
    var delayNode = audioCtx.createDelay(graphAst);

    mainAmp.gain.value = 1;

    var sourceParams = DspGraph.evaluate(
        audioCtx,
        mainAmp,
        graphAst.source
    );

    var delayTimeParams = DspGraph.evaluate(
        audioCtx,
        delayNode.delayTime,
        graphAst.delayTime
    );

    var feedbackParams = DspGraph.evaluate(
        audioCtx,
        feedbackAmp.gain,
        graphAst.feedback
    );

    mainAmp.connect(delayNode);
    delayNode.connect(feedbackAmp);
    feedbackAmp.connect(mainAmp);

    mainAmp.connect(audioTargetNode);

    return util.mergeNodeParams([sourceParams, delayTimeParams, feedbackParams]);
};

DspGraph.evaluate = function(audioCtx, audioTargetNode, graphAst) {
    var result;
    switch (graphAst.type) {
        case 'CONSTANT':
            result = internal.createConstant(audioCtx, audioTargetNode, graphAst);
            break;
        case 'PARAM':
            result = internal.createParam(audioCtx, audioTargetNode, graphAst);
            break;
        case 'ARENVELOPE':
            result = internal.createEnvelope(audioCtx, audioTargetNode, graphAst);
            break;
        case 'OSCILLATOR':
            result = internal.createOscillator(audioCtx, audioTargetNode, graphAst);
            break;
        case 'FILTER':
            result = internal.createFilter(audioCtx, audioTargetNode, graphAst);
            break;
        case 'AMP':
            result = internal.createAmp(audioCtx, audioTargetNode, graphAst);
            break;
        default:
            throw new Error("Unknown DSP graph type: " + graphAst.type);
    }
    return result;
};

module.exports = DspGraph;

<commit_msg>Making sure delay gets created<commit_after>
var util = require('./util');

var DspGraph = {};

var internal = {};

internal.createConstant = function (audioCtx, audioTargetNode, graphAst) {
    audioTargetNode.set(graphAst.value, audioCtx);
    return {
        paramNames: []
    };
};

internal.createParam = function (audioCtx, audioTargetNode, graphAst) {
    var paramName = graphAst.name;
    var defaultValue = graphAst.defaultValue;
    audioTargetNode.set(defaultValue, audioCtx);
    var paramParams = {};
    paramParams.params = {}; // worst name evar
    paramParams.paramNames = [paramName];
    paramParams.params[paramName] = [
        function (newValue) {
            audioTargetNode.set(newValue, audioCtx);
        }
    ];
    return paramParams;
};

internal.createInput = function (audioCtx, audioTargetNode, graphAst) {
    var inputName = graphAst.name;

    var inputParams = {};
    inputParams.params = {};
    inputParams.paramNames = ['connect'];
    inputParams.params.connect = [
        function (sourceNode) {
            sourceNode.connect(audioTargetNode);
        }
    ];
    return inputParams;
};

internal.createOscillator = function (audioCtx, audioTargetNode, graphAst) {
    var oscillator = audioCtx.createOscillator();
    oscillator.start();

    var waveParam = DspGraph.evaluate(
        audioCtx,
        oscillator.getWaveParam(),
        graphAst.waveshape
    );

    var freqParam = DspGraph.evaluate(
        audioCtx,
        oscillator.frequency,
        graphAst.frequency
    );

    oscillator.connect(audioTargetNode);

    return util.mergeNodeParams([waveParam, freqParam]);
};

internal.createEnvelope = function (audioCtx, audioTargetNode, graphAst) {

    var envParams = {};
    envParams.attack = {
        value: 0,
        set: function (newValue, audioCtx) {
            envParams.attack.value = newValue;
        },
        get: function () {
            return envParams.attack.value;
        }
    };
    envParams.decay = {
        value: 0,
        set: function (newValue, audioCtx) {
            envParams.decay.value = newValue;
        },
        get: function () {
            return envParams.decay.value;
        }
    };

    var attackParams = DspGraph.evaluate(
        audioCtx,
        envParams.attack,
        graphAst.attack
    );

    var decayParams = DspGraph.evaluate(
        audioCtx,
        envParams.decay,
        graphAst.decay
    );

    var trigger = function () {
        var t = audioCtx.currentTime + envParams.attack.value;
        audioTargetNode.linearRampToValueAtTime(
            1.0, t
        );
    };
    var stop = function () {
        var t = audioCtx.currentTime + envParams.decay.value;
        audioTargetNode.linearRampToValueAtTime(
            0.0, t
        );
    };
    var triggerParams = {
        paramNames: ['trigger', 'stop'],
        params: {
            trigger: [trigger],
            stop: [stop]
        }
    };

    return util.mergeNodeParams([attackParams, decayParams, triggerParams]);
};

internal.createFilter = function (audioCtx, audioTargetNode, graphAst) {
    var filter = audioCtx.createBiquadFilter();

    var sourceParams = DspGraph.evaluate(
        audioCtx,
        filter,
        graphAst.source
    );

    var filterTypeParam = DspGraph.evaluate(
        audioCtx,
        filter.getFilterTypeParam(),
        graphAst.filterType
    );

    var freqParam = DspGraph.evaluate(
        audioCtx,
        filter.frequency,
        graphAst.frequency
    );

    var resonanceParam = DspGraph.evaluate(
        audioCtx,
        filter.Q,
        graphAst.resonance
    );

    filter.connect(audioTargetNode);

    return util.mergeNodeParams([sourceParams, filterTypeParam, freqParam, resonanceParam]);
};

internal.createAmp = function (audioCtx, audioTargetNode, graphAst) {
    var amp = audioCtx.createGain();
    amp.gain.value = 0;

    var sourceParams = DspGraph.evaluate(
        audioCtx,
        amp,
        graphAst.source
    );

    var volumeParams = DspGraph.evaluate(
        audioCtx,
        amp.gain,
        graphAst.volume
    );
    amp.connect(audioTargetNode);

    return util.mergeNodeParams([sourceParams, volumeParams]);
};

internal.createDelay = function (audioCtx, audioTargetNode, graphAst) {
    var feedbackAmp = audioCtx.createGain();
    var mainAmp = audioCtx.createGain();
    var delayNode = audioCtx.createDelay(graphAst);

    mainAmp.gain.value = 1;

    var sourceParams = DspGraph.evaluate(
        audioCtx,
        mainAmp,
        graphAst.source
    );

    var delayTimeParams = DspGraph.evaluate(
        audioCtx,
        delayNode.delayTime,
        graphAst.delayTime
    );

    var feedbackParams = DspGraph.evaluate(
        audioCtx,
        feedbackAmp.gain,
        graphAst.feedback
    );

    mainAmp.connect(delayNode);
    delayNode.connect(feedbackAmp);
    feedbackAmp.connect(mainAmp);

    mainAmp.connect(audioTargetNode);

    return util.mergeNodeParams([sourceParams, delayTimeParams, feedbackParams]);
};

DspGraph.evaluate = function(audioCtx, audioTargetNode, graphAst) {
    var result;
    switch (graphAst.type) {
        case 'CONSTANT':
            result = internal.createConstant(audioCtx, audioTargetNode, graphAst);
            break;
        case 'PARAM':
            result = internal.createParam(audioCtx, audioTargetNode, graphAst);
            break;
        case 'ARENVELOPE':
            result = internal.createEnvelope(audioCtx, audioTargetNode, graphAst);
            break;
        case 'OSCILLATOR':
            result = internal.createOscillator(audioCtx, audioTargetNode, graphAst);
            break;
        case 'FILTER':
            result = internal.createFilter(audioCtx, audioTargetNode, graphAst);
            break;
        case 'AMP':
            result = internal.createAmp(audioCtx, audioTargetNode, graphAst);
            break;
        case 'DELAY':
            result = internal.createDelay(audioCtx, audioTargetNode, graphAst);
            break;
        default:
            throw new Error("Unknown DSP graph type: " + graphAst.type);
    }
    return result;
};

module.exports = DspGraph;

<|endoftext|>


<commit_before>var marked = require('marked')
  , converter = module.exports = {}
  , element = document.createElement('div')
  ;

marked.setOptions({
  gfm: true,
  tables: true,
  breaks: false,

  // Without this set to true, converting something like
  //
*

*
 will become

  pedantic: true,

  sanitize: false,
  smartLists: true,
  langPrefix: ''
});

converter.convertMarkdown = function (content, links, inline) {
  element.innerHTML = convertMarkdown(content, links || {}, inline);
  element.innerHTML = element.innerHTML.replace(/
\s*<\/p>/g, '');
  return element.innerHTML.replace(/\n\r?$/, '');
};

function convertMarkdown (content, links, insideContentClass) {
  var i, tag, markdown = '', html;

  for (i = 0; i < content.length; ++i) {
    if (typeof content[i] === 'string') {
      markdown += content[i];
    }
    else {
      tag = content[i].block ? 'div' : 'span';
      markdown += '<' + tag + ' class="' + content[i].class + '">';
      markdown += convertMarkdown(content[i].content, links, true);
      markdown += '</' + tag + '>';
    }
  }

  var tokens = marked.Lexer.lex(markdown.replace(/^\s+/, ''));
  tokens.links = links;
  html = marked.Parser.parse(tokens);

  if (insideContentClass) {
    element.innerHTML = html;
    if (element.children.length === 1 && element.children[0].tagName === 'P') {
      html = element.children[0].innerHTML;
    }
  }

  return html;
}
<commit_msg>pass block flag down into child markdown renderer properly<commit_after>var marked = require('marked')
  , converter = module.exports = {}
  , element = document.createElement('div')
  ;

marked.setOptions({
  gfm: true,
  tables: true,
  breaks: false,

  // Without this set to true, converting something like
  //
*

*
 will become

  pedantic: true,

  sanitize: false,
  smartLists: true,
  langPrefix: ''
});

converter.convertMarkdown = function (content, links, inline) {
  element.innerHTML = convertMarkdown(content, links || {}, inline);
  element.innerHTML = element.innerHTML.replace(/
\s*<\/p>/g, '');
  return element.innerHTML.replace(/\n\r?$/, '');
};

function convertMarkdown (content, links, insideContentClass) {
  var i, tag, markdown = '', html;

  for (i = 0; i < content.length; ++i) {
    if (typeof content[i] === 'string') {
      markdown += content[i];
    }
    else {
      tag = content[i].block ? 'div' : 'span';
      markdown += '<' + tag + ' class="' + content[i].class + '">';
      markdown += convertMarkdown(content[i].content, links, !content[i].block);
      markdown += '</' + tag + '>';
    }
  }

  var tokens = marked.Lexer.lex(markdown.replace(/^\s+/, ''));
  tokens.links = links;
  html = marked.Parser.parse(tokens);

  if (insideContentClass) {
    element.innerHTML = html;
    if (element.children.length === 1 && element.children[0].tagName === 'P') {
      html = element.children[0].innerHTML;
    }
  }

  return html;
}
<|endoftext|>


<commit_before>var _ = require('lodash');
var util = require('util');
var BaseReporter = require('./base');
var CompositeError = require('../error/composite');

module.exports = ConsoleReporter;

function ConsoleReporter() {
    BaseReporter.call(this);
    this.matrix = {};
    this.status = null;
    this.browserStatus = {};
    // start timer, will be reset if grid was not started yet.
    this.start = new Date();
    this.count = 0;
}
util.inherits(ConsoleReporter, BaseReporter);

ConsoleReporter.prototype.onBefore = function (grid) {
    this.start = new Date();
    var browsers = grid.config.browsers;
    console.log('Will execute tests on following configurations:\n');
    browsers.forEach(function (b) {
        console.log('  -> %s', browserId(b));
    });
};

ConsoleReporter.prototype.onBeforeBrowser = function (browserRunner, browserCfg) {
    this.browserStatus[browserId(browserCfg)] = null;
    this.matrix[browserId(browserCfg)] = {};
};
ConsoleReporter.prototype.onBeforeScenario = function (scenarioRunner, browserCfg) {
    var matrix = this.matrix[browserId(browserCfg)];
    if (typeof(matrix[scenarioRunner.getName()]) !== "undefined") {
        console.log(color('bright yellow', 'This test and browser combination has already been lanched.'));
    }
    matrix[scenarioRunner.getName()] = null;
};
ConsoleReporter.prototype.onAfterScenario = function (err, scenarioRunner, browserCfg) {
    this.count++;
    this.matrix[browserId(browserCfg)][scenarioRunner.getName()] = err || false;
    if (err) {
        this.status = false;
        console.log(color('fail', '  %s on %s'), scenarioRunner.getName(), browserCfg.browserName, color('bright fail', 'FAIL'));
        if (err instanceof CompositeError) {
            console.log(err.toString().replace(/^/gm, '    > '));
        } else if (err.inspect) {
            console.log('Webdriver error:'.replace(/^/gm, '    > '));

            if (err.data && err.data.value && err.data.value.message) {
                console.log(err.data.value.message.replace(/^/gm, '    > '));
            } else if (err.cause && err.cause.value && err.cause.value.message) {
                console.log(err.cause.value.message.replace(/^/gm, '    > '));
            } else {
                console.log(err.inspect().replace(/^/gm, '    > '));
            }
        } else if (err.stack) {
            console.log(err.stack.replace(/^/gm, '    > '));
        } else {
            console.log(util.inspect(err).replace(/^/gm, '    > '));
        }
        return ;
    }
    console.log(color('pass', '  %s on %s'), scenarioRunner.getName(), browserCfg.browserName, color('bright pass', 'PASS'));
};
ConsoleReporter.prototype.onAfterBrowser = function (err, browserRunner, browserCfg) {
    this.browserStatus[browserId(browserCfg)] = err || false;
    if (err) {this.status = false;}
};
ConsoleReporter.prototype.onAfter = function (grid) {
    console.log("\n\n  =================================\n");
    var end = new Date();
    var elapsed = (end.getTime() - this.start.getTime()) / 1000;
    var resultStr = "  %s jobs ran in %s s\n";
    if (this.status || this.status === null) {
        return console.log(color('bright pass', resultStr), this.count, elapsed);
    }

    console.log(color('bright fail', resultStr), this.count, elapsed);

    // there were errors
    var browsers = this.browserStatus;
    _.each(this.matrix, function (tests, browser) {
        if (!browsers[browser]) {
            // there were no error
            console.log('   ', browser, '-', color('bright pass','OK'));
            return;
        }
        console.log(color('fail', '    %s'), browser);
        _.each(tests, function (test, id) {
            if (test) {
                console.log(color('bright fail', '       %s %s - failed'), symbols.err, id);
            }
        });
    });
};

function browserId(browser) {
    browser = _.defaults(browser, {
        browserName: 'any browser',
        platform: 'any platform',
        version: 'any version'
    });

    return util.format('%s (%s) on %s', browser.browserName, browser.version, browser.platform);
}

// what comes next is taken from mocha reporters
// https://github.com/visionmedia/mocha/blob/master/lib/reporters/base.js

var tty = require('tty');
/**
 * Check if both stdio streams are associated with a tty.
 */

var isatty = tty.isatty(1) && tty.isatty(2);

/**
 * Enable coloring by default.
 */

var useColors = isatty;

/**
 * Default color map.
 */

var colors = {
    'pass': 90
  , 'fail': 31
  , 'bright pass': 92
  , 'bright fail': 91
  , 'bright yellow': 93
  , 'pending': 36
  , 'suite': 0
  , 'error title': 0
  , 'error message': 31
  , 'error stack': 90
  , 'checkmark': 32
  , 'fast': 90
  , 'medium': 33
  , 'slow': 31
  , 'green': 32
  , 'light': 90
  , 'diff gutter': 90
  , 'diff added': 42
  , 'diff removed': 41
};

/**
 * Default symbol map.
 */

var symbols = {
  ok: '✓',
  err: '✖',
  dot: '․'
};

// With node.js on Windows: use symbols available in terminal default fonts
if ('win32' == process.platform) {
  symbols.ok = '\u221A';
  symbols.err = '\u00D7';
  symbols.dot = '.';
}

/**
 * Color `str` with the given `type`,
 * allowing colors to be disabled,
 * as well as user-defined color
 * schemes.
 *
 * @param {String} type
 * @param {String} str
 * @return {String}
 * @api private
 */

var color = function(type, str) {
  if (!useColors) return str;
  return '\u001b[' + colors[type] + 'm' + str + '\u001b[0m';
};
<commit_msg>Better step reporting.<commit_after>var _ = require('lodash');
var util = require('util');
var BaseReporter = require('./base');
var CompositeError = require('../error/composite');

module.exports = ConsoleReporter;

function ConsoleReporter() {
    BaseReporter.call(this);
    this.matrix = {};
    this.status = null;
    this.browserStatus = {};
    // start timer, will be reset if grid was not started yet.
    this.start = new Date();
    this.count = 0;
}
util.inherits(ConsoleReporter, BaseReporter);

ConsoleReporter.prototype.onBefore = function (grid) {
    this.start = new Date();
    var browsers = grid.config.browsers;
    console.log('Will execute tests on following configurations:\n');
    browsers.forEach(function (b) {
        console.log('  -> %s', browserId(b));
    });
};

ConsoleReporter.prototype.onBeforeBrowser = function (browserRunner, browserCfg) {
    this.browserStatus[browserId(browserCfg)] = null;
    this.matrix[browserId(browserCfg)] = {};
};
ConsoleReporter.prototype.onBeforeScenario = function (scenarioRunner, browserCfg) {
    var matrix = this.matrix[browserId(browserCfg)];
    if (typeof(matrix[scenarioRunner.getName()]) !== "undefined") {
        console.log(color('bright yellow', 'This test and browser combination has already been lanched.'));
    }
    matrix[scenarioRunner.getName()] = null;
};
ConsoleReporter.prototype.onAfterScenario = function (err, scenarioRunner, browserCfg) {
    this.count++;
    this.matrix[browserId(browserCfg)][scenarioRunner.getName()] = err || false;
    if (err) {
        this.status = false;
        console.log(color('fail', '  %s on %s'), scenarioRunner.getName(), browserId(browserCfg), color('bright fail', 'FAIL'));
        if (err instanceof CompositeError) {
            console.log(err.toString().replace(/^/gm, '    > '));
        } else if (err.inspect) {
            console.log('Webdriver error:'.replace(/^/gm, '    > '));

            if (err.data && err.data.value && err.data.value.message) {
                console.log(err.data.value.message.replace(/^/gm, '    > '));
            } else if (err.cause && err.cause.value && err.cause.value.message) {
                console.log(err.cause.value.message.replace(/^/gm, '    > '));
            } else {
                console.log(err.inspect().replace(/^/gm, '    > '));
            }
        } else if (err.stack) {
            console.log(err.stack.replace(/^/gm, '    > '));
        } else {
            console.log(util.inspect(err).replace(/^/gm, '    > '));
        }
        return ;
    }
    console.log(color('pass', '  %s on %s'), scenarioRunner.getName(), browserId(browserCfg), color('bright pass', 'PASS'));
};
ConsoleReporter.prototype.onAfterBrowser = function (err, browserRunner, browserCfg) {
    this.browserStatus[browserId(browserCfg)] = err || false;
    if (err) {this.status = false;}
};
ConsoleReporter.prototype.onAfter = function (grid) {
    console.log("\n\n  =================================\n");
    var end = new Date();
    var elapsed = (end.getTime() - this.start.getTime()) / 1000;
    var resultStr = "  %s jobs ran in %s s\n";
    if (this.status || this.status === null) {
        return console.log(color('bright pass', resultStr), this.count, elapsed);
    }

    console.log(color('bright fail', resultStr), this.count, elapsed);

    // there were errors
    var browsers = this.browserStatus;
    _.each(this.matrix, function (tests, browser) {
        if (!browsers[browser]) {
            // there were no error
            console.log('   ', browser, '-', color('bright pass','OK'));
            return;
        }
        console.log(color('fail', '    %s'), browser);
        _.each(tests, function (test, id) {
            if (test) {
                console.log(color('bright fail', '       %s %s - failed'), symbols.err, id);
            }
        });
    });
};

function browserId(browser) {
    browser = _.defaults(browser, {
        browserName: 'any browser',
        platform: 'any platform',
        version: 'any version'
    });

    return util.format('%s (%s) on %s', browser.browserName, browser.version, browser.platform);
}

// what comes next is taken from mocha reporters
// https://github.com/visionmedia/mocha/blob/master/lib/reporters/base.js

var tty = require('tty');
/**
 * Check if both stdio streams are associated with a tty.
 */

var isatty = tty.isatty(1) && tty.isatty(2);

/**
 * Enable coloring by default.
 */

var useColors = isatty;

/**
 * Default color map.
 */

var colors = {
    'pass': 90
  , 'fail': 31
  , 'bright pass': 92
  , 'bright fail': 91
  , 'bright yellow': 93
  , 'pending': 36
  , 'suite': 0
  , 'error title': 0
  , 'error message': 31
  , 'error stack': 90
  , 'checkmark': 32
  , 'fast': 90
  , 'medium': 33
  , 'slow': 31
  , 'green': 32
  , 'light': 90
  , 'diff gutter': 90
  , 'diff added': 42
  , 'diff removed': 41
};

/**
 * Default symbol map.
 */

var symbols = {
  ok: '✓',
  err: '✖',
  dot: '․'
};

// With node.js on Windows: use symbols available in terminal default fonts
if ('win32' == process.platform) {
  symbols.ok = '\u221A';
  symbols.err = '\u00D7';
  symbols.dot = '.';
}

/**
 * Color `str` with the given `type`,
 * allowing colors to be disabled,
 * as well as user-defined color
 * schemes.
 *
 * @param {String} type
 * @param {String} str
 * @return {String}
 * @api private
 */

var color = function(type, str) {
  if (!useColors) return str;
  return '\u001b[' + colors[type] + 'm' + str + '\u001b[0m';
};
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import GridLayout from '../components/GridLayout';
import Title from '../components/Title';
import Loader from '../components/Loader';

const endpoint = pageNumber =>
                    `http://gamingdb.info/api/game?page=${pageNumber}`

class GamesPage extends Component {
    constructor(props) {
        super(props);
        this.state = {
            page: 1,
            games:[],
            loading: true
        };
    };

    fetchData() {
        fetch(endpoint(this.state.page),{
            method: 'GET'
        }).then(response => response.json())
        .then(response => {
            for (var i = 0; i < response.objects.length; i++) {
                let obj = response.objects[i];
                let details = this._buildDetails(obj);
                let item = {
                    title: obj.title,
                    img: obj.image_url,
                    url: "/games/" + obj.game_id,
                    details: details
                }
                var gamesArray = this.state.games.slice();
                gamesArray.push(item);
                this.setState({ games: gamesArray });
            }
            this.setState({
                loading: false
            });
        });
    };

    componentDidMount() {
        this.fetchData();
    };

    render() {
        return (

                {this.state.loading && <Loader/>}
                {!this.state.loading &&

                        <Title title="Games"/>
                        <GridLayout items={this.state.games}/>

                }

        )
    }

    changePage(pageNumber) {
        this.setState({
            page: pageNumber,
            games: [],
            loading: true
        });
        this.fetchData();
    };

    _buildDetails(obj) {
        let details = []
        if(obj.release_date)
            details.push({ title: "Released:", content:obj.release_date});
        if(obj.rating)
            details.push({title: "Rating:", content: obj.rating.toFixed(0) + "/100"});
        if(obj.genres.length > 0)
            details.push({title: "Genre:", content:obj.genres[0].name});

        return details;
    }
}

export default GamesPage;
<commit_msg>working on pagination<commit_after>import React, { Component } from 'react';
import GridLayout from '../components/GridLayout';
import Title from '../components/Title';
import Loader from '../components/Loader';

let endpoint = (pageNumber) =>
                    `http://gamingdb.info/api/game?page=${pageNumber}`

class GamesPage extends Component {
    constructor(props) {
        super(props);
        this.state = {
            page: 10,
            games:[],
            loading: true
        };
    };

    fetchData() {
        fetch(endpoint(this.state.page),{
            method: 'GET'
        }).then(response => response.json())
        .then(response => {
            for (var i = 0; i < response.objects.length; i++) {
                let obj = response.objects[i];
                let details = this._buildDetails(obj);
                let item = {
                    title: obj.title,
                    img: obj.image_url,
                    url: "/games/" + obj.game_id,
                    details: details
                }
                var gamesArray = this.state.games.slice();
                gamesArray.push(item);
                this.setState({ games: gamesArray });
            }
            this.setState({
                loading: false
            });
        });
    };

    componentDidMount() {
        this.fetchData();
    };

    render() {
        return (

                {this.state.loading && <Loader/>}
                {!this.state.loading &&

                        <Title title="Games"/>
                        <GridLayout items={this.state.games}/>
                        <button onClick={this.decPage}>Previous Page</button>
                        <button onClick={this.incPage}>Next Page</button>

                }

        )
    }

    incPage = () => {
        this.changePage(this.state.page + 1);
    }

    decPage = () => {
        this.changePage(this.state.page - 1);
    }

    changePage = (page) => {
        this.setState({
            page: page,
            games: [],
            loading: true
        }, () => { this.fetchData() });
    };

    _buildDetails(obj) {
        let details = []
        if(obj.release_date)
            details.push({ title: "Released:", content:obj.release_date});
        if(obj.rating)
            details.push({title: "Rating:", content: obj.rating.toFixed(0) + "/100"});
        if(obj.genres.length > 0)
            details.push({title: "Genre:", content:obj.genres[0].name});

        return details;
    }
}

export default GamesPage;
<|endoftext|>


<commit_before>import {
	elementOpen as coreElementOpen,
	elementClose as coreElementClose,
	text as coreText,
	getNextNode
} from './core';
import { updateAttribute } from './attributes';
import {
	nextComponentStart,
	nextComponentEnd,
	getData
} from "./component";
import {
	assertNotInAttributes,
	assertNotInSkip,
	assertInAttributes,
	assertCloseMatchesOpenTag
} from './assertions';

const argsBuilder = [];

const elementOpen = function(tag, attributes, key, statics)
{
	if(process.env.NODE_ENV !== "production") {
		assertNotInAttributes("elementOpen");
		assertNotInSkip("elementOpen");
	}

	const node = coreElementOpen(tag, key)
	const data = getData(node)

	if(statics && !data.staticsApplied)
	{
		for(let key in statics) {
			updateAttribute(node, key, statics[key], true)
		}

		data.staticsApplied = true
	}

	let renderText = (attributes && attributes.$value) ? true : false

	if(data.parentAttributes)
	{
		if(attributes)
		{
			renderText = (attributes.$value !== undefined | attributes.bind !== undefined)
			attributes = Object.assign(data.parentAttributes, attributes)
		}
		else {
			attributes = data.parentAttributes
		}
	}

	const prevAttributes = data.attributes

	if(attributes)
	{
		// Remove attributes
		for(let key in prevAttributes) {
			if(attributes[key] === undefined) {
				updateAttribute(node, key, undefined)
			}
		}

		// Update attributes
		for(let key in attributes)
		{
			const value = attributes[key]

			if(prevAttributes[key] === undefined ||
			   prevAttributes[key] !== value ||
			   (key[0] === "$" && data.$[key] !== value) ||
			   key === "bind")
			{
				updateAttribute(node, key, value)
			}
		}
	}
	else
	{
		// Remove attributes
		for(let key in prevAttributes) {
			updateAttribute(node, key, undefined)
		}

		data.attributes = {}
	}

	if(data.render)
	{
		if(renderText) {
			text(data.$value)
		}
	}
	else
	{
		if(data.$value !== null) {
			text(data.$value)
		}
	}

	return node
};

const elementClose = function(tag)
{
	if(process.env.NODE_ENV !== "production") {
		assertNotInAttributes("elementClose")
	}

	const node = coreElementClose()

	if(process.env.NODE_ENV !== "production") {
		assertCloseMatchesOpenTag(getData(node).nodeName, tag)
	}

	return node
};

const elementVoid = function(tag, attributes, key, statics) {
	elementOpen(tag, attributes, key, statics)
	return elementClose(tag)
}

const componentVoid = function(component, attributes, key)
{
	if(!component) {
		console.warn("Invalid component object passed")
		return
	}

	const node = getNextNode()
	let data = node ? node.metaData : null

	if(!data || data.constructor !== component)
	{
		data = nextComponentStart(component)
		data.key = key

		assignAttributes(data, attributes)

		if(data.setup) {
			data.setup()
		}
	}
	else {
		assignAttributes(data, attributes)
	}

	data.render()
	nextComponentEnd()

	return data
}

const assignAttributes = function(data, attributes)
{
	if(attributes)
	{
		data.parentAttributes = attributes

		for(let key in attributes)
		{
			if(key[0] === "$")
			{
				const state = key.slice(1)

				if(data.$[state] === undefined) {
					console.log(`State '${state}' not defined for component:`, component)
					return
				}

				data[key] = attributes[key]
			}
		}

		if(attributes.bind) {
			data.bind = attributes.bind
			data.attributes.bind = attributes.bind
		}
	}
}

const text = function(value, formatFunc)
{
	if(process.env.NODE_ENV !== "production") {
		assertNotInAttributes("text")
		assertNotInSkip("text")
	}

	const node = coreText()
	const data = getData(node)

	if(data.$.value !== value)
	{
		data.$.value = value

		if(formatFunc) {
			node.data = formatFunc(value)
		}
		else {
			node.data = value
		}
	}
}

export {
	elementOpen,
	elementClose,
	elementVoid,
	componentVoid
}
<commit_msg>Setup binding before other attributes<commit_after>import {
	elementOpen as coreElementOpen,
	elementClose as coreElementClose,
	text as coreText,
	getNextNode
} from './core';
import { updateAttribute } from './attributes';
import {
	nextComponentStart,
	nextComponentEnd,
	getData
} from "./component";
import {
	assertNotInAttributes,
	assertNotInSkip,
	assertInAttributes,
	assertCloseMatchesOpenTag
} from './assertions';

const argsBuilder = [];

const elementOpen = function(tag, attributes, key, statics)
{
	if(process.env.NODE_ENV !== "production") {
		assertNotInAttributes("elementOpen");
		assertNotInSkip("elementOpen");
	}

	const node = coreElementOpen(tag, key)
	const data = getData(node)

	if(statics && !data.staticsApplied)
	{
		for(let key in statics) {
			updateAttribute(node, key, statics[key], true)
		}

		data.staticsApplied = true
	}

	let renderText = (attributes && attributes.$value) ? true : false

	if(data.parentAttributes)
	{
		if(attributes)
		{
			renderText = (attributes.$value !== undefined | attributes.bind !== undefined)
			attributes = Object.assign(data.parentAttributes, attributes)
		}
		else {
			attributes = data.parentAttributes
		}
	}

	const prevAttributes = data.attributes

	if(attributes)
	{
		// Remove attributes
		for(let key in prevAttributes) {
			if(attributes[key] === undefined) {
				updateAttribute(node, key, undefined)
			}
		}

		// Update attributes
		for(let key in attributes)
		{
			const value = attributes[key]

			if(prevAttributes[key] === undefined ||
			   prevAttributes[key] !== value ||
			   (key[0] === "$" && data.$[key] !== value) ||
			   key === "bind")
			{
				updateAttribute(node, key, value)
			}
		}
	}
	else
	{
		// Remove attributes
		for(let key in prevAttributes) {
			updateAttribute(node, key, undefined)
		}

		data.attributes = {}
	}

	if(data.render)
	{
		if(renderText) {
			text(data.$value)
		}
	}
	else
	{
		if(data.$value !== null) {
			text(data.$value)
		}
	}

	return node
};

const elementClose = function(tag)
{
	if(process.env.NODE_ENV !== "production") {
		assertNotInAttributes("elementClose")
	}

	const node = coreElementClose()

	if(process.env.NODE_ENV !== "production") {
		assertCloseMatchesOpenTag(getData(node).nodeName, tag)
	}

	return node
};

const elementVoid = function(tag, attributes, key, statics) {
	elementOpen(tag, attributes, key, statics)
	return elementClose(tag)
}

const componentVoid = function(component, attributes, key)
{
	if(!component) {
		console.warn("Invalid component object passed")
		return
	}

	const node = getNextNode()
	let data = node ? node.metaData : null

	if(!data || data.constructor !== component)
	{
		data = nextComponentStart(component)
		data.key = key

		assignAttributes(data, attributes)

		if(data.setup) {
			data.setup()
		}
	}
	else {
		assignAttributes(data, attributes)
	}

	data.render()
	nextComponentEnd()

	return data
}

const assignAttributes = function(data, attributes)
{
	if(attributes)
	{
		data.parentAttributes = attributes

		if(attributes.bind) {
			data.bind = attributes.bind
			data.attributes.bind = attributes.bind
		}

		for(let key in attributes)
		{
			if(key[0] === "$")
			{
				const state = key.slice(1)

				if(data.$[state] === undefined) {
					console.log(`State '${state}' not defined for component:`, data)
					return
				}

				data[key] = attributes[key]
			}
		}
	}
}

const text = function(value, formatFunc)
{
	if(process.env.NODE_ENV !== "production") {
		assertNotInAttributes("text")
		assertNotInSkip("text")
	}

	const node = coreText()
	const data = getData(node)

	if(data.$.value !== value)
	{
		data.$.value = value

		if(formatFunc) {
			node.data = formatFunc(value)
		}
		else {
			node.data = value
		}
	}
}

export {
	elementOpen,
	elementClose,
	elementVoid,
	componentVoid
}
<|endoftext|>


<commit_before>(function () {

var D = Flotr.DOM;

Flotr.addPlugin('legend', {
  options: {
    show: true,            // => setting to true will show the legend, hide otherwise
    noColumns: 1,          // => number of colums in legend table // @todo: doesn't work for HtmlText = false
    labelFormatter: function(v){return v;}, // => fn: string -> string
    labelBoxBorderColor: '#CCCCCC', // => border color for the little label boxes
    labelBoxWidth: 14,
    labelBoxHeight: 10,
    labelBoxMargin: 5,
    labelBoxOpacity: 0.4,
    container: null,       // => container (as jQuery object) to put legend in, null means default on top of graph
    position: 'nw',        // => position of default legend container within plot
    margin: 5,             // => distance from grid edge to default legend container within plot
    backgroundColor: null, // => null means auto-detect
    backgroundOpacity: 0.85// => set to 0 to avoid background, set to 1 for a solid background
  },
  callbacks: {
    'flotr:afterinit': function() {
      this.legend.insertLegend();
    }
  },
  /**
   * Adds a legend div to the canvas container or draws it on the canvas.
   */
  insertLegend: function(){

    if(!this.options.legend.show)
      return;

    var series = this.series,
      plotOffset = this.plotOffset,
      options = this.options,
      legend = options.legend,
      fragments = [],
      rowStarted = false,
      ctx = this.ctx,
      noLegendItems = _.filter(series, function(s) {return (s.label && !s.hide);}).length,
      p = legend.position,
      m = legend.margin,
      i, label, color;

    if (noLegendItems) {
      if (!options.HtmlText && this.textEnabled && !legend.container) {
        var style = {
          size: options.fontSize*1.1,
          color: options.grid.color
        };

        var lbw = legend.labelBoxWidth,
            lbh = legend.labelBoxHeight,
            lbm = legend.labelBoxMargin,
            offsetX = plotOffset.left + m,
            offsetY = plotOffset.top + m;

        // We calculate the labels' max width
        var labelMaxWidth = 0;
        for(i = series.length - 1; i > -1; --i){
          if(!series[i].label || series[i].hide) continue;
          label = legend.labelFormatter(series[i].label);
          labelMaxWidth = Math.max(labelMaxWidth, Flotr.measureText(ctx, label, style).width);
        }

        var legendWidth  = Math.round(lbw + lbm*3 + labelMaxWidth),
            legendHeight = Math.round(noLegendItems*(lbm+lbh) + lbm);

        if(p.charAt(0) == 's') offsetY = plotOffset.top + this.plotHeight - (m + legendHeight);
        if(p.charAt(1) == 'e') offsetX = plotOffset.left + this.plotWidth - (m + legendWidth);

        // Legend box
        color = this.processColor(legend.backgroundColor || 'rgb(240,240,240)', {opacity: legend.backgroundOpacity || 0.1});

        ctx.fillStyle = color;
        ctx.fillRect(offsetX, offsetY, legendWidth, legendHeight);
        ctx.strokeStyle = legend.labelBoxBorderColor;
        ctx.strokeRect(Flotr.toPixel(offsetX), Flotr.toPixel(offsetY), legendWidth, legendHeight);

        // Legend labels
        var x = offsetX + lbm;
        var y = offsetY + lbm;
        for(i = 0; i < series.length; i++){
          if(!series[i].label || series[i].hide) continue;
          label = legend.labelFormatter(series[i].label);

          ctx.fillStyle = series[i].color;
          ctx.fillRect(x, y, lbw-1, lbh-1);

          ctx.strokeStyle = legend.labelBoxBorderColor;
          ctx.lineWidth = 1;
          ctx.strokeRect(Math.ceil(x)-1.5, Math.ceil(y)-1.5, lbw+2, lbh+2);

          // Legend text
          Flotr.drawText(ctx, label, x + lbw + lbm, y + (lbh + style.size - ctx.fontDescent(style))/2, style);

          y += lbh + lbm;
        }
      }
      else {
        for(i = 0; i < series.length; ++i){
          if(!series[i].label || series[i].hide) continue;

          if(i % legend.noColumns === 0){
            fragments.push(rowStarted ? '

' : '
');
            rowStarted = true;
          }

          // @TODO remove requirement on bars
          var s = series[i],
            boxWidth = legend.labelBoxWidth,
            boxHeight = legend.labelBoxHeight,
            opacityValue = (s.bars ? s.bars.fillOpacity : legend.labelBoxOpacity),
            opacity = 'opacity:' + opacityValue + ';filter:alpha(opacity=' + opacityValue*100 + ');';

          label = legend.labelFormatter(s.label);
          color = 'background-color:' + ((s.bars && s.bars.show && s.bars.fillColor && s.bars.fill) ? s.bars.fillColor : s.color) + ';';

          fragments.push(
            '',
              '
',
                '
', // Border
                  '

', // Background
                '
',
              '
',
            '	',
            '', label, '	'
          );
        }
        if(rowStarted) fragments.push('
');

        if(fragments.length > 0){
          var table = '
' + fragments.join('') + '
';
          if(legend.container){
            D.insert(legend.container, table);
          }
          else {
            var styles = {position: 'absolute', 'z-index': 2};

                 if(p.charAt(0) == 'n') { styles.top = (m + plotOffset.top) + 'px'; styles.bottom = 'auto'; }
            else if(p.charAt(0) == 's') { styles.bottom = (m + plotOffset.bottom) + 'px'; styles.top = 'auto'; }
                 if(p.charAt(1) == 'e') { styles.right = (m + plotOffset.right) + 'px'; styles.left = 'auto'; }
            else if(p.charAt(1) == 'w') { styles.left = (m + plotOffset.left) + 'px'; styles.right = 'auto'; }

            var div = D.create('div'), size;
            div.className = 'flotr-legend';
            D.setStyles(div, styles);
            D.insert(div, table);
            D.insert(this.el, div);

            if(legend.backgroundOpacity !== 0.0)
              return;
            /**
             * Put in the transparent background separately to avoid blended labels and
             * label boxes.
             */
            var c = legend.backgroundColor;
            if(!c){
              var tmp = (options.grid.backgroundColor) ? options.grid.backgroundColor : Flotr.Color.extract(div);
              c = this.processColor(tmp, null, {opacity: 1});
            }
            c = '#ff00ff';

            _.extend(styles, D.size(div), {
              'backgroundColor': c,
              'z-index': 1
            });
            styles.width += 'px';
            styles.height += 'px';

            div = D.create('div');
            div.className = 'flotr-legend-bg';
            D.setStyles(div, styles);
            D.opacity(div, legend.backgroundOpacity);
            D.insert(div, ' ');
            D.insert(this.el, div);
          }
        }
      }
    }
  }
});
})();
<commit_msg>Fix html background bug.<commit_after>(function () {

var D = Flotr.DOM;

Flotr.addPlugin('legend', {
  options: {
    show: true,            // => setting to true will show the legend, hide otherwise
    noColumns: 1,          // => number of colums in legend table // @todo: doesn't work for HtmlText = false
    labelFormatter: function(v){return v;}, // => fn: string -> string
    labelBoxBorderColor: '#CCCCCC', // => border color for the little label boxes
    labelBoxWidth: 14,
    labelBoxHeight: 10,
    labelBoxMargin: 5,
    labelBoxOpacity: 0.4,
    container: null,       // => container (as jQuery object) to put legend in, null means default on top of graph
    position: 'nw',        // => position of default legend container within plot
    margin: 5,             // => distance from grid edge to default legend container within plot
    backgroundColor: null, // => null means auto-detect
    backgroundOpacity: 0.85// => set to 0 to avoid background, set to 1 for a solid background
  },
  callbacks: {
    'flotr:afterinit': function() {
      this.legend.insertLegend();
    }
  },
  /**
   * Adds a legend div to the canvas container or draws it on the canvas.
   */
  insertLegend: function(){

    if(!this.options.legend.show)
      return;

    var series = this.series,
      plotOffset = this.plotOffset,
      options = this.options,
      legend = options.legend,
      fragments = [],
      rowStarted = false,
      ctx = this.ctx,
      noLegendItems = _.filter(series, function(s) {return (s.label && !s.hide);}).length,
      p = legend.position,
      m = legend.margin,
      i, label, color;

    if (noLegendItems) {
      if (!options.HtmlText && this.textEnabled && !legend.container) {
        var style = {
          size: options.fontSize*1.1,
          color: options.grid.color
        };

        var lbw = legend.labelBoxWidth,
            lbh = legend.labelBoxHeight,
            lbm = legend.labelBoxMargin,
            offsetX = plotOffset.left + m,
            offsetY = plotOffset.top + m;

        // We calculate the labels' max width
        var labelMaxWidth = 0;
        for(i = series.length - 1; i > -1; --i){
          if(!series[i].label || series[i].hide) continue;
          label = legend.labelFormatter(series[i].label);
          labelMaxWidth = Math.max(labelMaxWidth, Flotr.measureText(ctx, label, style).width);
        }

        var legendWidth  = Math.round(lbw + lbm*3 + labelMaxWidth),
            legendHeight = Math.round(noLegendItems*(lbm+lbh) + lbm);

        if(p.charAt(0) == 's') offsetY = plotOffset.top + this.plotHeight - (m + legendHeight);
        if(p.charAt(1) == 'e') offsetX = plotOffset.left + this.plotWidth - (m + legendWidth);

        // Legend box
        color = this.processColor(legend.backgroundColor || 'rgb(240,240,240)', {opacity: legend.backgroundOpacity || 0.1});

        ctx.fillStyle = color;
        ctx.fillRect(offsetX, offsetY, legendWidth, legendHeight);
        ctx.strokeStyle = legend.labelBoxBorderColor;
        ctx.strokeRect(Flotr.toPixel(offsetX), Flotr.toPixel(offsetY), legendWidth, legendHeight);

        // Legend labels
        var x = offsetX + lbm;
        var y = offsetY + lbm;
        for(i = 0; i < series.length; i++){
          if(!series[i].label || series[i].hide) continue;
          label = legend.labelFormatter(series[i].label);

          ctx.fillStyle = series[i].color;
          ctx.fillRect(x, y, lbw-1, lbh-1);

          ctx.strokeStyle = legend.labelBoxBorderColor;
          ctx.lineWidth = 1;
          ctx.strokeRect(Math.ceil(x)-1.5, Math.ceil(y)-1.5, lbw+2, lbh+2);

          // Legend text
          Flotr.drawText(ctx, label, x + lbw + lbm, y + (lbh + style.size - ctx.fontDescent(style))/2, style);

          y += lbh + lbm;
        }
      }
      else {
        for(i = 0; i < series.length; ++i){
          if(!series[i].label || series[i].hide) continue;

          if(i % legend.noColumns === 0){
            fragments.push(rowStarted ? '

' : '
');
            rowStarted = true;
          }

          // @TODO remove requirement on bars
          var s = series[i],
            boxWidth = legend.labelBoxWidth,
            boxHeight = legend.labelBoxHeight,
            opacityValue = (s.bars ? s.bars.fillOpacity : legend.labelBoxOpacity),
            opacity = 'opacity:' + opacityValue + ';filter:alpha(opacity=' + opacityValue*100 + ');';

          label = legend.labelFormatter(s.label);
          color = 'background-color:' + ((s.bars && s.bars.show && s.bars.fillColor && s.bars.fill) ? s.bars.fillColor : s.color) + ';';

          fragments.push(
            '',
              '
',
                '
', // Border
                  '

', // Background
                '
',
              '
',
            '	',
            '', label, '	'
          );
        }
        if(rowStarted) fragments.push('
');

        if(fragments.length > 0){
          var table = '
' + fragments.join('') + '
';
          if(legend.container){
            D.insert(legend.container, table);
          }
          else {
            var styles = {position: 'absolute', 'z-index': 2};

                 if(p.charAt(0) == 'n') { styles.top = (m + plotOffset.top) + 'px'; styles.bottom = 'auto'; }
            else if(p.charAt(0) == 's') { styles.bottom = (m + plotOffset.bottom) + 'px'; styles.top = 'auto'; }
                 if(p.charAt(1) == 'e') { styles.right = (m + plotOffset.right) + 'px'; styles.left = 'auto'; }
            else if(p.charAt(1) == 'w') { styles.left = (m + plotOffset.left) + 'px'; styles.right = 'auto'; }

            var div = D.create('div'), size;
            div.className = 'flotr-legend';
            D.setStyles(div, styles);
            D.insert(div, table);
            D.insert(this.el, div);

            if(legend.backgroundOpacity == 0.0)
              return;
            /**
             * Put in the transparent background separately to avoid blended labels and
             * label boxes.
             */
            var c = legend.backgroundColor;
            if(!c){
              var tmp = (options.grid.backgroundColor) ? options.grid.backgroundColor : Flotr.Color.extract(div);
              c = this.processColor(tmp, null, {opacity: 1});
            }

            _.extend(styles, D.size(div), {
              'backgroundColor': c,
              'z-index': 1
            });
            styles.width += 'px';
            styles.height += 'px';

            div = D.create('div');
            div.className = 'flotr-legend-bg';
            D.setStyles(div, styles);
            D.opacity(div, legend.backgroundOpacity);
            D.insert(div, ' ');
            D.insert(this.el, div);
          }
        }
      }
    }
  }
});
})();
<|endoftext|>


<commit_before>(function($, window, document, undefined) {

  if (!$.Rapido) {
    $.Rapido = {};
  }

  $.Rapido.Suggest = function(options) {
    var base = this;

    base.init = function() {
      base.options = $.extend({},$.Rapido.Suggest.defaultOptions, options);

      setSize();

      $(window).resize(function() {
        setSize();
      });

      compileInput();

    };

    var setSize = function() {
      $(base.options.suggestClass).each(function() {

        var $suggest = $(this);
        var $input = $(this).parents(base.options.containerClass).children('input[type = "text"]');

        // Get position of the input and position the suggest accordingly
        $suggest.css({
          'top': ($input.position().top + $input.height()) + 'px',
          'left': $input.position().left + 'px',
          'width': $input.outerWidth() + 'px'
        });

        // Toggle class on :focus and :blur
        $input.focus(function() {
          $(base.options.suggestClass).removeClass('open');
          $suggest.addClass('open');
        });

        $input.blur(function() {
          $suggest.removeClass('open');
        });

      });
    };

    var compileInput = function() {
      $(base.options.suggestClass + ' a').on('click', function(e) {

        var value = $(this).text();
        var $input = $(this).parents(base.options.containerClass).children('input[type = "text"]');

        $input.val(value);

        e.preventDefault();
      });
    };

    base.init();
  };

  $.Rapido.Suggest.defaultOptions = {
    containerClass: '.form__controls',
    suggestClass: '.form__suggest'
  };

  $.rapido_Suggest = function(options) {
    new $.Rapido.Suggest(options);
  };

})(jQuery, window, document);

<commit_msg>Cleaned duplicated code<commit_after>(function($, window, document, undefined) {

  if (!$.Rapido) {
    $.Rapido = {};
  }

  $.Rapido.Suggest = function(options) {
    var base = this;

    base.init = function() {
      base.options = $.extend({},$.Rapido.Suggest.defaultOptions, options);

      $(window).on('ready resize', function() {
        setSize();
      });

      compileInput();

    };

    var setSize = function() {
      $(base.options.suggestClass).each(function() {

        var $suggest = $(this);
        var $input = $(this).parents(base.options.containerClass).children('input[type = "text"]');

        // Get position of the input and position the suggest accordingly
        $suggest.css({
          'top': ($input.position().top + $input.height()) + 'px',
          'left': $input.position().left + 'px',
          'width': $input.outerWidth() + 'px'
        });

        // Toggle class on :focus and :blur
        $input.focus(function() {
          $(base.options.suggestClass).removeClass('open');
          $suggest.addClass('open');
        });

        $input.blur(function() {
          $suggest.removeClass('open');
        });

      });
    };

    var compileInput = function() {
      $(base.options.suggestClass + ' a').on('click', function(e) {

        var value = $(this).text();
        var $input = $(this).parents(base.options.containerClass).children('input[type = "text"]');

        $input.val(value);

        e.preventDefault();
      });
    };

    base.init();
  };

  $.Rapido.Suggest.defaultOptions = {
    containerClass: '.form__controls',
    suggestClass: '.form__suggest'
  };

  $.rapido_Suggest = function(options) {
    new $.Rapido.Suggest(options);
  };

})(jQuery, window, document);

<|endoftext|>


<commit_before>/**
 * Code for getting results
**/
$(document).ready(function() {
	var getResult = function(type, resultInt) {
		var results;

		$.ajax({
			type: "GET",
			url: "functions.php",
			async: false,
			data: {
				request: type,
				value: resultInt
			},
			success: function(data) {
				results = data;
			}
		});
		return results;
	};

	var processResults = function(Results) {
		var objects = {
			bl : {left: [], top:[]},
			br : {left: [], top:[]},
			de : {left: [], top:[]},
			bl : {left: [], top:[]},
			br : {left: [], top:[]},
			de : {left: [], top:[]},
			dx : {left: [], top:[]},
			ke : {left: [], top:[]},
			ma : {left: [], top:[]},
			mi : {left: [], top:[]},
			mp : {left: [], top:[]},
			pa : {left: [], top:[]},
			pe : {left: [], top:[]},
			qu : {left: [], top:[]},
			th : {left: [], top:[]},
			wa : {left: [], top:[]},
			wi : {left: [], top:[]}
		}

		$.each(Results, function(i, Result) {
			var Result = JSON.parse(Result);

			delete Result['desc'];

			$.each(Result, function(j, ObjPiece) {
				objects[j].left.push(ObjPiece.x);
				objects[j].top.push(ObjPiece.y);
			});
		});

		$.each(objects, function(i, obj) {
			var lsum = tsum = 0;
			for(var i = 0; i < obj.left.length; i++){
			    lsum += parseInt(obj.left[i]);
			    tsum += parseInt(obj.top[i]);
			}

			var lavg = lsum/obj.left.length;
			var tavg = tsum/obj.top.length;

			obj.left = lavg;
			obj.top = tavg;
		});

		drawResults(objects);
	};

	var drawResults = function(Objects) {
		$.each(Objects, function(i, obj) {
			$(window[i]).css({
				left: obj.left + '%',
				top: obj.top + '%'
			});
		});
	};

	var setCurrentResult = function(amount) {
		$('#currentResult').val(amount);
	};

	var setResultAmount = function() {
		var amount = getResult('resultAmount');

		$('#resultAmount').val(amount);
	};

	var getAllResults = function() {
		return getResult('average');
	};

	// Gets one random result
	$('#random').click(function() {
		var result = getResult('singleRandom');
		// Splits result into result number and result contents
		var json = JSON.parse(result);

		// Gets result number, which is the value given plus 1
		var amount = parseInt(json[0]) + 1;

		// Sends result contents to be processed
		// Adds result to array, so the processing function can handle it
		processResults([json[1]]);

		// Show description

		// Sets which result we're currently on
		setCurrentResult(amount);
	});

	$('#average').click(function() {
		var Results = getAllResults();

		// Splits result into result number and result contents
		var json = JSON.parse(Results);

		processResults(json)
	});

	$('#currentResult').change(function() {
		var val = $(this).val();
		if(val > $('#resultAmount').val()) {
			$(this).val($('#resultAmount').val());
		} else if (val < 1) {
			$(this).val(1);
		}

		var result = getResult('specific', $(this).val() - 1);

		processResults([result]);

	});

	setResultAmount();
});<commit_msg>Processed objects created on the fly.<commit_after>/**
 * Code for getting results
**/
$(document).ready(function() {
	var getResult = function(type, resultInt) {
		var results;

		$.ajax({
			type: "GET",
			url: "functions.php",
			async: false,
			data: {
				request: type,
				value: resultInt
			},
			success: function(data) {
				results = data;
			}
		});
		return results;
	};

	var processResults = function(Results) {
		var objects = {};

		$.each(Results, function(i, Result) {
			var Result = JSON.parse(Result);

			delete Result['desc'];

			$.each(Result, function(j, ObjPiece) {
				objects[j] = {left: [], top:[]};

				objects[j].left.push(ObjPiece.x);
				objects[j].top.push(ObjPiece.y);
			});
		});

		$.each(objects, function(i, obj) {
			var lsum = tsum = 0;
			for(var i = 0; i < obj.left.length; i++){
			    lsum += parseInt(obj.left[i]);
			    tsum += parseInt(obj.top[i]);
			}

			var lavg = lsum/obj.left.length;
			var tavg = tsum/obj.top.length;

			obj.left = lavg;
			obj.top = tavg;
		});

		drawResults(objects);
	};

	var drawResults = function(Objects) {
		$.each(Objects, function(i, obj) {
			$(window[i]).css({
				left: obj.left + '%',
				top: obj.top + '%'
			});
		});
	};

	var setCurrentResult = function(amount) {
		$('#currentResult').val(amount);
	};

	var setResultAmount = function() {
		var amount = getResult('resultAmount');

		$('#resultAmount').val(amount);
	};

	var getAllResults = function() {
		return getResult('average');
	};

	// Gets one random result
	$('#random').click(function() {
		var result = getResult('singleRandom');
		// Splits result into result number and result contents
		var json = JSON.parse(result);

		// Gets result number, which is the value given plus 1
		var amount = parseInt(json[0]) + 1;

		// Sends result contents to be processed
		// Adds result to array, so the processing function can handle it
		processResults([json[1]]);

		// Show description

		// Sets which result we're currently on
		setCurrentResult(amount);
	});

	$('#average').click(function() {
		var Results = getAllResults();

		// Splits result into result number and result contents
		var json = JSON.parse(Results);

		processResults(json)
	});

	$('#currentResult').change(function() {
		var val = $(this).val();
		if(val > $('#resultAmount').val()) {
			$(this).val($('#resultAmount').val());
		} else if (val < 1) {
			$(this).val(1);
		}

		var result = getResult('specific', $(this).val() - 1);

		processResults([result]);

	});

	setResultAmount();
});<|endoftext|>