<commit_before>if (typeof define !== 'function') { var define = require('amdefine')(module); }
define([], function () {
    'use strict';

    /**
     * OOP for JavaScript with class inheritance and private and protected encapsulation
     *
     * @module clajs
     * @author Robin Schaufler <robin@likethebird.com>
    **/

    function propertyExtend (dest, src) {
        var srcNames = Object.getOwnPropertyNames(src);
        srcNames.forEach(function (name) {
            Object.defineProperty(dest, name, Object.getOwnPropertyDescriptor(src, name));
        });
        return dest;
    }

    function assert (assertion, message) {
        if (!assertion) {
            throw new Error(message);
        }
    }

    /**
     * clajs - Declare a constructor to be a class
     *
     * Factory function, not used with new.
     *
     * Returns a constructor which supports inheritance with private and protected enapsulation,
     * in contrast to the typical JavaScript constructor which exposes all its state
     * in public properties of the returned object.
     *
     * @class clajs
     *
     * @param[in] name The name of the clajs
     * @param[in] xtor The original constructor function
     * @param[in] base Optional - the constructor of the base clajs
    **/
    return function clajs (name, xtor, base) {
        var actualXtor = function actualXtor () {
            assert(this instanceof actualXtor, name + ' must be called with new.');
            this.instance = function (options) {
                options = options || {};
                var protectedProperties = options.protectedProps || {};
                var publicProperties = options.publicProps || {};
                var rebase = isExtension && base.prototype || actualXtor.prototype;
                var Replacement = function () {};
                var rp = Replacement.prototype = Object.create(rebase, {
                    constructor: {
                        value: Replacement,
                        writeable: false,
                        configurable: false,
                        enumerable: true
                    },
                    originalName: {
                        value: name,
                        writeable: false,
                        configurable: false,
                        enumerable: true
                    },
                    name: {
                        value: name + ' Replacement',
                        writeable: false,
                        configurable: false,
                        enumerable: true
                    }
                });
                propertyExtend(rp, publicProperties);
                return new Replacement();
            };
            return xtor.apply(this, arguments);
        };
        actualXtor.prototype = {
            constructor: actualXtor,
            name: name,
            baseConstructor: base
        };
        var isExtension = !!base && base.prototype instanceof actualXtor;
        return actualXtor;
    };
});
<commit_msg>clajs works with a single clajs.<commit_after>if (typeof define !== 'function') { var define = require('amdefine')(module); }
define([], function () {
    'use strict';

    /**
     * OOP for JavaScript with class inheritance and private and protected encapsulation
     *
     * @module clajs
     * @author Robin Schaufler <robin@likethebird.com>
    **/

    // Extend object dest with own properties of src, with the same property definitions
    function propertyExtend (dest, src) {
        var srcNames = Object.getOwnPropertyNames(src);
        srcNames.forEach(function (name) {
            Object.defineProperty(dest, name, Object.getOwnPropertyDescriptor(src, name));
        });
        return dest;
    }

    function assert (assertion, message) {
        if (!assertion) {
            throw new Error(message);
        }
    }

    /**
     * clajs - Declare a constructor to be a class
     *
     * Factory function, not used with new.
     *
     * Returns a constructor which supports inheritance with private and protected enapsulation,
     * in contrast to the typical JavaScript constructor which exposes all its state
     * in public properties of the returned object.
     *
     * @class clajs
     *
     * @param clajsName (String) The clajsName of the clajs
     * @param xtor (Function) The original constructor function
     * @param base Optional - the base clajs:
     *        (Function) - the constructor of the base clajs, assumes same arguments as xtor
     *        (Object)   - options describing the base clajs
     *
     *      base.base (Function) Required: The base clajs
     *      base.factory (Function) params are the same as xtor, returns new instance of base.base
    **/
    return function clajs (clajsName, xtor, base) {
        var baseInstanceFactory;
        if (base instanceof Object && !(base instanceof Function)) {
            baseInstanceFactory = base.factory;
            base = base.base;
        }
        // When a client makes a clajs, say, var A = clajs('A',...);
        // A is an instance of actualXtor.
        // There is a distinct actualXtor for each clajs.
        // new A() invokes actualXtor with "this" = the object created by new.
        var actualXtor = function actualXtor () {
            assert(this instanceof actualXtor, clajsName + ' must be called with new.');

            this.base = base || this.rebase || Object;
            var suprFactory = baseInstanceFactory &&
                function baseFactory () {
                    var baseInstance = Object.create(base.prototype);
                    return baseInstanceFactory.apply(baseInstance, arguments).prototype;
                } ||
                !!base &&
                    function baseInstanceFactory () {
                        var baseInstance = Object.create(base.prototype);
                        // this.rebase tells the base xtor the outermost clajs that extends it.
                        baseInstance.rebase = this.rebase || actualXtor;
                        base.apply(baseInstance, arguments);
                        return Object.getPrototypeOf(baseInstance);
                    }.bind(this) ||
                    function rebaseInstanceFactory () {
                        // This clajs is the ultimate base class.
                        // If it is not being called in the context of an extension,
                        // its replacement prototype can extend its own prototype.
                        this.rebase = this.rebase || actualXtor;
                        return this.rebase.prototype;
                    }.bind(this);

            this.supr = suprFactory(arguments);

            // TODO Is there any way to assign a name to the function itself?
            var Replacement = function () {};
            var rp = Replacement.prototype = Object.create(this.supr, {
                constructor: {
                    value: Replacement,
                    writeable: false,
                    configurable: false,
                    enumerable: true
                },
                originalName: {
                    value: clajsName,
                    writeable: false,
                    configurable: false,
                    enumerable: true
                },
                name: {
                    value: clajsName + ' Replacement',
                    writeable: false,
                    configurable: false,
                    enumerable: true
                }
            });

            this.instance = function (options) {
                options = options || {};
                var protectedProperties = options.protectedProps || {};
                var publicProperties = options.publicProps || {};
                propertyExtend(rp, publicProperties);
                if (this.rebase !== actualXtor.prototype) {
                    propertyExtend(rp, protectedProperties);
                }
                return new Replacement();
            };
            return xtor.apply(this, arguments);
        };
        actualXtor.prototype = Object.create((base || Object).prototype, {
            constructor: {
                value: actualXtor
            },
            clajsName: {
                value: clajsName
            }
        });
        return actualXtor;
    };
});
<|endoftext|>


<commit_before>/**
 * Async Request Controller - jQuery plugin for requests asynchronously
 *
 * Copyright (c) 2016 lucasantanaweb@gmail.com
 *
 * Licensed under the MIT license:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Project home:
 *   http://lucaszanevich.com.br/async-request-controller/
 *
 * Version:  1.0.0
 *
 */
(function($) {
    jQuery.fn.asyncController = function(options) {

        var defaults = {
            requests: 0,
            requestMethod: 'GET',
            requestType: 'html',
            requestAttempts: 0,
            requestAttemptsTimer: 5000,
            requestData: {},
            targetProgress: null,
            progressEffect: true,
            before: function() {},
            success: function() {},
            always: function() {}
        };

        var $this = $(this);
        var custom = $.extend({}, defaults, options);

        var settings = {
            requests: [],
            requestData: [],
            requestRunning: 0,
            requestRunningAttempts: {},
            requestCall: 0,
            requestNum: 0,
            requestNumTotal: 0,
            requestTimer: null,
            requestAgain: {},
            requestActiveAttempts: false
        }

        var returnCustom = {
            finishRequests: false
        };

        // transform requests & data order
        for (var key in custom.requests) {
            if (custom.requests.hasOwnProperty(key)) {
                settings.requests.push(custom.requests[key]);
            }
        }
        for (var key in custom.requestData) {
            if (custom.requestData.hasOwnProperty(key)) {
                settings.requestData.push(custom.requestData[key]);
            }
        }

        if (jQuery.type(settings.requests.length) === "undefined" || settings.requests == 0)
            return console.log('No data requests');

        // reset and config settings
        settings.requestCall = 0;
        settings.requestActiveAttempts = false;
        settings.requestRunningAttempts = {};
        settings.requestAgain = {};
        settings.requestNum = settings.requests.length;
        settings.requestNumTotal = settings.requests.length;

        setTimeout(function() {
            callProgress(0);
            callTimer(500);
        }, 500);

        var callTimer = function(delay) {
            settings.requestTimer = setInterval(function() {
                if (settings.requestRunning == 0 && settings.requestNum != 0)
                    callRequest();
            }, delay);
        }

        var callRequest = function() {
            $.ajax({
                    url: settings.requests[settings.requestCall],
                    type: custom.requestMethod,
                    dataType: custom.requestType,
                    data: settings.requestData[settings.requestCall],
                    beforeSend: function() {
                        settings.requestRunning = 1;
                        custom.before();
                    }
                })
                .done(function(responseData) {
                    custom.success(responseData);
                })
                .always(function(jqXHR) {
                    settings.requestRunning = 0;
                    var requestWithError = false;
                    if (jQuery.type(settings.requestRunningAttempts[settings.requestCall]) === "undefined") {
                        if (jQuery.type(jqXHR.abort) !== "undefined") {
                            if (jqXHR.abort.length != 0) {
                                settings.requestAgain[settings.requestCall] = settings.requests[settings.requestCall];
                                settings.requestRunningAttempts[settings.requestCall] = 1;
                                requestWithError = true;
                            }
                        }
                    } else {
                        if (jQuery.type(jqXHR.abort) === "undefined")
                            settings.requestRunningAttempts[settings.requestCall] = custom.requestAttempts;
                    }

                    verifyStatus();
                    if (settings.requestCall == 0 && !settings.requestActiveAttempts)
                        settings.requestCall = settings.requestNumTotal;
                    if (!settings.requestActiveAttempts && !requestWithError) {
                        var progressCalc = Math.floor((settings.requestCall / settings.requestNumTotal) * 100);
                        callProgress(progressCalc);
                    }

                    if (settings.requestNum == 0)
                        returnCustom.finishRequests = true;

                    custom.always(returnCustom);
                });
        }

        var verifyStatus = function() {
            if (settings.requestNum > 1) {
                if (settings.requestActiveAttempts) {
                    if (settings.requestRunningAttempts[settings.requestCall] >= custom.requestAttempts) {
                        delete settings.requestAgain[settings.requestCall];
                        delete settings.requestRunningAttempts[settings.requestCall];
                        settings.requestNum = settings.requestNum - 1;
                        settings.requestCall = Object.keys(settings.requestAgain)[0];
                    } else {
                        settings.requestRunningAttempts[settings.requestCall] = settings.requestRunningAttempts[settings.requestCall] + 1;
                    }
                } else {
                    settings.requestNum = settings.requestNum - 1;
                    settings.requestCall = settings.requestCall + 1;
                }
            } else {
                if (settings.requestActiveAttempts) {
                    if (settings.requestRunningAttempts[settings.requestCall] >= custom.requestAttempts) {
                        delete settings.requestAgain[settings.requestCall];
                        delete settings.requestRunningAttempts[settings.requestCall];
                        settings.requestNum = 0;
                        settings.requestCall = 0;
                        clearInterval(settings.requestTimer);
                        settings.requestActiveAttempts = false;
                    } else {
                        settings.requestRunningAttempts[settings.requestCall] = settings.requestRunningAttempts[settings.requestCall] + 1;
                    }
                } else {
                    var checkAttempts = verifiyAttempts();
                    if (!checkAttempts) {
                        settings.requestNum = 0;
                        settings.requestCall = 0;
                        clearInterval(settings.requestTimer);
                    }
                }
            }
        }

        var verifiyAttempts = function() {
            var numRequestsAgain = Object.keys(settings.requestAgain);
            if (custom.requestAttempts == 0 || numRequestsAgain.length == 0 || settings.requestActiveAttempts) {
                return false;
            } else {
                settings.requestNum = numRequestsAgain.length;
                settings.requestCall = numRequestsAgain[0];
                settings.requestActiveAttempts = true;
                clearInterval(settings.requestTimer);
                callTimer(custom.requestAttemptsTimer);
                return true;
            }
        }

        var callProgress = function(progressValue) {
            var divTarget = {};
            divTarget[custom.targetProgress] = progressValue + '%';
            if (progressValue == 0) {
                $this.animate(divTarget, 0);
                return;
            }
            if (custom.progressEffect)
                $this.animate(divTarget, 1500);
            else
                $this.animate(divTarget, 0);
        }

    };
})(jQuery);<commit_msg>Delete jquery.asyncController.js<commit_after><|endoftext|>


<commit_before>
/**
 * Firebug/Web Inspector Outline Implementation using jQuery
 * Tested to work in Chrome, FF, Safari. Buggy in IE ;(
 * Andrew Childs <ac@glomerate.com>
 *
 * Example Setup:
 * var myClickHandler = function (element) { console.log('Clicked element:', element); }
 * var myDomOutline = DomOutline({ onClick: myClickHandler });
 *
 * Public API:
 * myDomOutline.start();
 * myDomOutline.stop();
 */
var DomOutline = function (options) {
    options = options || {};

    var pub = {};
    var self = {
        opts: {
            namespace: options.namespace || 'DomOutline',
            borderWidth: options.borderWidth || 2,
            onClick: options.onClick || false
        },
        keyCodes: {
            backspace: 8,
            escape: 27,
            delete: 46
        },
        active: false,
        initialized: false,
        elements: {}
    };

    function writeStylesheet(css) {
        var element = document.createElement('style');
        element.type = 'text/css';
        document.getElementsByTagName('head')[0].appendChild(element);

        if (element.styleSheet) {
            element.styleSheet.cssText = css; // IE
        } else {
            element.innerHTML = css; // Non-IE
        }
    }

    function initStylesheet() {
        if (self.initialized !== true) {
            var css = '' +
                '.' + self.opts.namespace + ' {' +
                '    background: #09c;' +
                '    position: absolute;' +
                '    z-index: 1000000;' +
                '}' +
                '.' + self.opts.namespace + '_label {' +
                '    background: #09c;' +
                '    border-radius: 2px;' +
                '    color: #fff;' +
                '    font: bold 12px/12px Helvetica, sans-serif;' +
                '    padding: 4px 6px;' +
                '    position: absolute;' +
                '    text-shadow: 0 1px 1px rgba(0, 0, 0, 0.25);' +
                '    z-index: 1000001;' +
                '}';

            writeStylesheet(css);
            self.initialized = true;
        }
    }

    function createOutlineElements() {
        self.elements.label = jQuery('

').addClass(self.opts.namespace + '_label').appendTo('body');
        self.elements.top = jQuery('

').addClass(self.opts.namespace).appendTo('body');
        self.elements.bottom = jQuery('

').addClass(self.opts.namespace).appendTo('body');
        self.elements.left = jQuery('

').addClass(self.opts.namespace).appendTo('body');
        self.elements.right = jQuery('

').addClass(self.opts.namespace).appendTo('body');
    }

    function removeOutlineElements() {
        jQuery.each(self.elements, function(name, element) {
            element.remove();
        });
    }

    function compileLabelText(element, width, height) {
        var label = element.tagName.toLowerCase();
        if (element.id) {
            label += '#' + element.id;
        }
        if (element.className) {
            label += ('.' + jQuery.trim(element.className).replace(/ /g, '.')).replace(/\.\.+/g, '.');
        }
        return label + ' (' + Math.round(width) + 'x' + Math.round(height) + ')';
    }

    function getScrollTop() {
        if (!self.elements.window) {
            self.elements.window = jQuery(window);
        }
        return self.elements.window.scrollTop();
    }

    function updateOutlinePosition(e) {
        if (e.target.className.indexOf(self.opts.namespace) !== -1) {
            return;
        }
        pub.element = e.target;

        var b = self.opts.borderWidth;
        var scroll_top = getScrollTop();
        var pos = pub.element.getBoundingClientRect();
        var top = pos.top + scroll_top;

        var label_text = compileLabelText(pub.element, pos.width, pos.height);
        var label_top = Math.max(0, top - 20 - b, scroll_top);
        var label_left = Math.max(0, pos.left - b);

        self.elements.label.css({ top: label_top, left: label_left }).text(label_text);
        self.elements.top.css({ top: Math.max(0, top - b), left: pos.left - b, width: pos.width + b, height: b });
        self.elements.bottom.css({ top: top + pos.height, left: pos.left - b, width: pos.width + b, height: b });
        self.elements.left.css({ top: top - b, left: Math.max(0, pos.left - b), width: b, height: pos.height + b });
        self.elements.right.css({ top: top - b, left: pos.left + pos.width, width: b, height: pos.height + (b * 2) });
    }

    function stopOnEscape(e) {
        console.log(e.keyCode);
        if (e.keyCode === self.keyCodes.escape || e.keyCode === self.keyCodes.backspace || e.keyCode === self.keyCodes.delete) {
            pub.stop();
        }

        return false;
    }

    function clickHandler(e) {
        pub.stop();
        self.opts.onClick(pub.element);

        return false;
    }

    pub.start = function () {
        initStylesheet();
        if (self.active !== true) {
            self.active = true;
            createOutlineElements();
            jQuery('body').bind('mousemove.' + self.opts.namespace, updateOutlinePosition);
            jQuery('body').bind('keyup.' + self.opts.namespace, stopOnEscape);
            if (self.opts.onClick) {
                setTimeout(function () {
                    jQuery('body').bind('click.' + self.opts.namespace, clickHandler);
                }, 50);
            }
        }
    };

    pub.stop = function () {
        self.active = false;
        removeOutlineElements();
        jQuery('body').unbind('mousemove.' + self.opts.namespace)
            .unbind('keyup.' + self.opts.namespace)
            .unbind('click.' + self.opts.namespace);
    };

    return pub;
};
<commit_msg>AC: keyCode naming<commit_after>/**
 * Firebug/Web Inspector Outline Implementation using jQuery
 * Tested to work in Chrome, FF, Safari. Buggy in IE ;(
 * Andrew Childs <ac@glomerate.com>
 *
 * Example Setup:
 * var myClickHandler = function (element) { console.log('Clicked element:', element); }
 * var myDomOutline = DomOutline({ onClick: myClickHandler });
 *
 * Public API:
 * myDomOutline.start();
 * myDomOutline.stop();
 */
var DomOutline = function (options) {
    options = options || {};

    var pub = {};
    var self = {
        opts: {
            namespace: options.namespace || 'DomOutline',
            borderWidth: options.borderWidth || 2,
            onClick: options.onClick || false
        },
        keyCodes: {
            BACKSPACE: 8,
            ESC: 27,
            DELETE: 46
        },
        active: false,
        initialized: false,
        elements: {}
    };

    function writeStylesheet(css) {
        var element = document.createElement('style');
        element.type = 'text/css';
        document.getElementsByTagName('head')[0].appendChild(element);

        if (element.styleSheet) {
            element.styleSheet.cssText = css; // IE
        } else {
            element.innerHTML = css; // Non-IE
        }
    }

    function initStylesheet() {
        if (self.initialized !== true) {
            var css = '' +
                '.' + self.opts.namespace + ' {' +
                '    background: #09c;' +
                '    position: absolute;' +
                '    z-index: 1000000;' +
                '}' +
                '.' + self.opts.namespace + '_label {' +
                '    background: #09c;' +
                '    border-radius: 2px;' +
                '    color: #fff;' +
                '    font: bold 12px/12px Helvetica, sans-serif;' +
                '    padding: 4px 6px;' +
                '    position: absolute;' +
                '    text-shadow: 0 1px 1px rgba(0, 0, 0, 0.25);' +
                '    z-index: 1000001;' +
                '}';

            writeStylesheet(css);
            self.initialized = true;
        }
    }

    function createOutlineElements() {
        self.elements.label = jQuery('

').addClass(self.opts.namespace + '_label').appendTo('body');
        self.elements.top = jQuery('

').addClass(self.opts.namespace).appendTo('body');
        self.elements.bottom = jQuery('

').addClass(self.opts.namespace).appendTo('body');
        self.elements.left = jQuery('

').addClass(self.opts.namespace).appendTo('body');
        self.elements.right = jQuery('

').addClass(self.opts.namespace).appendTo('body');
    }

    function removeOutlineElements() {
        jQuery.each(self.elements, function(name, element) {
            element.remove();
        });
    }

    function compileLabelText(element, width, height) {
        var label = element.tagName.toLowerCase();
        if (element.id) {
            label += '#' + element.id;
        }
        if (element.className) {
            label += ('.' + jQuery.trim(element.className).replace(/ /g, '.')).replace(/\.\.+/g, '.');
        }
        return label + ' (' + Math.round(width) + 'x' + Math.round(height) + ')';
    }

    function getScrollTop() {
        if (!self.elements.window) {
            self.elements.window = jQuery(window);
        }
        return self.elements.window.scrollTop();
    }

    function updateOutlinePosition(e) {
        if (e.target.className.indexOf(self.opts.namespace) !== -1) {
            return;
        }
        pub.element = e.target;

        var b = self.opts.borderWidth;
        var scroll_top = getScrollTop();
        var pos = pub.element.getBoundingClientRect();
        var top = pos.top + scroll_top;

        var label_text = compileLabelText(pub.element, pos.width, pos.height);
        var label_top = Math.max(0, top - 20 - b, scroll_top);
        var label_left = Math.max(0, pos.left - b);

        self.elements.label.css({ top: label_top, left: label_left }).text(label_text);
        self.elements.top.css({ top: Math.max(0, top - b), left: pos.left - b, width: pos.width + b, height: b });
        self.elements.bottom.css({ top: top + pos.height, left: pos.left - b, width: pos.width + b, height: b });
        self.elements.left.css({ top: top - b, left: Math.max(0, pos.left - b), width: b, height: pos.height + b });
        self.elements.right.css({ top: top - b, left: pos.left + pos.width, width: b, height: pos.height + (b * 2) });
    }

    function stopOnEscape(e) {
        console.log(e.keyCode);
        if (e.keyCode === self.keyCodes.ESC || e.keyCode === self.keyCodes.BACKSPACE || e.keyCode === self.keyCodes.DELETE) {
            pub.stop();
        }

        return false;
    }

    function clickHandler(e) {
        pub.stop();
        self.opts.onClick(pub.element);

        return false;
    }

    pub.start = function () {
        initStylesheet();
        if (self.active !== true) {
            self.active = true;
            createOutlineElements();
            jQuery('body').bind('mousemove.' + self.opts.namespace, updateOutlinePosition);
            jQuery('body').bind('keyup.' + self.opts.namespace, stopOnEscape);
            if (self.opts.onClick) {
                setTimeout(function () {
                    jQuery('body').bind('click.' + self.opts.namespace, clickHandler);
                }, 50);
            }
        }
    };

    pub.stop = function () {
        self.active = false;
        removeOutlineElements();
        jQuery('body').unbind('mousemove.' + self.opts.namespace)
            .unbind('keyup.' + self.opts.namespace)
            .unbind('click.' + self.opts.namespace);
    };

    return pub;
};
<|endoftext|>


<commit_before>(function( $ ) {

  /*
   * Configuration.
   */
  var key = ''; // TODO add your API key
  var datasource = function (products, callback) {
    // TODO add your data call
    // Example: $.getJSON(your_url, url_params, callback);
    /*
     * @param products A list of product to get data for.
     * @param callback The function to call with the product data.
     *
     * The callback method takes a list of dictionaries/objects containing the
     * data for each product in the products argument. This is used for
     * rendering templates so if your template uses the variables id, name and
     * price and you are the list [2,42,1337] as the products argument then the
     * argument for callback should be like:
     *
     *     [{'id': 2,
     *       'name': 'The name of 2',
     *       'price' 1.99
     *       },
     *      {'id': 42,
     *       'name': 'The name of 42',
     *       'price' 49.0
     *       },
     *      {'id': 1337,
     *       'name': 'The name of 1337',
     *       'price' 100.0}]
     *
     * The order dosn't matter but all dictionaries/object MUST have an entry
     * named 'id' with the products ID. Also if the ID is not used in any
     * template.
     */
  };

  /**************************************************************************/

  /**
   * Main invocation method for The Social Digits plugin.
   *
   * @param api The name of the API.
   * @param args The arguments for the API except 'key' and 'visitor' argument
   *             which are handled automaticly.
   * @param template A jQuery selector for the template to be used.
   */
  $.fn.thesocialdigits = function(api, args, template) {
    var elm = this;

    callAPI(api, args, function(data) {
      if('result' in data) {
        datasource(data.result, function(products) {
          buildHTML(elm, data.result, template, products);
        });
      }
    });
  };

  /*
   * Build HTML from template.
   */
  function buildHTML(elm, ids, template, _products) {
    // ensure the correct sorting of product data
    var products = [];

    for (var i in ids) {
      var id = ids[i];

      for(var j in _products) {
        if(_products[j]['id'] == id) {
          products[i] = _products[j];
          break;
        }
      }
    }

    // generate the html from the template
    elm.append(renderTemplate($(template).html(), products));

    // add click logging
    for (var i in ids) {
      var id = ids[i];

      $('a[rel="__tsd-' + id + '"]').click({'id': id}, function(event) {
        var href = $(this).attr('href');
        var t = setTimeout('window.location.href = "' + href + '";', 500); // always go

        callAPI('__log_click', {'product': event.data.id}, function() {
          clearTimeout(t);
          window.location.href = href; // go on success
        });

        return false; // don't go yet
      });
    }

    // cleanup to leave unmodified HTML
    $('a[rel|="__tsd"]').removeAttr('rel');
  }

  /*
   * Primitive template rendering.
   */
  function renderTemplate(template, products) {
    var output = '';

    for (var i in products) {
      var product = products[i];
      var tmp = template.replace(new RegExp('<a', 'g'), '<a rel="__tsd-' + product['id'] + '"');

      for (var key in product) {
        tmp = tmp.replace(new RegExp('{' + key + '}', 'g'), product[key]);
      }

      output += tmp;
    }

    return output;
  }

  /*
   * Base function to call the API.
   */
  function callAPI(api, args, callback) {
    args.key = key;
    var url = 'http://api.thesocialdigits.com/v1/' + api + '?callback=?';
    var data = {
            'payload': JSON.stringify(args)
          };

    $.getJSON(url, data, callback);
  }

})( jQuery );
<commit_msg>Added metadata information.<commit_after>(function( $ ) {

  /*
   * Configuration.
   */
  var key = ''; // TODO add your API key
  var datasource = function (products, callback) {
    // TODO add your data call
    // Example: $.getJSON(your_url, url_params, callback);
    /*
     * @param products A list of product to get data for.
     * @param callback The function to call with the product data.
     *
     * The callback method takes a list of dictionaries/objects containing the
     * data for each product in the products argument. This is used for
     * rendering templates so if your template uses the variables id, name and
     * price and you are the list [2,42,1337] as the products argument then the
     * argument for callback should be like:
     *
     *     [{'id': 2,
     *       'name': 'The name of 2',
     *       'price' 1.99
     *       },
     *      {'id': 42,
     *       'name': 'The name of 42',
     *       'price' 49.0
     *       },
     *      {'id': 1337,
     *       'name': 'The name of 1337',
     *       'price' 100.0}]
     *
     * The order dosn't matter but all dictionaries/object MUST have an entry
     * named 'id' with the products ID. Also if the ID is not used in any
     * template.
     */
  };

  /**************************************************************************/

  /**
   * Main invocation method for The Social Digits plugin.
   *
   * @param api The name of the API.
   * @param args The arguments for the API except 'key' and 'visitor' argument
   *             which are handled automaticly.
   * @param template A jQuery selector for the template to be used.
   */
  $.fn.thesocialdigits = function(api, args, template) {
    var elm = this;

    callAPI(api, args, function(data) {
      if('result' in data) {
        var metadata = {'api': api,
                        'args': args};

        datasource(data.result, function(products) {
          buildHTML(elm, data.result, template, products, metadata);
        });
      }
    });
  };

  /*
   * Build HTML from template.
   */
  function buildHTML(elm, ids, template, _products, metadata) {
    // ensure the correct sorting of product data
    var products = [];

    for (var i in ids) {
      var id = ids[i];

      for(var j in _products) {
        if(_products[j]['id'] == id) {
          products[i] = _products[j];
          break;
        }
      }
    }

    // generate the html from the template
    elm.append(renderTemplate($(template).html(), products));

    // add click logging
    for (var i in ids) {
      var id = ids[i];

      $('a[rel="__tsd-' + id + '"]').click({'id': id}, function(event) {
        var href = $(this).attr('href');
        var t = setTimeout('window.location.href = "' + href + '";', 500);

        callAPI('__log_click', {'product': event.data.id,
                                'metadata': metadata}, function() {
          clearTimeout(t);
          window.location.href = href; // go on success
        });

        return false; // don't go yet
      });
    }

    // cleanup to leave unmodified HTML
    $('a[rel|="__tsd"]').removeAttr('rel');
  }

  /*
   * Primitive template rendering.
   */
  function renderTemplate(template, products) {
    var output = '';

    for (var i in products) {
      var product = products[i];
      var tmp = template.replace(new RegExp('<a', 'g'), '<a rel="__tsd-' + product['id'] + '"');

      for (var key in product) {
        tmp = tmp.replace(new RegExp('{' + key + '}', 'g'), product[key]);
      }

      output += tmp;
    }

    return output;
  }

  /*
   * Base function to call the API.
   */
  function callAPI(api, args, callback) {
    args.key = key;
    var url = 'http://api.thesocialdigits.com/v1/' + api + '?callback=?';
    var data = {
            'payload': JSON.stringify(args)
          };

    $.getJSON(url, data, callback);
  }

})( jQuery );
<|endoftext|>


<commit_before>// @flow
import { expect } from 'chai';

import {
    scenario,
    scenarios,
    setupForRspec,
    setupForAva,
    Stage,
    State,
    Hidden,
    Quoted,
} from '../src';

import {
    BasicScenarioGivenStage,
    BasicScenarioWhenStage,
    BasicScenarioThenStage,
} from './basic-stages';

if (global.describe && global.it) {
    setupForRspec(describe, it);
} else {
    const test = require('ava');
    setupForAva(test);
}

class ES5GivenStage extends BasicScenarioGivenStage {
    @State
    calledRecorder: {
        called: boolean,
    };
    ES5Stage: Class<any>;
    ES5GivenStage: Class<any>;
    ES5WhenStage: Class<any>;
    ES5ThenStage: Class<any>;

    an_es5_stage_class(): this {
        this.calledRecorder = {
            called: false,
        };
        const self = this;

        // $FlowIgnore
        function ES5Stage() {}
        ES5Stage.prototype = {
            an_action_is_performed(): ES5Stage {
                self.calledRecorder.called = true;
                return this;
            },
            anHiddenStep(): ES5Stage {
                return this;
            },
            some_value_$(value: string): ES5Stage {
                return this;
            },
        };
        Object.setPrototypeOf(ES5Stage.prototype, Stage.prototype);
        Object.setPrototypeOf(ES5Stage, Stage);

        // $FlowIgnore
        Hidden.addHiddenStep(ES5Stage, 'anHiddenStep');
        // $FlowIgnore
        Quoted.formatParameter(ES5Stage, 'some_value_$', 'value');

        this.ES5Stage = ES5Stage;

        return this;
    }

    a_scenario_that_uses_this_stage_class(): this {
        this.scenarioRunner.scenarios(
            'group_name',
            this.ES5Stage,
            ({ given, when, then }) => {
                return {
                    scenario_using_stages: scenario({}, () => {
                        given();
                        when().an_action_is_performed();
                        then();
                    }),
                };
            }
        );
        return this;
    }

    a_scenario_that_uses_hidden_steps(): this {
        this.scenarioRunner.scenarios(
            'group_name',
            this.ES5Stage,
            ({ given, when, then }) => {
                return {
                    scenario_name: scenario({}, () => {
                        given();
                        when()
                            .an_action_is_performed()
                            .and()
                            .anHiddenStep();
                        then();
                    }),
                };
            }
        );
        return this;
    }

    a_scenario_that_uses_formatted_parameters(): this {
        this.scenarioRunner.scenarios(
            'group_name',
            this.ES5Stage,
            ({ given, when, then }) => {
                return {
                    scenario_name: scenario({}, () => {
                        given().some_value_$(1337);
                        when();
                        then();
                    }),
                };
            }
        );
        return this;
    }

    three_state_full_es5_stage_classes(): this {
        this.calledRecorder = {
            called: false,
        };
        const self = this;

        // $FlowIgnore
        function ES5GivenStage() {}
        ES5GivenStage.prototype = {
            a_number: function(value: number) {
                this.value = value;
            },
        };
        Object.setPrototypeOf(ES5GivenStage.prototype, Stage.prototype);
        Object.setPrototypeOf(ES5GivenStage, Stage);
        // $FlowIgnore
        State.addProperty(ES5GivenStage, 'value');
        this.ES5GivenStage = ES5GivenStage;

        // $FlowIgnore
        function ES5WhenStage() {}
        ES5WhenStage.prototype = {
            it_is_incremented() {
                this.value++;
            },
        };
        Object.setPrototypeOf(ES5WhenStage.prototype, Stage.prototype);
        Object.setPrototypeOf(ES5WhenStage, Stage);
        // $FlowIgnore
        State.addProperty(ES5WhenStage, 'value');
        this.ES5WhenStage = ES5WhenStage;

        // $FlowIgnore
        function ES5ThenStage() {}
        ES5ThenStage.prototype = {
            its_new_value_is(value: number) {
                expect(this.value).to.equal(value);
                self.calledRecorder.called = true;
            },
        };
        Object.setPrototypeOf(ES5ThenStage.prototype, Stage.prototype);
        Object.setPrototypeOf(ES5ThenStage, Stage);
        // $FlowIgnore
        State.addProperty(ES5ThenStage, 'value');
        this.ES5ThenStage = ES5ThenStage;

        return this;
    }

    a_scenario_that_uses_these_stage_classes(): this {
        this.scenarioRunner.scenarios(
            'group_name',
            [this.ES5GivenStage, this.ES5WhenStage, this.ES5ThenStage],
            ({ given, when, then }) => {
                return {
                    scenario_using_stages: scenario({}, () => {
                        given().a_number(1);
                        when().it_is_incremented();
                        then().its_new_value_is(2);
                    }),
                };
            }
        );
        return this;
    }
}

class ES5ThenStage extends BasicScenarioThenStage {
    @State
    calledRecorder: {
        called: boolean,
    };

    the_es_5_stage_has_been_used(): this {
        expect(this.calledRecorder.called).to.be.true;
        return this;
    }

    the_report_does_not_include_the_hidden_steps(): this {
        const { steps } = this.findPartByKind('WHEN');
        expect(steps.map(({ name }) => name)).to.deep.equal([
            'When an action is performed',
        ]);
        return this;
    }

    the_report_includes_formatted_parameters(): this {
        const { steps } = this.findPartByKind('GIVEN');
        expect(steps.map(({ name }) => name)).to.deep.equal([
            'Given some value "1337"',
        ]);
        return this;
    }
}

scenarios(
    'core.support.es5',
    [ES5GivenStage, BasicScenarioWhenStage, ES5ThenStage],
    ({ given, when, then }) => {
        return {
            scenarios_can_use_an_es5_stage_class: scenario({}, () => {
                given()
                    .a_scenario_runner()
                    .and()
                    .an_es5_stage_class()
                    .and()
                    .a_scenario_that_uses_this_stage_class();

                when().the_scenario_is_executed();

                then().the_es_5_stage_has_been_used();
            }),

            scenarios_can_use_es5_stage_classes_and_share_state: scenario(
                {},
                () => {
                    given()
                        .a_scenario_runner()
                        .and()
                        .three_state_full_es5_stage_classes()
                        .and()
                        .a_scenario_that_uses_these_stage_classes();

                    when().the_scenario_is_executed();

                    then().the_es_5_stage_has_been_used();
                }
            ),

            scenarios_can_use_an_es5_stage_class_with_hidden_steps: scenario(
                {},
                () => {
                    given()
                        .a_scenario_runner()
                        .and()
                        .an_es5_stage_class()
                        .and()
                        .a_scenario_that_uses_hidden_steps();

                    when().the_scenario_is_executed();

                    then().the_report_does_not_include_the_hidden_steps();
                }
            ),

            scenarios_can_use_an_es5_stage_class_with_steps_using_formatted_parameters: scenario(
                {},
                () => {
                    given()
                        .a_scenario_runner()
                        .and()
                        .an_es5_stage_class()
                        .and()
                        .a_scenario_that_uses_formatted_parameters();

                    when().the_scenario_is_executed();

                    then().the_report_includes_formatted_parameters();
                }
            ),
        };
    }
);
<commit_msg>fix(flow): Fix ES5 flow errors<commit_after>// @flow
import { expect } from 'chai';

import {
    scenario,
    scenarios,
    setupForRspec,
    setupForAva,
    Stage,
    State,
    Hidden,
    Quoted,
} from '../src';

import {
    BasicScenarioGivenStage,
    BasicScenarioWhenStage,
    BasicScenarioThenStage,
} from './basic-stages';

if (global.describe && global.it) {
    setupForRspec(describe, it);
} else {
    const test = require('ava');
    setupForAva(test);
}

class ES5GivenStage extends BasicScenarioGivenStage {
    @State
    calledRecorder: {
        called: boolean,
    };
    ES5Stage: Function;
    ES5GivenStage: Function;
    ES5WhenStage: Function;
    ES5ThenStage: Function;

    an_es5_stage_class(): this {
        this.calledRecorder = {
            called: false,
        };
        const self = this;

        // $FlowIgnore
        function ES5Stage() {}
        ES5Stage.prototype = {
            an_action_is_performed(): ES5Stage {
                self.calledRecorder.called = true;
                return this;
            },
            anHiddenStep(): ES5Stage {
                return this;
            },
            some_value_$(value: string): ES5Stage {
                return this;
            },
        };
        Object.setPrototypeOf(ES5Stage.prototype, Stage.prototype);
        Object.setPrototypeOf(ES5Stage, Stage);

        // $FlowIgnore
        Hidden.addHiddenStep(ES5Stage, 'anHiddenStep');
        // $FlowIgnore
        Quoted.formatParameter(ES5Stage, 'some_value_$', 'value');

        this.ES5Stage = ES5Stage;

        return this;
    }

    a_scenario_that_uses_this_stage_class(): this {
        this.scenarioRunner.scenarios(
            'group_name',
            this.ES5Stage,
            ({ given, when, then }) => {
                return {
                    scenario_using_stages: scenario({}, () => {
                        given();
                        when().an_action_is_performed();
                        then();
                    }),
                };
            }
        );
        return this;
    }

    a_scenario_that_uses_hidden_steps(): this {
        this.scenarioRunner.scenarios(
            'group_name',
            this.ES5Stage,
            ({ given, when, then }) => {
                return {
                    scenario_name: scenario({}, () => {
                        given();
                        when()
                            .an_action_is_performed()
                            .and()
                            .anHiddenStep();
                        then();
                    }),
                };
            }
        );
        return this;
    }

    a_scenario_that_uses_formatted_parameters(): this {
        this.scenarioRunner.scenarios(
            'group_name',
            this.ES5Stage,
            ({ given, when, then }) => {
                return {
                    scenario_name: scenario({}, () => {
                        given().some_value_$(1337);
                        when();
                        then();
                    }),
                };
            }
        );
        return this;
    }

    three_state_full_es5_stage_classes(): this {
        this.calledRecorder = {
            called: false,
        };
        const self = this;

        // $FlowIgnore
        function ES5GivenStage() {}
        ES5GivenStage.prototype = {
            a_number: function(value: number) {
                this.value = value;
            },
        };
        Object.setPrototypeOf(ES5GivenStage.prototype, Stage.prototype);
        Object.setPrototypeOf(ES5GivenStage, Stage);
        // $FlowIgnore
        State.addProperty(ES5GivenStage, 'value');
        this.ES5GivenStage = ES5GivenStage;

        // $FlowIgnore
        function ES5WhenStage() {}
        ES5WhenStage.prototype = {
            it_is_incremented() {
                this.value++;
            },
        };
        Object.setPrototypeOf(ES5WhenStage.prototype, Stage.prototype);
        Object.setPrototypeOf(ES5WhenStage, Stage);
        // $FlowIgnore
        State.addProperty(ES5WhenStage, 'value');
        this.ES5WhenStage = ES5WhenStage;

        // $FlowIgnore
        function ES5ThenStage() {}
        ES5ThenStage.prototype = {
            its_new_value_is(value: number) {
                expect(this.value).to.equal(value);
                self.calledRecorder.called = true;
            },
        };
        Object.setPrototypeOf(ES5ThenStage.prototype, Stage.prototype);
        Object.setPrototypeOf(ES5ThenStage, Stage);
        // $FlowIgnore
        State.addProperty(ES5ThenStage, 'value');
        this.ES5ThenStage = ES5ThenStage;

        return this;
    }

    a_scenario_that_uses_these_stage_classes(): this {
        this.scenarioRunner.scenarios(
            'group_name',
            [this.ES5GivenStage, this.ES5WhenStage, this.ES5ThenStage],
            ({ given, when, then }) => {
                return {
                    scenario_using_stages: scenario({}, () => {
                        given().a_number(1);
                        when().it_is_incremented();
                        then().its_new_value_is(2);
                    }),
                };
            }
        );
        return this;
    }
}

class ES5ThenStage extends BasicScenarioThenStage {
    @State
    calledRecorder: {
        called: boolean,
    };

    the_es_5_stage_has_been_used(): this {
        expect(this.calledRecorder.called).to.be.true;
        return this;
    }

    the_report_does_not_include_the_hidden_steps(): this {
        const { steps } = this.findPartByKind('WHEN');
        expect(steps.map(({ name }) => name)).to.deep.equal([
            'When an action is performed',
        ]);
        return this;
    }

    the_report_includes_formatted_parameters(): this {
        const { steps } = this.findPartByKind('GIVEN');
        expect(steps.map(({ name }) => name)).to.deep.equal([
            'Given some value "1337"',
        ]);
        return this;
    }
}

scenarios(
    'core.support.es5',
    [ES5GivenStage, BasicScenarioWhenStage, ES5ThenStage],
    ({ given, when, then }) => {
        return {
            scenarios_can_use_an_es5_stage_class: scenario({}, () => {
                given()
                    .a_scenario_runner()
                    .and()
                    .an_es5_stage_class()
                    .and()
                    .a_scenario_that_uses_this_stage_class();

                when().the_scenario_is_executed();

                then().the_es_5_stage_has_been_used();
            }),

            scenarios_can_use_es5_stage_classes_and_share_state: scenario(
                {},
                () => {
                    given()
                        .a_scenario_runner()
                        .and()
                        .three_state_full_es5_stage_classes()
                        .and()
                        .a_scenario_that_uses_these_stage_classes();

                    when().the_scenario_is_executed();

                    then().the_es_5_stage_has_been_used();
                }
            ),

            scenarios_can_use_an_es5_stage_class_with_hidden_steps: scenario(
                {},
                () => {
                    given()
                        .a_scenario_runner()
                        .and()
                        .an_es5_stage_class()
                        .and()
                        .a_scenario_that_uses_hidden_steps();

                    when().the_scenario_is_executed();

                    then().the_report_does_not_include_the_hidden_steps();
                }
            ),

            scenarios_can_use_an_es5_stage_class_with_steps_using_formatted_parameters: scenario(
                {},
                () => {
                    given()
                        .a_scenario_runner()
                        .and()
                        .an_es5_stage_class()
                        .and()
                        .a_scenario_that_uses_formatted_parameters();

                    when().the_scenario_is_executed();

                    then().the_report_includes_formatted_parameters();
                }
            ),
        };
    }
);
<|endoftext|>


<commit_before>/*globals pikaday, select2 */

'use strict';

var $ = require('jquery'),
    pikaday  = require('../libs/pikaday/plugins/pikaday.jquery'),
    select2  = require('../libs/select2/dist/js/select2.min'),
    spectrum = require('../libs/spectrum/spectrum');

function PulsarFormComponent(html) {

    this.$html = html;

};

PulsarFormComponent.prototype.init = function () {

    var component = this;

    // Colourpickers
    component.initColourpickers();

    // Attach basic pikaday to datepicker fields
    this.$html.find('[data-datepicker=true]').pikaday({
        format: 'DD/MM/YYYY'
    });

    component.$select2 = this.$html.find('.js-select2');

    component.$select2.each(function() {

        var $this = $(this);

        if ($this.data('html')) {

            function formatOption(data) {
                return $('' + data.text + '');
            };

            $this.select2({
                templateResult: formatOption,
                templateSelection: formatOption
            });

        } else {
            $this.select2();
        }
    });

    // Block styled checkboxes and radios
    var choiceBlock = component.$html.find(".choice--block");

    // set up choice block states on load
    $.each(choiceBlock, function() {
        component.initSelectionButtons($(this));
    });

    // choice block click behaviour
    choiceBlock.on('change', '.controls input[type="checkbox"], .controls input[type="radio"]', component.selectionButtons);

};

PulsarFormComponent.prototype.initSelectionButtons = function(e) {

    e.find('input[type="checkbox"]:checked, input[type="radio"]:checked')
        .closest('.control__label')
        .addClass('is-selected');

};

PulsarFormComponent.prototype.initColourpickers = function() {

    var component = this,
        pickers = component.$html.find('.js-colorpicker');

    pickers.each(function() {
        var $this = $(this),
            $input = $this.find('.form__control'),
            $pickerInput = $($.parseHTML('<input>'));

        $pickerInput.insertAfter($input);

        // changing the picker should update the input
        $pickerInput.spectrum({
            color: '#' + $input.val(),
            showInput: false,
            preferredFormat: 'hex',
            replacerClassName: 'btn',
            change: function (color) {
                $input.val(('' + color).substring(1));
            }
        });

        // changing the input should update the picker
        $input.on('change', function () {
            $pickerInput.spectrum('set', '#' + $input.val());
        });
    });
};

PulsarFormComponent.prototype.selectionButtons = function() {

    var $target = $(this);

    var $controls = $target.closest('.controls');

    $controls.find('input[type="checkbox"]:not(:checked), input[type="radio"]:not(:checked)')
        .closest('.control__label')
        .removeClass('is-selected');

    if ($target.is(':checked')) {
        $target.closest('.control__label').addClass('is-selected');
    } else {
        $target.closest('.control__label').removeClass('is-selected');
    }

};

module.exports = PulsarFormComponent;
<commit_msg>Linting tweaks<commit_after>'use strict';

var $ = require('jquery');

require('../libs/pikaday/plugins/pikaday.jquery'),
require('../libs/select2/dist/js/select2.min'),
require('../libs/spectrum/spectrum');

function PulsarFormComponent(html) {

    this.$html = html;

};

PulsarFormComponent.prototype.init = function () {

    var component = this;

    // Colourpickers
    component.initColourpickers();

    // Attach basic pikaday to datepicker fields
    this.$html.find('[data-datepicker=true]').pikaday({
        format: 'DD/MM/YYYY'
    });

    component.$select2 = this.$html.find('.js-select2');

    component.$select2.each(function() {

        var $this = $(this);

        if ($this.data('html')) {

            function formatOption(data) {
                return $('' + data.text + '');
            };

            $this.select2({
                templateResult: formatOption,
                templateSelection: formatOption
            });

        } else {
            $this.select2();
        }
    });

    // Block styled checkboxes and radios
    var choiceBlock = component.$html.find(".choice--block");

    // set up choice block states on load
    $.each(choiceBlock, function() {
        component.initSelectionButtons($(this));
    });

    // choice block click behaviour
    choiceBlock.on('change', '.controls input[type="checkbox"], .controls input[type="radio"]', component.selectionButtons);

};

PulsarFormComponent.prototype.initSelectionButtons = function(e) {

    e.find('input[type="checkbox"]:checked, input[type="radio"]:checked')
        .closest('.control__label')
        .addClass('is-selected');

};

PulsarFormComponent.prototype.initColourpickers = function() {

    var component = this,
        pickers = component.$html.find('.js-colorpicker');

    pickers.each(function() {
        var $this = $(this),
            $input = $this.find('.form__control'),
            $pickerInput = $($.parseHTML('<input>'));

        $pickerInput.insertAfter($input);

        // changing the picker should update the input
        $pickerInput.spectrum({
            color: '#' + $input.val(),
            showInput: false,
            preferredFormat: 'hex',
            replacerClassName: 'btn',
            change: function (color) {
                $input.val(('' + color).substring(1));
            }
        });

        // changing the input should update the picker
        $input.on('change', function () {
            $pickerInput.spectrum('set', '#' + $input.val());
        });
    });
};

PulsarFormComponent.prototype.selectionButtons = function() {

    var $target = $(this);

    var $controls = $target.closest('.controls');

    $controls.find('input[type="checkbox"]:not(:checked), input[type="radio"]:not(:checked)')
        .closest('.control__label')
        .removeClass('is-selected');

    if ($target.is(':checked')) {
        $target.closest('.control__label').addClass('is-selected');
    } else {
        $target.closest('.control__label').removeClass('is-selected');
    }

};

module.exports = PulsarFormComponent;
<|endoftext|>


<commit_before>'use strict';

module.exports = srcPath => {
  const B = require(srcPath + 'Broadcast');
  const say = B.sayAt;
  const Parser = require(srcPath + 'CommandParser').CommandParser;
  const CommandManager = require(srcPath + 'CommandManager');

  const subcommands = new CommandManager();
  subcommands.add({
    name: 'create',
    command: state => (args, player) => {
      if (player.party) {
        return say(player, "You're already in a group.");
      }

      state.PartyManager.create(player);
      say(player, "<green>You created a group, invite players with '<white>group invite <name></white>'</green>");
    }
  });

  subcommands.add({
    name: 'invite',
    command: state => (args, player) => {
      if (!player.party) {
        return say(player, "You don't have a group, create one with 'group create'.");
      }

      if (player.party && player !== player.party.leader) {
        return say(player, "You aren't the leader of the group.");
      }

      if (!args.length) {
        return say(player, "Invite whom?");
      }

      const target = Parser.parseDot(args, player.room.players);

      if (target === player) {
        return say(player, "You ask yourself if you want to join your own group. You humbly accept.");
      }

      if (!target) {
        return say(player, "They aren't here.");
      }

      if (target.party) {
        return say(player, "They are already in a group.");
      }

      say(target, `<b><green>${player.name} invited you to join their group. Join/decline with '<white>group join/decline ${player.name}</white>'</green></b>`);
      say(player, `<b><green>You invite ${target.name} to join your group.</green></b>`);
      player.party.invite(target);
      B.prompt(target);
    }
  }
  );

  subcommands.add({
    name: 'disband',
    command: state => (args, player) => {
      if (!player.party) {
        return say(player, "You aren't in a group.");
      }

      if (player !== player.party.leader) {
        return say(player, "You aren't the leader of the group.");
      }

      if (!args || args !== 'sure') {
        return say(player, `<b><green>You have to confirm disbanding your group with '<white>group disband sure</white>'</green></b>`);
      }

      say(player.party, '<green>Your group was disbanded!</green>');
      state.PartyManager.disband(player.party);
    }
  });

  subcommands.add({
    name: 'join',
    command: state => (args, player) => {
      if (!args.length) {
        return say(player, "Join whose group?");
      }

      const target = Parser.parseDot(args, player.room.players);

      if (!target) {
        return say(player, "They aren't here.");
      }

      if (!target.party || target !== target.party.leader) {
        return say(player, "They aren't leading a group.");
      }

      if (!target.party.isInvited(player)) {
        return say(player, "They haven't invited you to join their group.");
      }

      say(player, `<b><green>You join ${target.name}'s group.</green></b>`);
      say(target.party, `<b><green>${player.name} joined the group.</green></b>`);
      target.party.add(player);
      player.follow(target);
    }
  });

  subcommands.add({
    name: 'decline',
    command: state => (args, player) => {
      if (!args.length) {
        return say(player, "Decline whose invite?");
      }

      const target = Parser.parseDot(args, player.room.players);

      if (!target) {
        return say(player, "They aren't here.");
      }

      say(player, `<b><green>You decline to join ${target.name}'s group.</green></b>`);
      say(target, `<b><green>${player.name} declined to join your group.</green></b>`);
      target.party.removeInvite(player);
    }
  });

  subcommands.add({
    name: 'leave',
    command: state => (args, player) => {
      if (!player.party) {
        return say(player, "You're not in a group.");
      }

      const party = player.party;
      player.party.delete(player);
      say(party, `<b><green>${player.name} left the group.</green></b>`);
      say(player, '<green>You leave the group.</green>');
    }
  });

  subcommands.add({
    name: 'list',
    command: state => (args, player) => {
      if (!player.party) {
        return say(player, "You're not in a group.");
      }

      say(player, '' + B.center(80, 'Group', 'green', '-') + '');
      for (const member of player.party) {
        let tag = '   ';
        if (member === player.party.leader) {
          tag = '[L]';
        }
        say(player, `<b><green>${tag} ${member.name}</green></b>`);
      }
    }
  });

  return {
    aliases: [ 'party' ],
    command: state => (args, player) => {

      if (!args || !args.length) {
        args = 'list';
      }

      const [ command, ...commandArgs ] = args.split(' ');
      const subcommand = subcommands.find(command);

      if (!subcommand) {
        return say(player, "Not a valid party command.");
      }

      subcommand.command(state)(commandArgs, player);
    }
  };
};
<commit_msg>Fix bug in group invite<commit_after>'use strict';

module.exports = srcPath => {
  const B = require(srcPath + 'Broadcast');
  const say = B.sayAt;
  const Parser = require(srcPath + 'CommandParser').CommandParser;
  const CommandManager = require(srcPath + 'CommandManager');

  const subcommands = new CommandManager();
  subcommands.add({
    name: 'create',
    command: state => (args, player) => {
      if (player.party) {
        return say(player, "You're already in a group.");
      }

      state.PartyManager.create(player);
      say(player, "<green>You created a group, invite players with '<white>group invite <name></white>'</green>");
    }
  });

  subcommands.add({
    name: 'invite',
    command: state => (args, player) => {
      if (!player.party) {
        return say(player, "You don't have a group, create one with 'group create'.");
      }

      if (player.party && player !== player.party.leader) {
        return say(player, "You aren't the leader of the group.");
      }

      if (!args.length) {
        return say(player, "Invite whom?");
      }

      const target = Parser.parseDot(args, player.room.players);

      if (target === player) {
        return say(player, "You ask yourself if you want to join your own group. You humbly accept.");
      }

      if (!target) {
        return say(player, "They aren't here.");
      }

      if (target.party) {
        return say(player, "They are already in a group.");
      }

      say(target, `<b><green>${player.name} invited you to join their group. Join/decline with '<white>group join/decline ${player.name}</white>'</green></b>`);
      say(player, `<b><green>You invite ${target.name} to join your group.</green></b>`);
      player.party.invite(target);
      B.prompt(target);
    }
  }
  );

  subcommands.add({
    name: 'disband',
    command: state => (args, player) => {
      if (!player.party) {
        return say(player, "You aren't in a group.");
      }

      if (player !== player.party.leader) {
        return say(player, "You aren't the leader of the group.");
      }

      if (!args || args !== 'sure') {
        return say(player, `<b><green>You have to confirm disbanding your group with '<white>group disband sure</white>'</green></b>`);
      }

      say(player.party, '<green>Your group was disbanded!</green>');
      state.PartyManager.disband(player.party);
    }
  });

  subcommands.add({
    name: 'join',
    command: state => (args, player) => {
      if (!args.length) {
        return say(player, "Join whose group?");
      }

      const target = Parser.parseDot(args, player.room.players);

      if (!target) {
        return say(player, "They aren't here.");
      }

      if (!target.party || target !== target.party.leader) {
        return say(player, "They aren't leading a group.");
      }

      if (!target.party.isInvited(player)) {
        return say(player, "They haven't invited you to join their group.");
      }

      say(player, `<b><green>You join ${target.name}'s group.</green></b>`);
      say(target.party, `<b><green>${player.name} joined the group.</green></b>`);
      target.party.add(player);
      player.follow(target);
    }
  });

  subcommands.add({
    name: 'decline',
    command: state => (args, player) => {
      if (!args.length) {
        return say(player, "Decline whose invite?");
      }

      const target = Parser.parseDot(args, player.room.players);

      if (!target) {
        return say(player, "They aren't here.");
      }

      say(player, `<b><green>You decline to join ${target.name}'s group.</green></b>`);
      say(target, `<b><green>${player.name} declined to join your group.</green></b>`);
      target.party.removeInvite(player);
    }
  });

  subcommands.add({
    name: 'leave',
    command: state => (args, player) => {
      if (!player.party) {
        return say(player, "You're not in a group.");
      }

      const party = player.party;
      player.party.delete(player);
      say(party, `<b><green>${player.name} left the group.</green></b>`);
      say(player, '<green>You leave the group.</green>');
    }
  });

  subcommands.add({
    name: 'list',
    command: state => (args, player) => {
      if (!player.party) {
        return say(player, "You're not in a group.");
      }

      say(player, '' + B.center(80, 'Group', 'green', '-') + '');
      for (const member of player.party) {
        let tag = '   ';
        if (member === player.party.leader) {
          tag = '[L]';
        }
        say(player, `<b><green>${tag} ${member.name}</green></b>`);
      }
    }
  });

  return {
    aliases: [ 'party' ],
    command: state => (args, player) => {

      if (!args || !args.length) {
        args = 'list';
      }

      const [ command, ...commandArgs ] = args.split(' ');
      const subcommand = subcommands.find(command);

      if (!subcommand) {
        return say(player, "Not a valid party command.");
      }

      subcommand.command(state)(commandArgs.join(' '), player);
    }
  };
};
<|endoftext|>


<commit_before>console.log("Hello, World")

console.log("What is: 3 + 5 = ", 3 + 5)
<commit_msg>break down of a simple JavaScript program, 'hello world'<commit_after>// My 'hello world' program in JavaScript
console.log("Hello, World")

console.log("Hello,", "World\n")

console.error("Hello,", "World")

/*
Statement
calling a
function

function argument(s)
Object
membership
comment: single line, and multi-line
*/
<|endoftext|>


<commit_before>function initTable(table){
	console.log(table);
	table.dataTable({
		"sPaginationType": "full_numbers",
		'iDisplayLength': 100,
		"oLanguage": {
            "sProcessing": "正在加载中......",
            "bFilter": false,
            "bInfo": false,
            "sLengthMenu": "每页显示 _MENU_ 条记录",
            "sZeroRecords": "对不起，查询不到相关数据！",
            "sEmptyTable": "表中无数据存在！",
            "sInfo": "当前显示 _START_ 到 _END_ 条，共 _TOTAL_ 条记录",
            "sInfoFiltered": "数据表中共为 _MAX_ 条记录",
            "sSearch": "搜索",
            "oPaginate": {
                "sFirst": "首页",
                "sPrevious": "上一页",
                "sNext": "下一页",
                "sLast": "末页"
            }
        }
	});
}

function init(){
	$('#contents').dataTable({
		"sPaginationType": "full_numbers",
		'iDisplayLength': 50,
		"oLanguage": {
            "sProcessing": "正在加载中......",
            "sLengthMenu": "每页显示 _MENU_ 条记录",
            "sZeroRecords": "对不起，查询不到相关数据！",
            "sEmptyTable": "表中无数据存在！",
            "sInfo": "当前显示 _START_ 到 _END_ 条，共 _TOTAL_ 条记录",
            "sInfoFiltered": "数据表中共为 _MAX_ 条记录",
            "sSearch": "搜索",
            "oPaginate": {
                "sFirst": "首页",
                "sPrevious": "上一页",
                "sNext": "下一页",
                "sLast": "末页"
            }
        }
	});
	var value=$("select[name='contents_length']")[0];
    value.value=50;
}<commit_msg>remove invalid code<commit_after>function initTable(table){
	console.log(table);
	table.dataTable({
		"sPaginationType": "full_numbers",
		'iDisplayLength': 100,
		"oLanguage": {
            "sProcessing": "正在加载中......",
            "bFilter": false,
            "bInfo": false,
            "sLengthMenu": "每页显示 _MENU_ 条记录",
            "sZeroRecords": "对不起，查询不到相关数据！",
            "sEmptyTable": "表中无数据存在！",
            "sInfo": "当前显示 _START_ 到 _END_ 条，共 _TOTAL_ 条记录",
            "sInfoFiltered": "数据表中共为 _MAX_ 条记录",
            "sSearch": "搜索",
            "oPaginate": {
                "sFirst": "首页",
                "sPrevious": "上一页",
                "sNext": "下一页",
                "sLast": "末页"
            }
        }
	});
}

function init(){
	$('#contents').dataTable({
		"sPaginationType": "full_numbers",
		'iDisplayLength': 50,
		"oLanguage": {
            "sProcessing": "正在加载中......",
            "sLengthMenu": "每页显示 _MENU_ 条记录",
            "sZeroRecords": "对不起，查询不到相关数据！",
            "sEmptyTable": "表中无数据存在！",
            "sInfo": "当前显示 _START_ 到 _END_ 条，共 _TOTAL_ 条记录",
            "sInfoFiltered": "数据表中共为 _MAX_ 条记录",
            "sSearch": "搜索",
            "oPaginate": {
                "sFirst": "首页",
                "sPrevious": "上一页",
                "sNext": "下一页",
                "sLast": "末页"
            }
        }
	});
}<|endoftext|>


<commit_before>var esprima = require('esprima');
var fs = require('fs');

Blend.defineClass('Builder.analyzer.Parser', {
    parseOptions: null,
    lastError: null,
    visitor: function () {
        return false;
    },
    init: function () {
        var me = this;
        me.callParent.apply(me, arguments);
        me.parseOptions = me.parseOptions || {};
        me.parseOptions = Blend.apply(me.parseOptions, {tolerant: true});
    },
    parse: function (filename) {
        var me = this,
                syntax;
        try {
            syntax = esprima.parse(fs.readFileSync(filename, 'utf-8'), me.parseOptions);
            return {
                success: me.traverse(syntax),
                error: me.lastError
            };
        } catch (e) {
            return {
                success: false,
                error: e
            };
        }
    },
    /**
     * Executes visitor on the object and its children (recursively).
     * Source: esprima.org
     * @param {type} object
     * @param {type} visitor
     * @returns {undefined}
     */
    traverse: function (object) {
        var me = this, key, child, ok;
        ok = me.visitor.apply(me, [object]);
        if (ok) {
            for (key in object) {
                if (object.hasOwnProperty(key) && ok) {
                    child = object[key];
                    if (typeof child === 'object' && child !== null) {
                        ok = me.traverse(child);
                    }
                }
            }
        }
        return ok;
    },
    isNullAST: function (obj) {
        return (obj.type && obj.type === 'Literal' && obj.value === null);
    }
});

<commit_msg>Added AST value getter functions<commit_after>var esprima = require('esprima');
var fs = require('fs');
Blend.defineClass('Builder.analyzer.Parser', {
    parseOptions: null,
    lastError: null,
    visitor: function () {
        return false;
    },
    init: function () {
        var me = this;
        me.callParent.apply(me, arguments);
        me.parseOptions = me.parseOptions || {};
        me.parseOptions = Blend.apply(me.parseOptions, {tolerant: true});
    },
    parse: function (filename) {
        var me = this,
                syntax;
        try {
            syntax = esprima.parse(fs.readFileSync(filename, 'utf-8'), me.parseOptions);
            return {
                success: me.traverse(syntax),
                error: me.lastError
            };
        } catch (e) {
            return {
                success: false,
                error: e
            };
        }
    },
    /**
     * Executes visitor on the object and its children (recursively).
     * Source: esprima.org
     * @param {type} object
     * @param {type} visitor
     * @returns {undefined}
     */
    traverse: function (object) {
        var me = this, key, child, ok;
        ok = me.visitor.apply(me, [object]);
        if (ok) {
            for (key in object) {
                if (object.hasOwnProperty(key) && ok) {
                    child = object[key];
                    if (typeof child === 'object' && child !== null) {
                        ok = me.traverse(child);
                    }
                }
            }
        }
        return ok;
    },
    isNullAST: function (obj) {
        return (obj.type && obj.type === 'Literal' && obj.value === null);
    },
    getASTValue: function (ast) {
        var me = this, value = ast;
        if (ast.type === 'Literal') {
            value = ast.value;
        } else if (ast.type === 'ArrayExpastsion') {
            value = [];
            Blend.foreach(ast.elements, function (el) {
                value.push(el.value);
            });
        } else if (ast.type === 'ObjectExpression') {
            value = {};
            console.log('hey!');
            Blend.foreach(ast.properties, function (prop) {
                if (prop.key.type === 'Identifier') {
                    value[prop.key.name] = me.getASTValue(prop.value);
                }
            });
        }
        return value;
    },
    getASTProperty: function (name, props) {
        var me = this, res = null;
        Blend.foreach(props, function (prop) {
            if (prop.type === 'Property' && prop.key.name === name) {
                res = prop.value;
                return false; // stop the loop
            }
        });
        if (res) {
            res = me.getASTValue(res);
        }
        return res;
    }
});

<|endoftext|>


<commit_before>/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 *  KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

/*jshint node: true*/

var Q     = require('q'),
    path  = require('path'),
    shell = require('shelljs'),
    spawn = require('./spawn'),
    check_reqs = require('./check_reqs'),
    fs = require('fs');

var events = require('cordova-common').events;

var projectPath = path.join(__dirname, '..', '..');
var projectName = null;

module.exports.run = function (buildOpts) {

    buildOpts = buildOpts || {};

    if (buildOpts.debug && buildOpts.release) {
        return Q.reject('Only one of "debug"/"release" options should be specified');
    }

    if (buildOpts.device && buildOpts.emulator) {
        return Q.reject('Only one of "device"/"emulator" options should be specified');
    }

    if(buildOpts.buildConfig) {
        if(!fs.existsSync(buildOpts.buildConfig)) {
            return Q.reject('Build config file does not exist:' + buildOpts.buildConfig);
        }
        events.emit('log','Reading build config file:', path.resolve(buildOpts.buildConfig));
        var contents = fs.readFileSync(buildOpts.buildConfig, 'utf-8');
        var buildConfig = JSON.parse(contents.replace(/^\ufeff/, '')); // Remove BOM
        if(buildConfig.ios) {
            var buildType = buildOpts.release ? 'release' : 'debug';
            var config = buildConfig.ios[buildType];
            if(config) {
                ['codeSignIdentity', 'codeSignResourceRules', 'provisioningProfile'].forEach(
                    function(key) {
                        buildOpts[key] = buildOpts[key] || config[key];
                    });
            }
        }
    }

    return check_reqs.run().then(function () {
        return findXCodeProjectIn(projectPath);
    }).then(function (name) {
        projectName = name;
        var extraConfig = '';
        if (buildOpts.codeSignIdentity) {
            extraConfig += 'CODE_SIGN_IDENTITY = ' + buildOpts.codeSignIdentity + '\n';
            extraConfig += 'CODE_SIGN_IDENTITY[sdk=iphoneos*] = ' + buildOpts.codeSignIdentity + '\n';
        }
        if (buildOpts.codeSignResourceRules) {
            extraConfig += 'CODE_SIGN_RESOURCE_RULES_PATH = ' + buildOpts.codeSignResourceRules + '\n';
        }
        if (buildOpts.provisioningProfile) {
            extraConfig += 'PROVISIONING_PROFILE = ' + buildOpts.provisioningProfile + '\n';
        }
        return Q.nfcall(fs.writeFile, path.join(__dirname, '..', 'build-extras.xcconfig'), extraConfig, 'utf-8');
    }).then(function () {
        var configuration = buildOpts.release ? 'Release' : 'Debug';

        events.emit('log','Building project  : ' + path.join(projectPath, projectName + '.xcodeproj'));
        events.emit('log','\tConfiguration : ' + configuration);
        events.emit('log','\tPlatform      : ' + (buildOpts.device ? 'device' : 'emulator'));

        var xcodebuildArgs = getXcodeArgs(projectName, projectPath, configuration, buildOpts.device);
        return spawn('xcodebuild', xcodebuildArgs, projectPath);
    }).then(function () {
        if (!buildOpts.device || buildOpts.noSign) {
            return;
        }
        var buildOutputDir = path.join(projectPath, 'build', 'device');
        var pathToApp = path.join(buildOutputDir, projectName + '.app');
        var pathToIpa = path.join(buildOutputDir, projectName + '.ipa');
        var xcRunArgs = ['-sdk', 'iphoneos', 'PackageApplication',
            '-v', pathToApp,
            '-o', pathToIpa];
        if (buildOpts.codeSignIdentity) {
            xcRunArgs.concat('--sign', buildOpts.codeSignIdentity);
        }
        if (buildOpts.provisioningProfile) {
            xcRunArgs.concat('--embed', buildOpts.provisioningProfile);
        }
        return spawn('xcrun', xcRunArgs, projectPath);
    });
};

/**
 * Searches for first XCode project in specified folder
 * @param  {String} projectPath Path where to search project
 * @return {Promise}            Promise either fulfilled with project name or rejected
 */
function findXCodeProjectIn(projectPath) {
    // 'Searching for Xcode project in ' + projectPath);
    var xcodeProjFiles = shell.ls(projectPath).filter(function (name) {
        return path.extname(name) === '.xcodeproj';
    });

    if (xcodeProjFiles.length === 0) {
        return Q.reject('No Xcode project found in ' + projectPath);
    }
    if (xcodeProjFiles.length > 1) {
        events.emit('warn','Found multiple .xcodeproj directories in \n' +
            projectPath + '\nUsing first one');
    }

    var projectName = path.basename(xcodeProjFiles[0], '.xcodeproj');
    return Q.resolve(projectName);
}

module.exports.findXCodeProjectIn = findXCodeProjectIn;

/**
 * Returns array of arguments for xcodebuild
 * @param  {String}  projectName   Name of xcode project
 * @param  {String}  projectPath   Path to project file. Will be used to set CWD for xcodebuild
 * @param  {String}  configuration Configuration name: debug|release
 * @param  {Boolean} isDevice      Flag that specify target for package (device/emulator)
 * @return {Array}                 Array of arguments that could be passed directly to spawn method
 */
function getXcodeArgs(projectName, projectPath, configuration, isDevice) {
    var xcodebuildArgs;
    if (isDevice) {
        xcodebuildArgs = [
            '-xcconfig', path.join(__dirname, '..', 'build-' + configuration.toLowerCase() + '.xcconfig'),
            '-project', projectName + '.xcodeproj',
            'ARCHS=armv7 arm64',
            '-target', projectName,
            '-configuration', configuration,
            '-sdk', 'iphoneos',
            'build',
            'VALID_ARCHS=armv7 arm64',
            'CONFIGURATION_BUILD_DIR=' + path.join(projectPath, 'build', 'device'),
            'SHARED_PRECOMPS_DIR=' + path.join(projectPath, 'build', 'sharedpch')
        ];
    } else { // emulator
        xcodebuildArgs = [
            '-xcconfig', path.join(__dirname, '..', 'build-' + configuration.toLowerCase() + '.xcconfig'),
            '-project', projectName + '.xcodeproj',
            'ARCHS=i386',
            '-target', projectName ,
            '-configuration', configuration,
            '-sdk', 'iphonesimulator',
            'build',
            'VALID_ARCHS=i386',
            'CONFIGURATION_BUILD_DIR=' + path.join(projectPath, 'build', 'emulator'),
            'SHARED_PRECOMPS_DIR=' + path.join(projectPath, 'build', 'sharedpch')
        ];
    }
    return xcodebuildArgs;
}

// help/usage function
module.exports.help = function help() {
    console.log('');
    console.log('Usage: build [--debug | --release] [--archs=\"<list of architectures...>\"]');
    console.log('             [--device | --simulator] [--codeSignIdentity=\"<identity>\"]');
    console.log('             [--codeSignResourceRules=\"<resourcerules path>\"]');
    console.log('             [--provisioningProfile=\"<provisioning profile>\"]');
    console.log('    --help                  : Displays this dialog.');
    console.log('    --debug                 : Builds project in debug mode. (Default)');
    console.log('    --release               : Builds project in release mode.');
    console.log('    -r                      : Shortcut :: builds project in release mode.');
    // TODO: add support for building different archs
    // console.log("    --archs   : Builds project binaries for specific chip architectures (`anycpu`, `arm`, `x86`, `x64`).");
    console.log('    --device, --simulator');
    console.log('                            : Specifies, what type of project to build');
    console.log('    --codeSignIdentity      : Type of signing identity used for code signing.');
    console.log('    --codeSignResourceRules : Path to ResourceRules.plist.');
    console.log('    --provisioningProfile   : UUID of the profile.');
    console.log('    --device --noSign       : Builds project without application signing.');
    console.log('');
    console.log('examples:');
    console.log('    build ');
    console.log('    build --debug');
    console.log('    build --release');
    console.log('    build --codeSignIdentity="iPhone Distribution" --provisioningProfile="926c2bd6-8de9-4c2f-8407-1016d2d12954"');
    // TODO: add support for building different archs
    // console.log("    build --release --archs=\"armv7\"");
    console.log('');
    process.exit(0);
};
<commit_msg>CB-10695 - Replacing SDK/ARCH parameters by new destination parameter. Fixes issues when project has targets using different SDKs, i.e.: watchOS vs iOS<commit_after>/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 *  KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

/*jshint node: true*/

var Q     = require('q'),
    path  = require('path'),
    shell = require('shelljs'),
    spawn = require('./spawn'),
    check_reqs = require('./check_reqs'),
    fs = require('fs');

var events = require('cordova-common').events;

var projectPath = path.join(__dirname, '..', '..');
var projectName = null;

module.exports.run = function (buildOpts) {

    buildOpts = buildOpts || {};

    if (buildOpts.debug && buildOpts.release) {
        return Q.reject('Only one of "debug"/"release" options should be specified');
    }

    if (buildOpts.device && buildOpts.emulator) {
        return Q.reject('Only one of "device"/"emulator" options should be specified');
    }

    if(buildOpts.buildConfig) {
        if(!fs.existsSync(buildOpts.buildConfig)) {
            return Q.reject('Build config file does not exist:' + buildOpts.buildConfig);
        }
        events.emit('log','Reading build config file:', path.resolve(buildOpts.buildConfig));
        var contents = fs.readFileSync(buildOpts.buildConfig, 'utf-8');
        var buildConfig = JSON.parse(contents.replace(/^\ufeff/, '')); // Remove BOM
        if(buildConfig.ios) {
            var buildType = buildOpts.release ? 'release' : 'debug';
            var config = buildConfig.ios[buildType];
            if(config) {
                ['codeSignIdentity', 'codeSignResourceRules', 'provisioningProfile'].forEach(
                    function(key) {
                        buildOpts[key] = buildOpts[key] || config[key];
                    });
            }
        }
    }

    return check_reqs.run().then(function () {
        return findXCodeProjectIn(projectPath);
    }).then(function (name) {
        projectName = name;
        var extraConfig = '';
        if (buildOpts.codeSignIdentity) {
            extraConfig += 'CODE_SIGN_IDENTITY = ' + buildOpts.codeSignIdentity + '\n';
            extraConfig += 'CODE_SIGN_IDENTITY[sdk=iphoneos*] = ' + buildOpts.codeSignIdentity + '\n';
        }
        if (buildOpts.codeSignResourceRules) {
            extraConfig += 'CODE_SIGN_RESOURCE_RULES_PATH = ' + buildOpts.codeSignResourceRules + '\n';
        }
        if (buildOpts.provisioningProfile) {
            extraConfig += 'PROVISIONING_PROFILE = ' + buildOpts.provisioningProfile + '\n';
        }
        return Q.nfcall(fs.writeFile, path.join(__dirname, '..', 'build-extras.xcconfig'), extraConfig, 'utf-8');
    }).then(function () {
        var configuration = buildOpts.release ? 'Release' : 'Debug';

        events.emit('log','Building project  : ' + path.join(projectPath, projectName + '.xcodeproj'));
        events.emit('log','\tConfiguration : ' + configuration);
        events.emit('log','\tPlatform      : ' + (buildOpts.device ? 'device' : 'emulator'));

        var xcodebuildArgs = getXcodeArgs(projectName, projectPath, configuration, buildOpts.device);
        return spawn('xcodebuild', xcodebuildArgs, projectPath);
    }).then(function () {
        if (!buildOpts.device || buildOpts.noSign) {
            return;
        }
        var buildOutputDir = path.join(projectPath, 'build', 'device');
        var pathToApp = path.join(buildOutputDir, projectName + '.app');
        var pathToIpa = path.join(buildOutputDir, projectName + '.ipa');
        var xcRunArgs = ['-sdk', 'iphoneos', 'PackageApplication',
            '-v', pathToApp,
            '-o', pathToIpa];
        if (buildOpts.codeSignIdentity) {
            xcRunArgs.concat('--sign', buildOpts.codeSignIdentity);
        }
        if (buildOpts.provisioningProfile) {
            xcRunArgs.concat('--embed', buildOpts.provisioningProfile);
        }
        return spawn('xcrun', xcRunArgs, projectPath);
    });
};

/**
 * Searches for first XCode project in specified folder
 * @param  {String} projectPath Path where to search project
 * @return {Promise}            Promise either fulfilled with project name or rejected
 */
function findXCodeProjectIn(projectPath) {
    // 'Searching for Xcode project in ' + projectPath);
    var xcodeProjFiles = shell.ls(projectPath).filter(function (name) {
        return path.extname(name) === '.xcodeproj';
    });

    if (xcodeProjFiles.length === 0) {
        return Q.reject('No Xcode project found in ' + projectPath);
    }
    if (xcodeProjFiles.length > 1) {
        events.emit('warn','Found multiple .xcodeproj directories in \n' +
            projectPath + '\nUsing first one');
    }

    var projectName = path.basename(xcodeProjFiles[0], '.xcodeproj');
    return Q.resolve(projectName);
}

module.exports.findXCodeProjectIn = findXCodeProjectIn;

/**
 * Returns array of arguments for xcodebuild
 * @param  {String}  projectName   Name of xcode project
 * @param  {String}  projectPath   Path to project file. Will be used to set CWD for xcodebuild
 * @param  {String}  configuration Configuration name: debug|release
 * @param  {Boolean} isDevice      Flag that specify target for package (device/emulator)
 * @return {Array}                 Array of arguments that could be passed directly to spawn method
 */
function getXcodeArgs(projectName, projectPath, configuration, isDevice) {
    var xcodebuildArgs;
    if (isDevice) {
        xcodebuildArgs = [
            '-xcconfig', path.join(__dirname, '..', 'build-' + configuration.toLowerCase() + '.xcconfig'),
            '-project', projectName + '.xcodeproj',
            '-target', projectName,
            '-configuration', configuration,
            '-destination', 'platform=iOS',
            'build',
            'CONFIGURATION_BUILD_DIR=' + path.join(projectPath, 'build', 'device'),
            'SHARED_PRECOMPS_DIR=' + path.join(projectPath, 'build', 'sharedpch')
        ];
    } else { // emulator
        xcodebuildArgs = [
            '-xcconfig', path.join(__dirname, '..', 'build-' + configuration.toLowerCase() + '.xcconfig'),
            '-project', projectName + '.xcodeproj',
            '-target', projectName ,
            '-configuration', configuration,
            '-destination', 'platform=iOS Simulator',
            'build',
            'CONFIGURATION_BUILD_DIR=' + path.join(projectPath, 'build', 'emulator'),
            'SHARED_PRECOMPS_DIR=' + path.join(projectPath, 'build', 'sharedpch')
        ];
    }
    return xcodebuildArgs;
}

// help/usage function
module.exports.help = function help() {
    console.log('');
    console.log('Usage: build [--debug | --release] [--archs=\"<list of architectures...>\"]');
    console.log('             [--device | --simulator] [--codeSignIdentity=\"<identity>\"]');
    console.log('             [--codeSignResourceRules=\"<resourcerules path>\"]');
    console.log('             [--provisioningProfile=\"<provisioning profile>\"]');
    console.log('    --help                  : Displays this dialog.');
    console.log('    --debug                 : Builds project in debug mode. (Default)');
    console.log('    --release               : Builds project in release mode.');
    console.log('    -r                      : Shortcut :: builds project in release mode.');
    // TODO: add support for building different archs
    // console.log("    --archs   : Builds project binaries for specific chip architectures (`anycpu`, `arm`, `x86`, `x64`).");
    console.log('    --device, --simulator');
    console.log('                            : Specifies, what type of project to build');
    console.log('    --codeSignIdentity      : Type of signing identity used for code signing.');
    console.log('    --codeSignResourceRules : Path to ResourceRules.plist.');
    console.log('    --provisioningProfile   : UUID of the profile.');
    console.log('    --device --noSign       : Builds project without application signing.');
    console.log('');
    console.log('examples:');
    console.log('    build ');
    console.log('    build --debug');
    console.log('    build --release');
    console.log('    build --codeSignIdentity="iPhone Distribution" --provisioningProfile="926c2bd6-8de9-4c2f-8407-1016d2d12954"');
    // TODO: add support for building different archs
    // console.log("    build --release --archs=\"armv7\"");
    console.log('');
    process.exit(0);
};
<|endoftext|>


<commit_before>(function() {
  var accordionComponent = Object.create(HTMLElement.prototype);

  Object.defineProperty(accordionComponent, 'open', {
    value: '',
    writable: true
  });

  Object.defineProperty(accordionComponent, 'title', {
    value: '',
    writable: true
  });

  var content;

  accordionComponent.createdCallback = function() {
    content = this.innerHTML;
    this.innerHTML = null;

    this.titleElement = document.createElement('div');
    this.titleElement.className = 'accordion-component-title';
    this.titleElement.innerHTML = this.getAttribute('title');
    this.appendChild(this.titleElement);

    this.contentElement = document.createElement('div');
    this.contentElement.className = 'content';
    this.appendChild(this.contentElement);
  };

  accordionComponent.attachedCallback = function() {
    this.contentElement.innerHTML = content;
    this.contentElement.style.display = 'none';
    this.addEventListener('click', function() {
      this.toggle();
    });
  };

  accordionComponent.attributeChangedCallback = function(attributeName, oldValue, newValue) {
    switch (attributeName) {
      case 'open':
        if (this.getAttribute('open') != null) {
          this.open();
        } else {
          this.close();
        }
        break;
      case 'title':
        this.titleElement.innerHTML = newValue;
        break;
    }
  };

  accordionComponent.toggle = function() {
    if (this.getAttribute('open') != null) {
      this.removeAttribute('open');
      this.close();
    } else {
      this.setAttribute('open', '');
      this.open();
    }
  }

  accordionComponent.open = function() {
    this.querySelector('.content').style.display = 'block';
  }

  accordionComponent.close = function() {
    this.querySelector('.content').style.display = 'none';
  }

  document.registerElement('accordion-component', {prototype: accordionComponent});
}());
<commit_msg>Removed unnecessary attribute initializers.<commit_after>(function() {
  var accordionComponent = Object.create(HTMLElement.prototype);

  var content;

  accordionComponent.createdCallback = function() {
    content = this.innerHTML;
    this.innerHTML = null;

    this.titleElement = document.createElement('div');
    this.titleElement.className = 'accordion-component-title';
    this.titleElement.innerHTML = this.getAttribute('title');
    this.appendChild(this.titleElement);

    this.contentElement = document.createElement('div');
    this.contentElement.className = 'content';
    this.appendChild(this.contentElement);
  };

  accordionComponent.attachedCallback = function() {
    this.contentElement.innerHTML = content;
    this.contentElement.style.display = 'none';
    this.addEventListener('click', function() {
      this.toggle();
    });
  };

  accordionComponent.attributeChangedCallback = function(attributeName, oldValue, newValue) {
    switch (attributeName) {
      case 'open':
        if (this.getAttribute('open') != null) {
          this.open();
        } else {
          this.close();
        }
        break;
      case 'title':
        this.titleElement.innerHTML = newValue;
        break;
    }
  };

  accordionComponent.toggle = function() {
    if (this.getAttribute('open') != null) {
      this.removeAttribute('open');
      this.close();
    } else {
      this.setAttribute('open', '');
      this.open();
    }
  }

  accordionComponent.open = function() {
    this.querySelector('.content').style.display = 'block';
  }

  accordionComponent.close = function() {
    this.querySelector('.content').style.display = 'none';
  }

  document.registerElement('accordion-component', {prototype: accordionComponent});
}());
<|endoftext|>