<commit_before>/**
 * AuO.js
 *
 * Main entry point for the AuO library. Create a new instance of AuO by calling new AuO(). Calling
 * launch() adds the instance to the DOM tree, and calling suspend() removes the instance from the
 * DOM tree.
 *
 * @constructor
 */
const AuO = function () {
    /**
     * Launches this instance of AuO. Application becomes visible to the user. Will automatically
     * set the z-index so that the launched instance has higher z-index than all other elements on
     * the page.
     */
    this.launch = function () {
        const allElements = document.getElementsByTagName("*");
        const allElementsZindex = Array.from(allElements).map(function (element) {
            return element.style.zIndex;
        });
        const maxZindex = Math.max.apply(null, allElementsZindex);
        container.style("z-index", maxZindex + 1);
        document.body.appendChild(container.element);
    };

    /**
     * Suspends using this instance of AuO. Removes the application from the DOM tree and sets
     * the z-index to -Infinity. The interface is only hidden from view, however. To stop all
     * services, the instance itself must be deleted.
     */
    this.suspend = function () {
        container.detach().style("z-index", -Infinity);
    };

    /**
     * Determines whether the value is a nil-value. A nil value is an undefined or a null.
     */
    const isNil = function (value) {
        return (undefined === value) || (null === value);
    };

    /**
     * A functional, stripped-down wrapper around HTML DOM elements.
     *
     * Functions:
     *     get(attribute) --
     *
     * @constructor
     */
    const FunctionalElement = function (tagname) {
        this.element = document.createElement(tagname);
        this.get = function (attribute) {
            this.element.getAttribute(attribute, val);
            return this;
        };
        this.set = function (attribute, value) {
            if ("innerHTML" === attribute) {
                this.element.innerHTML = isNil(value) ? "" : value;
            } else {
                if (isNil(value)) {
                    this.element.removeAttribute(attribute);
                } else {
                    this.element.setAttribute(attribute, value);
                }
            }
            return this;
        };
        this.style = function (property, value) {
            this.element.style.setProperty(property, value);
            return this;
        };
        this.append = function (child) {
            this.element.appendChild(child.element);
            return this;
        };
        this.remove = function (child) {
            this.element.removechild(child.element);
            return this;
        };
        this.attach = function (parent) {
            parent.element.appendChild(this.element);
            return this;
        };
        this.detach = function () {
            this.element.parentNode.removeChild(this.element);
            return this;
        };
        this.listen = function (event, callback) {
            this.element.addEventLister(event, callback);
            return this;
        };
    };

    // Create the UI container.
    const container = new FunctionalElement("div")
        .style("position", "fixed")
        .style("top", "0px")
        .style("left", "0px")
        .style("width", "100%")
        .style("height", "100vh")
        .style("text-align", "center")
        .style("vertical-align", "middle")
        .style("background-color", "rgba(0, 0, 0, 0.2)");
};
<commit_msg>Creating layout elements.<commit_after>/**
 * AuO.js
 *
 * Main entry point for the AuO library. Create a new instance of AuO by calling new AuO(). Calling
 * launch() adds the instance to the DOM tree, and calling suspend() removes the instance from the
 * DOM tree.
 *
 * @constructor
 */
const AuO = function () {
    /**
     * Launches this instance of AuO. Application becomes visible to the user. Will automatically
     * set the z-index so that the launched instance has higher z-index than all other elements on
     * the page.
     */
    this.launch = function () {
        const allElements = document.getElementsByTagName("*");
        const allElementsZindex = Array.from(allElements).map(function (element) {
            return element.style.zIndex;
        });
        const maxZindex = Math.max.apply(null, allElementsZindex);
        container.style("z-index", maxZindex + 1);
        document.body.appendChild(container.element);
        initiate();
    };

    /**
     * Suspends using this instance of AuO. Removes the application from the DOM tree and sets
     * the z-index to -Infinity. The interface is only hidden from view, however. To stop all
     * services, the instance itself must be deleted.
     */
    this.suspend = function () {
        container.detach().style("z-index", -Infinity);
    };

    /**
     * Determines whether the value is a nil-value. A nil value is an undefined or a null.
     */
    const isNil = function (value) {
        return (undefined === value) || (null === value);
    };

    /**
     * A functional, stripped-down wrapper around HTML DOM elements.
     *
     * Functions:
     *     get(attribute) --
     *
     * @constructor
     */
    const FunctionalElement = function (tagname) {
        this.element = document.createElement(tagname);
        this.get = function (attribute) {
            this.element.getAttribute(attribute, val);
            return this;
        };
        this.set = function (attribute, value) {
            if ("innerHTML" === attribute) {
                this.element.innerHTML = isNil(value) ? "" : value;
            } else {
                if (isNil(value)) {
                    this.element.removeAttribute(attribute);
                } else {
                    this.element.setAttribute(attribute, value);
                }
            }
            return this;
        };
        this.style = function (property, value) {
            this.element.style.setProperty(property, value);
            return this;
        };
        this.append = function (child) {
            this.element.appendChild(child.element);
            return this;
        };
        this.remove = function (child) {
            this.element.removechild(child.element);
            return this;
        };
        this.attach = function (parent) {
            parent.element.appendChild(this.element);
            return this;
        };
        this.detach = function () {
            this.element.parentNode.removeChild(this.element);
            return this;
        };
        this.listen = function (event, callback) {
            this.element.addEventLister(event, callback);
            return this;
        };
    };

    var initiated = false;
    /**
     * Initiates runtime procedures for this instance of AuO. Will only run once throughout the
     * lifetime of an instance. Called by this.launch().
     */
    const initiate = function () {
        // Prevent multiple initiations.
        if (initiated) {
            return;
        }
        initiated = true;
    };

    ////////////////////////////////////////////////////////////////////////////////////////////////
    //
    // Create the DOM elements we want to work with.
    //
    ////////////////////////////////////////////////////////////////////////////////////////////////

    // Highest-level container for the interface, also responsible for the faded screen background.
    const container = new FunctionalElement("div");

    // Element to enable vertical centering of the interface.
    const verticalMiddleButtress = new FunctionalElement("div");

    // Element to enable horizontal centering of the interface.
    const horizontalCenterContainer = new FunctionalElement("div");

    // Main frame for UI.
    const frame = new FunctionalElement("div");

    // Title bar for the UI.
    const titleBar = new FunctionalElement("div");
    const title = new FunctionalElement("div");
    const titleClose = new FunctionalElement("div");

    // Container for the controls UI.
    const controlsUI = new FunctionalElement("div");

    // Buttons for controlling recording and playback.
    const buttonRecord = new FunctionalElement("button");
    const buttonPlay = new FunctionalElement("button");
    const buttonStop = new FunctionalElement("button");

    // Container for the zoom UI.
    const zoomUI = new FunctionalElement("div");

    // Buttons for zooming.
    const buttonZoomIn = new FunctionalElement("button");
    const buttonZoomOut = new FunctionalElement("button");

    // Display for the zoom value for the zoom UI.
    const zoomDisplay = new FunctionalElement("div");

    // Container for the audio UI.
    const audioUI = new FunctionalElement("div");

    // Display for the visualizer of the audio.
    const audioDiplay = new FunctionalElement("canvas");

    // Red bar for indicating the current time frame on the display.
    const audioCurrent = new FunctionalElement("div");

    ////////////////////////////////////////////////////////////////////////////////////////////////
    //
    // Set up the DOM tree.
    //
    ////////////////////////////////////////////////////////////////////////////////////////////////

    ////////////////////////////////////////////////////////////////////////////////////////////////
    //
    // Style the DOM elements.
    //
    ////////////////////////////////////////////////////////////////////////////////////////////////
    container
        .style("position", "fixed")
        .style("top", "0px")
        .style("left", "0px")
        .style("width", "100%")
        .style("height", "100vh")
        .style("text-align", "center")
        .style("vertical-align", "middle")
        .style("background-color", "rgba(0, 0, 0, 0.6)");
};
<|endoftext|>


<commit_before>import Ember from 'ember';
import layout from '../templates/components/tag-input';

const KEY_CODES = {
  BACK_BUTTON: 8,
  COMMA: 188,
  ENTER: 13,
  SPACE: 32
};

export default Ember.Component.extend({
  layout,

  classNames: ['emberTagInput'],

  tagName: 'ul',

  tags: Ember.A(),

  didInsertElement() {
    let tagInput = this.$('.js-ember-tag-input-new');

    tagInput.on('keydown', (e) => {
      let tags = this.get('tags'),
        tagInputVal = tagInput.val().trim();

      if (e.which === KEY_CODES.COMMA || e.which === KEY_CODES.SPACE || e.which === KEY_CODES.ENTER) {
        if (tagInputVal.length > 0) {
          tags.pushObject(tagInputVal);
          tagInput.val('');
          e.preventDefault();
        }
      } else if (e.which === KEY_CODES.BACK_BUTTON) {

      }
    });
  }
});
<commit_msg>Allow removing tags and add actions for add/remove<commit_after>import Ember from 'ember';
import layout from '../templates/components/tag-input';

const KEY_CODES = {
  BACK_BUTTON: 8,
  COMMA: 188,
  ENTER: 13,
  SPACE: 32
};

export default Ember.Component.extend({
  layout,

  classNames: ['emberTagInput'],

  tagName: 'ul',

  tags: Ember.A(),

  didInsertElement() {
    let tagInput = this.$('.js-ember-tag-input-new');

    tagInput.on('keydown', (e) => {
      let tags = this.get('tags'),
        tagInputVal = tagInput.val().trim();

      if (e.which === KEY_CODES.COMMA || e.which === KEY_CODES.SPACE || e.which === KEY_CODES.ENTER) {
        if (tagInputVal.length > 0) {
          let onTagAdd = this.get('onTagAdd');

          tags.pushObject(tagInputVal);
          tagInput.val('');

          if (onTagAdd) {
            onTagAdd(tagInputVal);
          }

          e.preventDefault();
        }
      } else if (e.which === KEY_CODES.BACK_BUTTON) {
        if (tagInputVal.length === 0) {
          let onTagRemove = this.get('onTagRemove'),
            removedTag = tags.popObject();

          if (onTagRemove) {
            onTagRemove(removedTag);
          }
        }
      }
    });
  }
});
<|endoftext|>


<commit_before>! function (definition) {
    if (typeof window != "undefined") window.cadence = definition()
    else if (typeof define == "function") define(definition)
    else module.exports = definition()
} (function () {
    var stack = [], push = [].push, token = {}

    function Cadence (cadence, steps, done) {
        this.finalizers = cadence.finalizers
        this.self = cadence.self
        this.steps = steps
        this.done = done
        this.loop = false
    }

    function Step (step) {
        this.cadence = step.cadence
        this.results = []
        this.errors = []
        this.count = 0
        this.called = 0
        this.index = step.index + 1
        this.sync = true
        this.next = null
        this.vargs = step.vargs
    }

    Step.prototype.callback = function (result, vargs) {
        var error = vargs.shift()
        if (error == null) {
            push.apply(result.vargs, vargs)
        } else {
            this.errors.push(error)
        }
        if (++this.called === this.count) {
            if (this.next == null) {
                this.sync = true
            } else {
                invoke(this.next)
            }
        }
    }

    Step.prototype.createCallback = function () {
        var self = this
        var result = { vargs: [] }

        self.results.push(result)
        self.count++
        self.sync = false

        return callback

        function callback () {
            var I = arguments.length
            var vargs = new Array(I)
            for (var i = 0; i < I; i++) {
                vargs[i] = arguments[i]
            }
            self.callback(result, vargs)
        }
    }

    Step.prototype.createCadence = function (vargs) {
        var self = this

        var callback = this.createCallback()

        var result = this.results[this.results.length - 1]

        var cadence = new Cadence(self.cadence, vargs, function (vargs) {
            callback.apply(null, vargs)
        })

        var step = new Step({
            index: -2,
            cadence: cadence,
            vargs: []
        })

        return result.starter = starter

        function starter () {
            var I = arguments.length
            var vargs = new Array(I)
            for (var i = 0; i < I; i++) {
                vargs[i] = arguments[i]
            }
            return self.starter(step, result, vargs)
        }
    }

    Step.prototype.starter = function (step, result, vargs) {
        if (vargs[0] === token) {
            invoke(step)
        } else {
            var count = 0, cadence = step.cadence

            label.invoke = token
            label.loop = false
            label.cadence = cadence
            label.index = cadence.steps.length

            step.index = -1
            step.cadence.loop = true
            push.apply(step.vargs, vargs)

            return label

            function label () {
                return {
                    invoke: token,
                    loop: true,
                    cadence: cadence,
                    index: 0
                }
            }
        }
    }

    function cadence () {
        var I = arguments.length
        var vargs = new Array(I)
        for (var i = 0; i < I; i++) {
            vargs[i] = arguments[i]
        }
        return _cadence(vargs)
    }

    function call (fn, self, vargs) {
        try {
            var ret = fn.apply(self, vargs)
        } catch (e) {
            return [ ret, e ]
        }
        return [ ret ]
    }

    function invoke (step) {
        while (step = _invoke(step)) { }
    }

    function rescue (step) {
        if (step.errors.length === 0) {
            invoke(step)
        } else {
            var error = step.errors.shift()

            execute(step.cadence.self, [
                step.catcher,
                function () {
                    var I = arguments.length
                    var vargs = new Array(I)
                    for (var i = 0; i < I; i++) {
                        vargs[i] = arguments[i]
                    }
                    if (vargs[0] !== error) {
                        step.vargs = vargs
                        step.results.length = 0
                    }
                }
            ], [ error, done ])

            function done (error) {
                if (error) {
                    step.cadence.done([ error ])
                } else {
                    rescue(step)
                }
            }
        }
    }

    function _invoke (step) {
        var vargs, steps = step.cadence.steps

        if (step.errors.length) {
            if (step.catcher) {
                rescue(step)
            } else {
                step.cadence.done([ step.errors[0] ])
            }
            return null
        }

        if (step.results.length == 0) {
            vargs = step.vargs
            if (vargs[0] && vargs[0].invoke === token) {
                var label = vargs.shift()
                step.cadence = label.cadence
                step.cadence.loop = label.loop
                step.index = label.index - 1
            }
        } else {
            vargs = []
            for (var i = 0, I = step.results.length; i < I; i++) {
                push.apply(vargs, step.results[i].vargs)
            }
        }

        step = new Step(step)

        if (step.index == steps.length) {
            var cadence = step.cadence
            if (cadence.loop) {
                step.index = 0
            } else {
                cadence.done([ null ].concat(vargs))
                return null
            }
        }

        var fn = steps[step.index]

        if (Array.isArray(fn)) {
            if (fn.length === 1) {
                step.cadence.finalizers.push({ steps: fn, vargs: vargs })
                return step
            } else {
                step.catcher = fn[1]
                fn = fn[0]
            }
        }

        stack.push(step)
        var ret = call(fn, step.cadence.self, vargs)
        stack.pop()
        if (ret.length === 2) {
            step.errors.push(ret[1])
            step.vargs = vargs
            step.results.length = 0
        } else {
            for (var i = 0, I = step.results.length; i < I; i++) {
                var result = step.results[i]
                if (result.starter) {
                    result.starter(token)
                }
            }
            step.vargs = [].concat(ret[0] === void(0) ? vargs : ret[0])
        }

        if (step.sync) {
            return step
        }

        step.next = step
        return null
    }

    function async () {
        var step = stack[stack.length - 1]
        var I = arguments.length
        if (I) {
            var vargs = new Array(I)
            for (var i = 0; i < I; i++) {
                vargs[i] = arguments[i]
            }
            return step.createCadence(vargs)
        } else {
            return step.createCallback()
        }
    }

    function finalize (cadence, errors, callback, vargs) {
        if (cadence.finalizers.length == 0) {
            if (errors.length === 0) {
                callback.apply(null, vargs)
            } else {
                callback.apply(null, [ errors[0] ])
            }
        } else {
            var finalizer = cadence.finalizers.shift()
            execute(cadence.self, finalizer.steps, finalizer.vargs.concat(done))
        }
        function done (error) {
            if (error) {
                errors.push(error)
            }
            finalize(cadence, errors, callback, vargs)
        }
    }

    function execute (self, steps, vargs) {
        var callback = vargs.pop()

        var cadence = new Cadence({ finalizers: [], self: self }, steps, done)

        var step = new Step({
            index: -2,
            cadence: cadence,
            vargs: vargs
        })

        invoke(step)

        function done (vargs) {
            if (cadence.finalizers.length == 0) {
                callback.apply(null, vargs)
            } else {
                finalize(cadence, [], callback, vargs)
            }
        }
    }

    function _cadence (steps) {
        var f

        switch (steps[0].length) {
        case 0:
            f = function () {
                var I = arguments.length
                var vargs = new Array(I + 1)
                vargs[0] = async
                for (var i = 0; i < I; i++) {
                    vargs[i + 1] = arguments[i]
                }
                execute(this, steps, vargs)
            }
            break
        case 1:
            f = function (one) {
                var I = arguments.length
                var vargs = new Array(I + 1)
                vargs[0] = async
                for (var i = 0; i < I; i++) {
                    vargs[i + 1] = arguments[i]
                }
                execute(this, steps, vargs)
            }
            break
        case 2:
            f = function (one, two) {
                var I = arguments.length
                var vargs = new Array(I + 1)
                vargs[0] = async
                for (var i = 0; i < I; i++) {
                    vargs[i + 1] = arguments[i]
                }
                execute(this, steps, vargs)
            }
            break
        case 3:
            f = function (one, two, three) {
                var I = arguments.length
                var vargs = new Array(I + 1)
                vargs[0] = async
                for (var i = 0; i < I; i++) {
                    vargs[i + 1] = arguments[i]
                }
                execute(this, steps, vargs)
            }
            break
        case 4:
            f = function (one, two, three, four) {
                var I = arguments.length
                var vargs = new Array(I + 1)
                vargs[0] = async
                for (var i = 0; i < I; i++) {
                    vargs[i + 1] = arguments[i]
                }
                execute(this, steps, vargs)
            }
            break
        default:
            // Avert your eyes if you're squeamish.
            var args = []
            for (var i = 0; i < steps[0].length; i++) {
                args[i] = '_' + i
            }

            var f = (new Function('execute', 'steps', 'return function (' + args.join(',') + ') {' +
                'execute.call(this, steps, Array.prototype.slice.call(arguments))' +
            '}'))(execute, steps)
        }

        f.toString = function () { return steps[0].toString() }

        f.isCadence = true

        return f
    }

    return cadence
})
<commit_msg>Test arity and to string.<commit_after>! function (definition) {
    if (typeof window != "undefined") window.cadence = definition()
    else if (typeof define == "function") define(definition)
    else module.exports = definition()
} (function () {
    var stack = [], push = [].push, token = {}

    function Cadence (cadence, steps, done) {
        this.finalizers = cadence.finalizers
        this.self = cadence.self
        this.steps = steps
        this.done = done
        this.loop = false
    }

    function Step (step) {
        this.cadence = step.cadence
        this.results = []
        this.errors = []
        this.count = 0
        this.called = 0
        this.index = step.index + 1
        this.sync = true
        this.next = null
        this.vargs = step.vargs
    }

    Step.prototype.callback = function (result, vargs) {
        var error = vargs.shift()
        if (error == null) {
            push.apply(result.vargs, vargs)
        } else {
            this.errors.push(error)
        }
        if (++this.called === this.count) {
            if (this.next == null) {
                this.sync = true
            } else {
                invoke(this.next)
            }
        }
    }

    Step.prototype.createCallback = function () {
        var self = this
        var result = { vargs: [] }

        self.results.push(result)
        self.count++
        self.sync = false

        return callback

        function callback () {
            var I = arguments.length
            var vargs = new Array(I)
            for (var i = 0; i < I; i++) {
                vargs[i] = arguments[i]
            }
            self.callback(result, vargs)
        }
    }

    Step.prototype.createCadence = function (vargs) {
        var self = this

        var callback = this.createCallback()

        var result = this.results[this.results.length - 1]

        var cadence = new Cadence(self.cadence, vargs, function (vargs) {
            callback.apply(null, vargs)
        })

        var step = new Step({
            index: -2,
            cadence: cadence,
            vargs: []
        })

        return result.starter = starter

        function starter () {
            var I = arguments.length
            var vargs = new Array(I)
            for (var i = 0; i < I; i++) {
                vargs[i] = arguments[i]
            }
            return self.starter(step, result, vargs)
        }
    }

    Step.prototype.starter = function (step, result, vargs) {
        if (vargs[0] === token) {
            invoke(step)
        } else {
            var count = 0, cadence = step.cadence

            label.invoke = token
            label.loop = false
            label.cadence = cadence
            label.index = cadence.steps.length

            step.index = -1
            step.cadence.loop = true
            push.apply(step.vargs, vargs)

            return label

            function label () {
                return {
                    invoke: token,
                    loop: true,
                    cadence: cadence,
                    index: 0
                }
            }
        }
    }

    function cadence () {
        var I = arguments.length
        var vargs = new Array(I)
        for (var i = 0; i < I; i++) {
            vargs[i] = arguments[i]
        }
        return _cadence(vargs)
    }

    function call (fn, self, vargs) {
        try {
            var ret = fn.apply(self, vargs)
        } catch (e) {
            return [ ret, e ]
        }
        return [ ret ]
    }

    function invoke (step) {
        while (step = _invoke(step)) { }
    }

    function rescue (step) {
        if (step.errors.length === 0) {
            invoke(step)
        } else {
            var error = step.errors.shift()

            execute(step.cadence.self, [
                step.catcher,
                function () {
                    var I = arguments.length
                    var vargs = new Array(I)
                    for (var i = 0; i < I; i++) {
                        vargs[i] = arguments[i]
                    }
                    if (vargs[0] !== error) {
                        step.vargs = vargs
                        step.results.length = 0
                    }
                }
            ], [ error, done ])

            function done (error) {
                if (error) {
                    step.cadence.done([ error ])
                } else {
                    rescue(step)
                }
            }
        }
    }

    function _invoke (step) {
        var vargs, steps = step.cadence.steps

        if (step.errors.length) {
            if (step.catcher) {
                rescue(step)
            } else {
                step.cadence.done([ step.errors[0] ])
            }
            return null
        }

        if (step.results.length == 0) {
            vargs = step.vargs
            if (vargs[0] && vargs[0].invoke === token) {
                var label = vargs.shift()
                step.cadence = label.cadence
                step.cadence.loop = label.loop
                step.index = label.index - 1
            }
        } else {
            vargs = []
            for (var i = 0, I = step.results.length; i < I; i++) {
                push.apply(vargs, step.results[i].vargs)
            }
        }

        step = new Step(step)

        if (step.index == steps.length) {
            var cadence = step.cadence
            if (cadence.loop) {
                step.index = 0
            } else {
                cadence.done([ null ].concat(vargs))
                return null
            }
        }

        var fn = steps[step.index]

        if (Array.isArray(fn)) {
            if (fn.length === 1) {
                step.cadence.finalizers.push({ steps: fn, vargs: vargs })
                return step
            } else {
                step.catcher = fn[1]
                fn = fn[0]
            }
        }

        stack.push(step)
        var ret = call(fn, step.cadence.self, vargs)
        stack.pop()
        if (ret.length === 2) {
            step.errors.push(ret[1])
            step.vargs = vargs
            step.results.length = 0
        } else {
            for (var i = 0, I = step.results.length; i < I; i++) {
                var result = step.results[i]
                if (result.starter) {
                    result.starter(token)
                }
            }
            step.vargs = [].concat(ret[0] === void(0) ? vargs : ret[0])
        }

        if (step.sync) {
            return step
        }

        step.next = step
        return null
    }

    function async () {
        var step = stack[stack.length - 1]
        var I = arguments.length
        if (I) {
            var vargs = new Array(I)
            for (var i = 0; i < I; i++) {
                vargs[i] = arguments[i]
            }
            return step.createCadence(vargs)
        } else {
            return step.createCallback()
        }
    }

    function finalize (cadence, errors, callback, vargs) {
        if (cadence.finalizers.length == 0) {
            if (errors.length === 0) {
                callback.apply(null, vargs)
            } else {
                callback.apply(null, [ errors[0] ])
            }
        } else {
            var finalizer = cadence.finalizers.shift()
            execute(cadence.self, finalizer.steps, finalizer.vargs.concat(done))
        }
        function done (error) {
            if (error) {
                errors.push(error)
            }
            finalize(cadence, errors, callback, vargs)
        }
    }

    function execute (self, steps, vargs) {
        var callback = vargs.pop()

        var cadence = new Cadence({ finalizers: [], self: self }, steps, done)

        var step = new Step({
            index: -2,
            cadence: cadence,
            vargs: vargs
        })

        invoke(step)

        function done (vargs) {
            if (cadence.finalizers.length == 0) {
                callback.apply(null, vargs)
            } else {
                finalize(cadence, [], callback, vargs)
            }
        }
    }

    function _cadence (steps) {
        var f

        switch (steps[0].length) {
        case 0:
            f = function () {
                var I = arguments.length
                var vargs = new Array(I + 1)
                vargs[0] = async
                for (var i = 0; i < I; i++) {
                    vargs[i + 1] = arguments[i]
                }
                execute(this, steps, vargs)
            }
            break
        case 1:
            f = function (one) {
                var I = arguments.length
                var vargs = new Array(I + 1)
                vargs[0] = async
                for (var i = 0; i < I; i++) {
                    vargs[i + 1] = arguments[i]
                }
                execute(this, steps, vargs)
            }
            break
        case 2:
            f = function (one, two) {
                var I = arguments.length
                var vargs = new Array(I + 1)
                vargs[0] = async
                for (var i = 0; i < I; i++) {
                    vargs[i + 1] = arguments[i]
                }
                execute(this, steps, vargs)
            }
            break
        case 3:
            f = function (one, two, three) {
                var I = arguments.length
                var vargs = new Array(I + 1)
                vargs[0] = async
                for (var i = 0; i < I; i++) {
                    vargs[i + 1] = arguments[i]
                }
                execute(this, steps, vargs)
            }
            break
        case 4:
            f = function (one, two, three, four) {
                var I = arguments.length
                var vargs = new Array(I + 1)
                vargs[0] = async
                for (var i = 0; i < I; i++) {
                    vargs[i + 1] = arguments[i]
                }
                execute(this, steps, vargs)
            }
            break
        default:
            // Avert your eyes if you're squeamish.
            var args = []
            for (var i = 0, I = steps[0].length; i < I; i++) {
                args[i] = '_' + i
            }
            var f = (new Function('execute', 'steps', 'async', '                \n\
                return function (' + args.join(',') + ') {                      \n\
                    var I = arguments.length                                    \n\
                    var vargs = new Array(I + 1)                                \n\
                    vargs[0] = async                                            \n\
                    for (var i = 0; i < I; i++) {                               \n\
                        vargs[i + 1] = arguments[i]                             \n\
                    }                                                           \n\
                    execute(this, steps, vargs)                                 \n\
                }                                                               \n\
           '))(execute, steps, async)
        }

        f.toString = function () { return steps[0].toString() }

        f.isCadence = true

        return f
    }

    return cadence
})
<|endoftext|>


<commit_before>/*
 * Exports artboards as png's and saves in the bucket folders e.g. drawable-mdpi
 * @author Łukasz 'Severiaan' Grela
 * @created 	2015/06/09
 * @modified	2015/06/09
 * @version     0.11
 */
/*
 #target Illustrator
 */
(function(){
    if (app.documents.length == 0 )
    {
            alert("Open a document containing some artboards to export before running this script");
            return;
    }
    var extensionFinder = /(\.[^\.]*)$/;
    var prefixTester = /^(((m|h|xh|xxh|xxxh)dpi)_(.*))/gm;
    var document = app.activeDocument;
    var artboards = document.artboards;
    var documentName = document.name.replace(extensionFinder,"");
    //
    var saveAsPng24 = function(document, filePath) {
        //alert("saveAsPng24(document,"+filePath+")")
        var file = new File(filePath);
	var options = new ExportOptionsPNG24();
            options.antiAliasing = true;
            options.transparency = true;
            options.artBoardClipping = true;
            options.verticalScale = 100;
            options.horizontalScale = 100;
        //
        document.exportFile(file, ExportType.PNG24, options);
    };
    var saveInBucket = function(folder, artboard){
        var bucket = artboard.name.replace(prefixTester,"$2");
        var fileName = artboard.name.replace(prefixTester,"$4");
        var myFolder = new Folder(folder.absoluteURI + "/"
                + documentName + "/drawable-" + bucket);
        if (!myFolder.exists) myFolder.create();
        saveAsPng24(document, myFolder.fsName + "/" + fileName + ".png");
    };
    //

    //iterate over artboards, get name and test it;s prefix and save as PNG in appriopriate folder
    var i,ab,folder;

    folder = Folder.selectDialog();

    for (i = artboards.length - 1; i >= 0; i--) {
        artboards.setActiveArtboardIndex(i);
	ab = artboards[i];
        saveInBucket(folder, ab);
    }
})();

<commit_msg>Added artboard name filter to export only specific artboards.<commit_after>/*
 * Exports artboards as png's and saves in the bucket folders e.g. drawable-mdpi
 * @author Łukasz 'Severiaan' Grela
 * @created 	2015/06/09
 * @modified	2015/06/09
 * @version     0.11
 */

// trim polyfill
if (!String.prototype.trim) {
    String.prototype.trim = function () {
      return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
    };
  }
/*
 #target Illustrator
 */
(function() {
  if (app.documents.length == 0) {
    alert(
      'Open a document containing some artboards to export before running this script'
    );
    return;
  }
  var extensionFinder = /(\.[^\.]*)$/;
  var prefixTester = /^(((m|h|xh|xxh|xxxh)dpi)_(.*))/gm;
  var document = app.activeDocument;
  var artboards = document.artboards;
  var documentName = document.name.replace(extensionFinder, '');
  //
  var saveAsPng24 = function(document, filePath) {
    //alert("saveAsPng24(document,"+filePath+")")
    var file = new File(filePath);
    var options = new ExportOptionsPNG24();
    options.antiAliasing = true;
    options.transparency = true;
    options.artBoardClipping = true;
    options.verticalScale = 100;
    options.horizontalScale = 100;
    //
    document.exportFile(file, ExportType.PNG24, options);
  };
  var saveInBucket = function(folder, artboard) {
    var bucket = artboard.name.replace(prefixTester, '$2');
    var fileName = artboard.name.replace(prefixTester, '$4');
    var myFolder = new Folder(
      folder.absoluteURI + '/' + documentName + '/drawable-' + bucket
    );
    if (!myFolder.exists) myFolder.create();
    saveAsPng24(document, myFolder.fsName + '/' + fileName + '.png');
  };
  //

  //iterate over artboards, get name and test it;s prefix and save as PNG in appriopriate folder
  var i, ab, folder, pattern;
  pattern = prompt(
    'Give pattern of artboard names to export, leave asterisk (*) to include all (case insensitive).',
    '*'
  );
  if (pattern === null || pattern.trim() === '') {
    pattern = '*';
  }
  folder = Folder.selectDialog();

  for (i = artboards.length - 1; i >= 0; i--) {
    artboards.setActiveArtboardIndex(i);
    ab = artboards[i];
    if (pattern === '*' || ab.name.toLowerCase().indexOf(pattern) !== -1) {
      saveInBucket(folder, ab);
    }
  }
})();
<|endoftext|>


<commit_before>define(function(require, exports, module) {
    main.consumes = [
        "Plugin", "c9", "tabManager", "preferences", "settings", "save", "ace", "fs", "proc", "info", "http"
    ];
    main.provides = ["wakatime"];
    return main;

    function main(options, imports, register) {
        var Plugin = imports.Plugin;
        var c9 = imports.c9;
        var settings = imports.settings;
        var prefs = imports.preferences;
        var tabManager = imports.tabManager;
        var ace = imports.ace;
        var save = imports.save;
        var fs = imports.fs;
        var proc = imports.proc;
        var info = imports.info;
        var http = imports.http;

        /***** Initialization *****/

        var plugin = new Plugin("WakaTime", main.consumes);
        // var emit = plugin.getEmitter();
        // emit.setMaxListeners(2);

        var pluginVersion = null;
        var c9Version = null;
        var lastFile = null;
        var lastTime = 0;
        var cachedPythonLocation = null;

        function init() {
            pluginVersion = options.version || '1.0.2';
            c9Version = c9.version.split(' ')[0];
            if (settings.get("user/wakatime/@debug"))
                console.log("Initializing WakaTime v" + pluginVersion);

            setupSettings();

            // get user's c9 email address
            info.getUser(function(err, user) {
                if (err || !user || !user.email) {
                    console.log(err);
                    finishInit();
                } else {
                    var apiKey = getApiKey();
                    if (isValidApiKey(apiKey)) {
                        finishInit();
                    } else {
                        createWakaUser(user, finishInit);
                    }
                }
            });
        }

        function finishInit() {

            // make sure we have a WakaTime api key
            var apiKey = getApiKey();
            if (!isValidApiKey(apiKey)) {
                apiKey = promptForApiKey();
                if (isValidApiKey(apiKey))
                    setApiKey(apiKey);
            }

            setupEventHandlers();
        }

        /***** Methods *****/

        function createWakaUser(user, callback) {
            //var url = 'https://wakatime.com/api/v1/users/signup/c9'
            var url = 'http://localhost:5000/api/v1/users/signup/c9'
            var query = {
                email: user.email,
            };
            if (user.fullname) query.full_name = user.fullname;
            var options = {
                query: query,
            };
            http.jsonP(url, options, function(jdata) {
                if (jdata.data && isValidApiKey(jdata.data.api_key))
                    setApiKey(jdata.data.api_key);
                callback && callback();
            });
        }

        function setApiKey(apiKey) {
            if (isValidApiKey(apiKey))
                settings.set("user/wakatime/@apikey", apiKey);
        }

        function getApiKey() {
            return settings.get("user/wakatime/@apikey");
        }

        function promptForApiKey() {
            var key = window.prompt("[WakaTime] Enter your wakatime.com api key:", getApiKey());
            return key;
        }

        function isValidApiKey(key) {
            if (!key) return false;
            var re = new RegExp('^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$', 'i');
            return re.test(key);
        }

        function setupSettings() {
            settings.on("read", function(e) {
                settings.setDefaults("user/wakatime", [
                    ["apikey", ""],
                    ["debug", false],
                    ["exclude", ""],
                ]);
            });
            prefs.add({
                "WakaTime" : {
                    position: 650,
                    "WakaTime" : {
                        position: 100,
                        "API Key": {
                            type: "textbox",
                            setting: "user/wakatime/@apikey",
                            position: 100,
                            width: 242,
                        },
                        "Debug": {
                            type: "checkbox",
                            setting: "user/wakatime/@debug",
                            position: 200,
                        },
                        "Exclude": {
                            type: "textarea-row",
                            setting: "user/wakatime/@exclude",
                            position: 300,
                            width: 600,
                            height: 100,
                            fixedFont: true,
                            rowheight: 250,
                        },
                    }
                }
            }, plugin);
        }

        function setupEventHandlers() {

            save.on("afterSave", function(e) {
                handleActivity(e.path, null, true);
            });

            tabManager.on("focus", function(e) {
                handleActivity(e.tab.path);
            });

            ace.on("create", function(e) {
                if (!lastFile)
                    lastFile = e.editor.activeDocument.tab.path;
                e.editor.ace.on("change", function(e) {
                    getCursorPosition(lastFile, false, e.start.row, e.start.column, handleActivity);
                });
            }, plugin);
        }

        function getCursorPosition(file, isWrite, row, col, callback) {
            if (file) {
                var re = new RegExp('^' + c9.home);
                var relativeFile = file.replace(re, '~');
                fs.readFile(relativeFile, function (err, data) {
                    var cursorpos = null;
                    if (!err) {
                        cursorpos = 0;
                        var lines = data.split(/\n/);
                        for (var i=0; i<lines.length; i++) {
                            if (i == row) {
                                cursorpos += col;
                                break;
                            }
                            cursorpos += lines[i].length + 1;
                        }
                    }
                    if (callback)
                      callback(file, cursorpos, isWrite);
                });
            }
        }

        function enoughTimePassed(time) {
            return lastTime + 120000 < time;
        }

        function fileIsIgnored(file) {
            var patterns = settings.get("user/wakatime/@exclude").split(/\n/);
            var ignore = false;
            for (var i=0; i<patterns.length; i++) {
                if (patterns[i].trim()) {
                    var re = new RegExp(patterns[i], "gi");
                    if (re.test(file)) {
                        console.log("matched " + patterns[i] + " on " + file);
                        ignore = true;
                        break;
                    }
                }
            }
            return ignore;
        }

        function pythonLocation(callback, locations) {
            if (cachedPythonLocation) {
                if (callback)
                    return callback(cachedPythonLocation);
                else
                    return;
            }

            if (locations === undefined) {
                locations = [
                    "pythonw",
                    "python",
                    "/usr/local/bin/python",
                    "/usr/bin/python",
                ];
                for (var i=26; i<40; i++) {
                    locations.push('\\python' + i + '\\pythonw');
                    locations.push('\\Python' + i + '\\pythonw');
                }
            }

            if (locations.length == 0) {
                if (callback)
                    callback(null);
                return;
            }

            var args = ['--version'];
            var location = locations[0];

            proc.execFile(location, {args:args}, function(error, stdout, stderr) {
                if (!error) {
                    cachedPythonLocation = location;
                    if (callback)
                        callback(location);
                } else {
                    locations.splice(0, 1);
                    pythonLocation(callback, locations);
                }
            });

        }

        function coreRelativeLocation() {
            return ".c9/lib/wakatime-core/wakatime-master/wakatime/cli.py";
        }

        function obfuscateKey(key) {
            var newKey = "";
            if (key) {
                newKey = key;
                if (key.length > 4)
                    newKey = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXX" + key.substring(key.length - 4);
            }
            return newKey;
        }

        function obfuscateKeyFromArguments(args) {
            var newCmds = [];
            var lastCmd = "";
            for (var i = 0; i<args.length; i++) {
                if (lastCmd == "--key")
                    newCmds.push(obfuscateKey(args[i]));
                else
                    newCmds.push(args[i]);
                lastCmd = args[i];
            }
            return newCmds;
        }

        function handleActivity(file, cursorpos, isWrite) {
            if (!file)
                return;
            if (file.indexOf('~') == 0) {
                file = c9.home + file.substring(1);
            }
            var time = Date.now();
            if (isWrite || enoughTimePassed(time) || lastFile != file) {
                if (fileIsIgnored(file))
                    return;
                sendHeartbeat(file, time, cursorpos, isWrite);
            }
        }

        function sendHeartbeat(file, time, cursorpos, isWrite) {
            pythonLocation(function(python) {
                if (!python)
                    return;
                var debug = settings.get("user/wakatime/@debug");
                var apiKey = getApiKey();
                var userAgent = 'c9/' + c9Version + ' c9-wakatime/' + pluginVersion;
                var core = c9.home + '/' + coreRelativeLocation();
                var args = [core, '--file', file, '--key', apiKey, '--plugin', userAgent];
                if (isWrite)
                    args.push('--write');
                if (debug)
                    args.push('--verbose');
                if (cursorpos) {
                    args.push('--cursorpos');
                    args.push(cursorpos);
                }
                if (debug) {
                    var clone = args.slice(0);
                    clone.unshift(python);
                    console.log('Sending heartbeat to wakatime-core: ' + obfuscateKeyFromArguments(clone).join(' '));
                }
                proc.execFile(python, {args:args}, function(error, stdout, stderr) {
                    if (error) {
                        if (stderr && stderr != '')
                            console.warn(stderr);
                        if (stdout && stdout != '')
                            console.warn(stdout);
                        if (error.code == 102)
                            console.warn('Warning: api error (102); Check your ~/.wakatime.log file for more details.');
                        else if (error.code == 103)
                            console.warn('Warning: config parsing error (103); Check your ~/.wakatime.log file for more details.');
                        else
                            console.warn(error);
                    }
                });
                lastTime = time;
                lastFile = file;
            });
        }

        /***** Lifecycle *****/

        plugin.on("load", function() {
            init();
        });
        plugin.on("unload", function() {
        });

        /***** Register and define API *****/
        plugin.freezePublicAPI({
            _events: [
            ],
        });

        register(null, {
            "wakatime": plugin
        });
    }
});
<commit_msg>store wakatime apikey in persistent storage<commit_after>define(function(require, exports, module) {
    main.consumes = [
        "Plugin", "c9", "tabManager", "preferences", "settings", "save", "ace", "fs", "proc", "info", "http"
    ];
    main.provides = ["wakatime"];
    return main;

    function main(options, imports, register) {
        var Plugin = imports.Plugin;
        var c9 = imports.c9;
        var settings = imports.settings;
        var prefs = imports.preferences;
        var tabManager = imports.tabManager;
        var ace = imports.ace;
        var save = imports.save;
        var fs = imports.fs;
        var proc = imports.proc;
        var info = imports.info;
        var http = imports.http;

        /***** Initialization *****/

        var plugin = new Plugin("WakaTime", main.consumes);
        var api  = plugin.setAPIKey(options.apikey);
        // var emit = plugin.getEmitter();
        // emit.setMaxListeners(2);

        var pluginVersion = null;
        var c9Version = null;
        var lastFile = null;
        var lastTime = 0;
        var cachedPythonLocation = null;
        var cachedApiKey = null;

        function init() {
            pluginVersion = options.version || '1.0.2';
            c9Version = c9.version.split(' ')[0];
            if (settings.get("user/wakatime/@debug"))
                console.log("Initializing WakaTime v" + pluginVersion);

            setupSettings();

            // get user's c9 email address
            info.getUser(function(err, user) {
                if (err || !user || !user.email) {
                    console.log(err);
                    finishInit();
                } else {
                    getApiKey(function(apiKey) {
                        if (isValidApiKey(apiKey)) {
                            finishInit();
                        } else {
                            createWakaUser(user, finishInit);
                        }
                    });
                }
            });
        }

        function finishInit() {

            // make sure we have a WakaTime api key
            getApiKey(function(apiKey) {

                if (!isValidApiKey(apiKey)) {
                    apiKey = promptForApiKey(apiKey);
                    if (isValidApiKey(apiKey))
                        setApiKey(apiKey);
                }

                setupEventHandlers();

            });
        }

        /***** Methods *****/

        function createWakaUser(user, callback) {
            var url = 'https://wakatime.com/api/v1/users/signup/c9'
            var query = {
                email: user.email,
            };
            if (user.fullname) query.full_name = user.fullname;
            var options = {
                query: query,
            };
            http.jsonP(url, options, function(jdata) {
                if (jdata.data && isValidApiKey(jdata.data.api_ey))
                    setApiKey(jdata.data.api_key);
                callback && callback();
            });
        }

        function setApiKey(apiKey) {
            if (isValidApiKey(apiKey)) {
                cachedApiKey = apiKey;

                var data = {
                  apiKey: apiKey,
                };
                api.setPersistentData("user", data, function(err) {
                    if (err) console.log(err);
                });
            }
        }

        function getApiKey(callback) {
            if (cachedApiKey) return callback && callback(cachedApiKey);

            api.getPersistentData("user", function(err, data) {
                if (err) console.log(err);
                var apiKey = undefined;
                if (data && data.apiKey) apiKey = data.apiKey;
                callback && callback(apiKey);
            });
        }

        function promptForApiKey(defaultKey) {
            var key = window.prompt("[WakaTime] Enter your wakatime.com api key:", defaultKey);
            return key;
        }

        function isValidApiKey(key) {
            if (!key) return false;
            var re = new RegExp('^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$', 'i');
            return re.test(key);
        }

        function setupSettings() {
            settings.on("read", function(e) {
                settings.setDefaults("user/wakatime", [
                    ["debug", false],
                    ["exclude", ""],
                ]);
            });
            prefs.add({
                "WakaTime" : {
                    position: 650,
                    "WakaTime" : {
                        position: 100,
                        "Debug": {
                            type: "checkbox",
                            setting: "user/wakatime/@debug",
                            position: 100,
                        },
                        "Exclude": {
                            type: "textarea-row",
                            setting: "user/wakatime/@exclude",
                            position: 200,
                            width: 600,
                            height: 100,
                            fixedFont: true,
                            rowheight: 250,
                        },
                    }
                }
            }, plugin);
        }

        function setupEventHandlers() {

            save.on("afterSave", function(e) {
                handleActivity(e.path, null, true);
            });

            tabManager.on("focus", function(e) {
                handleActivity(e.tab.path);
            });

            ace.on("create", function(e) {
                if (!lastFile)
                    lastFile = e.editor.activeDocument.tab.path;
                e.editor.ace.on("change", function(e) {
                    getCursorPosition(lastFile, false, e.start.row, e.start.column, handleActivity);
                });
            }, plugin);
        }

        function getCursorPosition(file, isWrite, row, col, callback) {
            if (file) {
                var re = new RegExp('^' + c9.home);
                var relativeFile = file.replace(re, '~');
                fs.readFile(relativeFile, function (err, data) {
                    var cursorpos = null;
                    if (!err) {
                        cursorpos = 0;
                        var lines = data.split(/\n/);
                        for (var i=0; i<lines.length; i++) {
                            if (i == row) {
                                cursorpos += col;
                                break;
                            }
                            cursorpos += lines[i].length + 1;
                        }
                    }
                    if (callback)
                      callback(file, cursorpos, isWrite);
                });
            }
        }

        function enoughTimePassed(time) {
            return lastTime + 120000 < time;
        }

        function fileIsIgnored(file) {
            var patterns = settings.get("user/wakatime/@exclude").split(/\n/);
            var ignore = false;
            for (var i=0; i<patterns.length; i++) {
                if (patterns[i].trim()) {
                    var re = new RegExp(patterns[i], "gi");
                    if (re.test(file)) {
                        console.log("matched " + patterns[i] + " on " + file);
                        ignore = true;
                        break;
                    }
                }
            }
            return ignore;
        }

        function pythonLocation(callback, locations) {
            if (cachedPythonLocation) {
                if (callback)
                    return callback(cachedPythonLocation);
                else
                    return;
            }

            if (locations === undefined) {
                locations = [
                    "pythonw",
                    "python",
                    "/usr/local/bin/python",
                    "/usr/bin/python",
                ];
                for (var i=26; i<40; i++) {
                    locations.push('\\python' + i + '\\pythonw');
                    locations.push('\\Python' + i + '\\pythonw');
                }
            }

            if (locations.length == 0) {
                if (callback)
                    callback(null);
                return;
            }

            var args = ['--version'];
            var location = locations[0];

            proc.execFile(location, {args:args}, function(error, stdout, stderr) {
                if (!error) {
                    cachedPythonLocation = location;
                    if (callback)
                        callback(location);
                } else {
                    locations.splice(0, 1);
                    pythonLocation(callback, locations);
                }
            });

        }

        function coreRelativeLocation() {
            return ".c9/lib/wakatime-core/wakatime-master/wakatime/cli.py";
        }

        function obfuscateKey(key) {
            var newKey = "";
            if (key) {
                newKey = key;
                if (key.length > 4)
                    newKey = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXX" + key.substring(key.length - 4);
            }
            return newKey;
        }

        function obfuscateKeyFromArguments(args) {
            var newCmds = [];
            var lastCmd = "";
            for (var i = 0; i<args.length; i++) {
                if (lastCmd == "--key")
                    newCmds.push(obfuscateKey(args[i]));
                else
                    newCmds.push(args[i]);
                lastCmd = args[i];
            }
            return newCmds;
        }

        function handleActivity(file, cursorpos, isWrite) {
            if (!file)
                return;
            if (file.indexOf('~') == 0) {
                file = c9.home + file.substring(1);
            }
            var time = Date.now();
            if (isWrite || enoughTimePassed(time) || lastFile != file) {
                if (fileIsIgnored(file))
                    return;
                sendHeartbeat(file, time, cursorpos, isWrite);
            }
        }

        function sendHeartbeat(file, time, cursorpos, isWrite) {
            pythonLocation(function(python) {
                if (!python)
                    return;
                var debug = settings.get("user/wakatime/@debug");
                getApiKey(function(apiKey) {
                    if (!isValidApiKey(apiKey))
                        return;
                    var userAgent = 'c9/' + c9Version + ' c9-wakatime/' + pluginVersion;
                    var core = c9.home + '/' + coreRelativeLocation();
                    var args = [core, '--file', file, '--key', apiKey, '--plugin', userAgent];
                    if (isWrite)
                        args.push('--write');
                    if (debug)
                        args.push('--verbose');
                    if (cursorpos) {
                        args.push('--cursorpos');
                        args.push(cursorpos);
                    }
                    if (debug) {
                        var clone = args.slice(0);
                        clone.unshift(python);
                        console.log('Sending heartbeat to wakatime-core: ' + obfuscateKeyFromArguments(clone).join(' '));
                    }
                    proc.execFile(python, {args:args}, function(error, stdout, stderr) {
                        if (error) {
                            if (stderr && stderr != '')
                                console.warn(stderr);
                            if (stdout && stdout != '')
                                console.warn(stdout);
                            if (error.code == 102)
                                console.warn('Warning: api error (102); Check your ~/.wakatime.log file for more details.');
                            else if (error.code == 103)
                                console.warn('Warning: config parsing error (103); Check your ~/.wakatime.log file for more details.');
                            else
                                console.warn(error);
                        }
                    });
                    lastTime = time;
                    lastFile = file;
                });
            });
        }

        /***** Lifecycle *****/

        plugin.on("load", function() {
            init();
        });
        plugin.on("unload", function() {
        });

        /***** Register and define API *****/
        plugin.freezePublicAPI({
            _events: [
            ],
        });

        register(null, {
            "wakatime": plugin
        });
    }
});
<|endoftext|>


<commit_before>'use strict';

class Player extends Phaser.Sprite {

  constructor(game, x, y) {
    super(game, x, y, 'character');
    this.anchor.set(0.5);
    this.game.physics.arcade.enable(this);
    this.body.collideWorldBounds = true;
    this.animations.add('up', [105, 106, 107, 108, 109, 110, 111, 112], 10, true);
    this.animations.add('left', [118, 119, 120, 121, 122, 123, 124, 125], 10, true);
    this.animations.add('down', [131, 132, 133, 134, 135, 136, 137, 138], 10, true);
    this.animations.add('right', [144, 145, 146, 147, 148, 149, 150, 151], 10, true);
    game.add.existing(this);
    this.leftFootstepSound = game.add.audio('leftFootstep');
    this.rightFootstepSound = game.add.audio('rightFootstep');
  }

  enableInput(cursors) {
    // To determine whether to restart the sound or not.
    this.walkingSoundIsPlaying = false;

    Object.keys(cursors).forEach((key) => {
      cursors[key].onDown.add(() => {
        if (!this.walkingSoundIsPlaying) {
          this.isWalking = true;
          this.startWalkingSound();
        }
      });
    });
  }

  disableInput(cursors) {
    Object.keys(cursors).forEach((key) => {
      cursors[key].onDown.removeAll();
    });
  }

  startWalkingSound() {
    this.leftFootstepSound.play();
    this.walkingSoundIsPlaying = true;

    this.leftFootstepSound.onStop.addOnce(() => {
      this.walkingSoundIsPlaying = false;

      if (this.isWalking) {
        this.rightFootstepSound.play();
        this.walkingSoundIsPlaying = true;

        this.rightFootstepSound.onStop.addOnce(() => {
          this.walkingSoundIsPlaying = false;

          if (this.isWalking) {
            this.startWalkingSound();
          }
        });
      }
    });
  }

  stopWalkingSound() {
    this.isWalking = false;
  }

  resetVelocity() {
    this.body.velocity.x = 0;
    this.body.velocity.y = 0;
  }

  walkLeft() {
    this.body.velocity.x = -1;
    this.animations.play('left');
  }

  walkRight() {
    this.body.velocity.x = 1;
    this.animations.play('right');
  }

  walkUp() {
    this.body.velocity.y = -1;
    this.animations.play('up');
  }

  walkDown() {
    this.body.velocity.y = 1;
    this.animations.play('down');
  }

  normalizeVelocity() {
    this.body.velocity.normalize().multiply(250, 250);
  }

  stop() {
    this.resetVelocity();
    this.animations.stop();
    this.stopWalkingSound();
  }
}

module.exports = Player;
<commit_msg>Default to a forward facing stance<commit_after>'use strict';

class Player extends Phaser.Sprite {

  constructor(game, x, y) {
    super(game, x, y, 'character', 130);
    this.anchor.set(0.5);
    this.game.physics.arcade.enable(this);
    this.body.collideWorldBounds = true;
    this.animations.add('up', [105, 106, 107, 108, 109, 110, 111, 112], 10, true);
    this.animations.add('left', [118, 119, 120, 121, 122, 123, 124, 125], 10, true);
    this.animations.add('down', [131, 132, 133, 134, 135, 136, 137, 138], 10, true);
    this.animations.add('right', [144, 145, 146, 147, 148, 149, 150, 151], 10, true);
    game.add.existing(this);
    this.leftFootstepSound = game.add.audio('leftFootstep');
    this.rightFootstepSound = game.add.audio('rightFootstep');
  }

  enableInput(cursors) {
    // To determine whether to restart the sound or not.
    this.walkingSoundIsPlaying = false;

    Object.keys(cursors).forEach((key) => {
      cursors[key].onDown.add(() => {
        if (!this.walkingSoundIsPlaying) {
          this.isWalking = true;
          this.startWalkingSound();
        }
      });
    });
  }

  disableInput(cursors) {
    Object.keys(cursors).forEach((key) => {
      cursors[key].onDown.removeAll();
    });
  }

  startWalkingSound() {
    this.leftFootstepSound.play();
    this.walkingSoundIsPlaying = true;

    this.leftFootstepSound.onStop.addOnce(() => {
      this.walkingSoundIsPlaying = false;

      if (this.isWalking) {
        this.rightFootstepSound.play();
        this.walkingSoundIsPlaying = true;

        this.rightFootstepSound.onStop.addOnce(() => {
          this.walkingSoundIsPlaying = false;

          if (this.isWalking) {
            this.startWalkingSound();
          }
        });
      }
    });
  }

  stopWalkingSound() {
    this.isWalking = false;
  }

  resetVelocity() {
    this.body.velocity.x = 0;
    this.body.velocity.y = 0;
  }

  walkLeft() {
    this.body.velocity.x = -1;
    this.animations.play('left');
  }

  walkRight() {
    this.body.velocity.x = 1;
    this.animations.play('right');
  }

  walkUp() {
    this.body.velocity.y = -1;
    this.animations.play('up');
  }

  walkDown() {
    this.body.velocity.y = 1;
    this.animations.play('down');
  }

  normalizeVelocity() {
    this.body.velocity.normalize().multiply(250, 250);
  }

  stop() {
    this.resetVelocity();
    this.stopWalkingSound();
    this.frame = 130;
  }
}

module.exports = Player;
<|endoftext|>


<commit_before>import Feed from '../models/feed'
import Beer from '../models/beer'
import Pub from '../models/pub'
import User from '../models/user'

export function getFeedList (req) {
  let findFeeds = Feed.find({is_ok: 1}).sort({crt_dt: -1})

  if (!req.query.type || req.query.type !== 'all') {
    const page = (!req.query.page || req.query.page <= 0)
      ? 1 : req.query.page
    const count = (!req.query.count || req.query.count <= 0)
      ? 20 : req.query.count
    findFeeds = findFeeds.limit(Number(count)).skip((page-1) * count)
  }

  return findFeeds.populate('beers', 'pub', 'user').exec((err, feeds) => {
    if (err) {
      return null
    }
    return feeds
  })
}

/**
  NOTE: 피드 저장 (저장 전에 이미지들 부터 저장 후 진행)
**/
export function insertFeed (req, next) {

}

function _saveImages (req, next) {

}

/**
  NOTE: 피드 수정
  TODO: (저장 전에 기존 이미지들 및 레퍼런스 삭제)
**/
export function updateFeed (req, next) {

}

/**
  NOTE: 피드 삭제 (삭제 전에 기존 이미지들 및 레퍼런스 삭제)
**/
export function deleteFeed (feed_id, next) {

}
<commit_msg>append func to upload feed<commit_after>import Feed from '../models/feed'
import Beer from '../models/beer'
import Pub from '../models/pub'
import User from '../models/user'
import FeedImage from  '../models/feedImage'

export function getFeedList (req) {
  let findFeeds = Feed.find({is_ok: 1}).sort({crt_dt: -1})

  if (!req.query.type || req.query.type !== 'all') {
    const page = (!req.query.page || req.query.page <= 0)
      ? 1 : req.query.page
    const count = (!req.query.count || req.query.count <= 0)
      ? 20 : req.query.count
    findFeeds = findFeeds.limit(Number(count)).skip((page-1) * count)
  }

  return findFeeds.populate('beers', 'pub', 'user').exec((err, feeds) => {
    if (err) {
      return null
    }
    return feeds
  })
}

/**
  NOTE: 피드 저장 (저장 전에 이미지들 부터 저장 후 진행)
**/
export async function insertFeed (req) {
  let newFeed = new Feed()
  newFeed.beers = await Beer.find({is_ok: 1, _id: {
    $in: req.body.beer_ids
  }}).exec((err, beers) => {
    if (err) {
      return null
    }
    return beers
  })
  newFeed.pub = await Pub.findOne({is_ok: 1,
    _id: req.body.pub_id}).exec((err, pub) => {
    if (err) {
      return null
    }
    return pub
  })
  newFeed.user = await User.findOne({is_ok: 1,
    id: req.query.id, platform: req.query.platform}).exec((err, user) => {
    if (err) {
      return null
    }
    return user
  })
  newFeed.context = req.body.context || ''
  newFeed.is_ok = 1
  newFeed.crt_dt = new Date()
  newFeed.udt_dt = newFeed.crt_dt
  const savedFeed = await newFeed.save((err, savedFeed) => {
    if (err) {
      return null
    }
    _saveImages(req.files.feedImages, savedFeed._id)
    return savedFeed
  })
  return Feed.populate(savedFeed, [
    {path: 'beers', model: 'Beer'},
    {path: 'pub', model: 'Pub'},
    {path: 'user', model: 'User'}
  ], (err, feed) => {
    if (err) {
      return null
    }
    return feed
  })
}

function _saveImages (feedImages, feedId) {
  if (!feedImages) {
    return null
  }
  return feedImages.map(async (v, k) => {
    let newImage = new FeedImage()
    newImage.feed = await Feed.findOne({is_ok: 1, _id: feedId})
    newImage.image = 'feeds/' + v.filename
    newImage.is_ok = 1
    newImage.crt_dt = new Date()
    newImage.udt_dt = newImage.crt_dt
    await newImage.save((err, image) => {
      if (err) {
        return null
      }
    })
    return newImage
  })
}

/**
  NOTE: 피드 수정
  TODO: (저장 전에 기존 이미지들 및 레퍼런스 삭제)
**/
export function updateFeed (req) {

}

/**
  NOTE: 피드 삭제 (삭제 전에 기존 이미지들 및 레퍼런스 삭제)
**/
export function deleteFeed (feedId) {

}
<|endoftext|>


<commit_before>const requestStream = require('./request.js')
const FeedParser = require('feedparser')
const fileOps = require('../util/fileOps.js')
const sqlCmds = require('./sql/commands.js')
const currentGuilds = require('../util/storage').currentGuilds

exports.addToDb = function (con, articleList, rssName, callback, customTitle) {
  const totalArticles = articleList.length
  let processedArticles = 0

  function getArticleId (article) {
    let equalGuids = (articleList.length > 1) // default to true for most feeds
    if (equalGuids && articleList[0].guid) {
      for (var x in articleList) {
        if (parseInt(x, 10) > 0 && articleList[x].guid !== articleList[x - 1].guid) equalGuids = false
      }
    }

    // If all articles have the same guids, fall back to title, and if no title, fall back to pubdate
    if ((!article.guid || equalGuids) && article.title) return article.title
    if ((!article.guid || equalGuids) && !article.title && article.pubdate && article.pubdate.toString() !== 'Invalid Date') return article.pubdate
    return article.guid
  }

  createTable()

  function createTable () {
    sqlCmds.createTable(con, rssName, function (err, rows) {
      if (err) return callback({type: 'database', content: err})
      if (articleList.length === 0) return incrementProgress(true)
      for (var x in articleList) {
        insertIntoTable({
          id: getArticleId(articleList[x]),
          title: articleList[x].title
        })
      }
    })
  }

  function insertIntoTable (articleInfo) {
    sqlCmds.insert(con, rssName, articleInfo, function (err, res) {
      if (err) return callback({type: 'database', content: err})
      incrementProgress()
    })
  }

  function incrementProgress (emptyFeed) {
    if (!emptyFeed) processedArticles++
    else return callback()
    if (processedArticles === totalArticles) callback()
  }
}

exports.addNewFeed = function (con, link, channel, cookies, callback, customTitle) {
  const feedparser = new FeedParser()
  const articleList = []
  let errored = false // Sometimes feedparser emits error twice

  while (true) { // Make links uniform
    if (link.endsWith('/')) link = link.slice(0, -1)
    if (link.endsWith('?')) link = link.slice(0, -1)

    if (!link.endsWith('/') && !link.endsWith('?')) break
  }

  link += '/' // Some links won't work without the trailing slash

  requestStream(link, cookies, feedparser, function (err) {
    if (err && errored === false) {
      errored = true
      return callback({type: 'request', content: err})
    }
  })

  feedparser.on('error', function (err) {
    feedparser.removeAllListeners('end')
    if (err && errored === false) {
      errored = true
      return callback({type: 'feedparser', content: err})
    }
  })

  feedparser.on('readable', function () {
    let item
    while (item = this.read()) {
      articleList.push(item)
    }
  })

  feedparser.on('end', function () {
    if (errored) return

    const randomNum = Math.floor((Math.random() * 99999999999) + 1)
    let metaLink = ''
    if (articleList[0]) metaLink = (articleList[0].meta.link) ? articleList[0].meta.link : (articleList[0].meta.title) ? articleList[0].meta.title : `random_${Math.floor((Math.random() * 99999) + 1)}`
    else metaLink = `random_${Math.floor((Math.random() * 99999) + 1)}`

    let rssName = `${randomNum}_${metaLink}`

    // MySQL table names have a limit of 64 char
    if (rssName.length >= 64) rssName = rssName.substr(0, 64)
    rssName = rssName.replace(/-|\?/g, '').replace(/\./g, '') // Remove question marks to prevent sql from auto-escaping, along with periods

    exports.addToDb(con, articleList, rssName, function (err) {
      if (err) return callback(err)
      addToConfig()
    })

    function addToConfig () {
      let metaTitle = customTitle || (articleList[0] && articleList[0].meta.title) ? articleList[0].meta.title : 'Untitled'

      if (articleList[0] && articleList[0].guid && articleList[0].guid.startsWith('yt:video')) metaTitle = `Youtube - ${articleList[0].meta.title}`
      else if (articleList[0] && articleList[0].meta.link && articleList[0].meta.link.includes('reddit')) metaTitle = `Reddit - ${articleList[0].meta.title}`

      if (metaTitle.length > 200) metaTitle = metaTitle.slice(0, 200) + ' [...]'

      var guildRss
      if (currentGuilds.has(channel.guild.id)) {
        guildRss = currentGuilds.get(channel.guild.id)
        if (!guildRss.sources) guildRss.sources = {}

        var rssList = guildRss.sources
        rssList[rssName] = {
          title: metaTitle,
          link: link,
          channel: channel.id
        }

        if (cookies) rssList[rssName].advanced = {cookies: cookies}
      } else {
        guildRss = {
          name: channel.guild.name,
          id: channel.guild.id,
          sources: {}
        }
        guildRss.sources[rssName] = {
          title: metaTitle,
          link: link,
          channel: channel.id
        }
        if (cookies) guildRss.sources[rssName].advanced = {cookies: cookies}

        currentGuilds.set(channel.guild.id, guildRss)
      }

      fileOps.updateFile(channel.guild.id, guildRss)
      callback(null, metaTitle, rssName)
    }
  })
}
<commit_msg>Removed link uniforming<commit_after>const requestStream = require('./request.js')
const FeedParser = require('feedparser')
const fileOps = require('../util/fileOps.js')
const sqlCmds = require('./sql/commands.js')
const currentGuilds = require('../util/storage').currentGuilds

exports.addToDb = function (con, articleList, rssName, callback, customTitle) {
  const totalArticles = articleList.length
  let processedArticles = 0

  function getArticleId (article) {
    let equalGuids = (articleList.length > 1) // default to true for most feeds
    if (equalGuids && articleList[0].guid) {
      for (var x in articleList) {
        if (parseInt(x, 10) > 0 && articleList[x].guid !== articleList[x - 1].guid) equalGuids = false
      }
    }

    // If all articles have the same guids, fall back to title, and if no title, fall back to pubdate
    if ((!article.guid || equalGuids) && article.title) return article.title
    if ((!article.guid || equalGuids) && !article.title && article.pubdate && article.pubdate.toString() !== 'Invalid Date') return article.pubdate
    return article.guid
  }

  createTable()

  function createTable () {
    sqlCmds.createTable(con, rssName, function (err, rows) {
      if (err) return callback({type: 'database', content: err})
      if (articleList.length === 0) return incrementProgress(true)
      for (var x in articleList) {
        insertIntoTable({
          id: getArticleId(articleList[x]),
          title: articleList[x].title
        })
      }
    })
  }

  function insertIntoTable (articleInfo) {
    sqlCmds.insert(con, rssName, articleInfo, function (err, res) {
      if (err) return callback({type: 'database', content: err})
      incrementProgress()
    })
  }

  function incrementProgress (emptyFeed) {
    if (!emptyFeed) processedArticles++
    else return callback()
    if (processedArticles === totalArticles) callback()
  }
}

exports.addNewFeed = function (con, link, channel, cookies, callback, customTitle) {
  const feedparser = new FeedParser()
  const articleList = []
  let errored = false // Sometimes feedparser emits error twice

  requestStream(link, cookies, feedparser, function (err) {
    if (err && errored === false) {
      errored = true
      return callback({type: 'request', content: err})
    }
  })

  feedparser.on('error', function (err) {
    feedparser.removeAllListeners('end')
    if (err && errored === false) {
      errored = true
      return callback({type: 'feedparser', content: err})
    }
  })

  feedparser.on('readable', function () {
    let item
    while (item = this.read()) {
      articleList.push(item)
    }
  })

  feedparser.on('end', function () {
    if (errored) return

    const randomNum = Math.floor((Math.random() * 99999999999) + 1)
    let metaLink = ''
    if (articleList[0]) metaLink = (articleList[0].meta.link) ? articleList[0].meta.link : (articleList[0].meta.title) ? articleList[0].meta.title : `random_${Math.floor((Math.random() * 99999) + 1)}`
    else metaLink = `random_${Math.floor((Math.random() * 99999) + 1)}`

    let rssName = `${randomNum}_${metaLink}`

    // MySQL table names have a limit of 64 char
    if (rssName.length >= 64) rssName = rssName.substr(0, 64)
    rssName = rssName.replace(/-|\?/g, '').replace(/\./g, '') // Remove question marks to prevent sql from auto-escaping, along with periods

    exports.addToDb(con, articleList, rssName, function (err) {
      if (err) return callback(err)
      addToConfig()
    })

    function addToConfig () {
      let metaTitle = customTitle || (articleList[0] && articleList[0].meta.title) ? articleList[0].meta.title : 'Untitled'

      if (articleList[0] && articleList[0].guid && articleList[0].guid.startsWith('yt:video')) metaTitle = `Youtube - ${articleList[0].meta.title}`
      else if (articleList[0] && articleList[0].meta.link && articleList[0].meta.link.includes('reddit')) metaTitle = `Reddit - ${articleList[0].meta.title}`

      if (metaTitle.length > 200) metaTitle = metaTitle.slice(0, 200) + ' [...]'

      var guildRss
      if (currentGuilds.has(channel.guild.id)) {
        guildRss = currentGuilds.get(channel.guild.id)
        if (!guildRss.sources) guildRss.sources = {}

        var rssList = guildRss.sources
        rssList[rssName] = {
          title: metaTitle,
          link: link,
          channel: channel.id
        }

        if (cookies) rssList[rssName].advanced = {cookies: cookies}
      } else {
        guildRss = {
          name: channel.guild.name,
          id: channel.guild.id,
          sources: {}
        }
        guildRss.sources[rssName] = {
          title: metaTitle,
          link: link,
          channel: channel.id
        }
        if (cookies) guildRss.sources[rssName].advanced = {cookies: cookies}

        currentGuilds.set(channel.guild.id, guildRss)
      }

      fileOps.updateFile(channel.guild.id, guildRss)
      callback(null, metaTitle, rssName)
    }
  })
}
<|endoftext|>


<commit_before>import Ember from 'ember';
import layout from '../templates/components/tag-input';

const KEY_CODES = {
  BACK_BUTTON: 8,
  COMMA: 188,
  ENTER: 13,
  SPACE: 32
};

export default Ember.Component.extend({
  layout,

  classNames: ['emberTagInput'],

  tagName: 'ul',

  tags: Ember.A(),

  didInsertElement() {
    let container = this.$(),
      newTagInput = this.$('.js-ember-tag-input-new');

    container.on('click', (e) => {
      newTagInput.focus();
    });

    newTagInput.on('keydown', (e) => {
      let tags = this.get('tags'),
        newTagInputVal = newTagInput.val().trim();

      if (e.which === KEY_CODES.COMMA || e.which === KEY_CODES.SPACE || e.which === KEY_CODES.ENTER) {
        if (newTagInputVal.length > 0) {
          let onTagAdd = this.get('onTagAdd');

          tags.pushObject(newTagInputVal);
          newTagInput.val('');

          if (onTagAdd) {
            onTagAdd(newTagInputVal);
          }

          e.preventDefault();
        }
      } else if (e.which === KEY_CODES.BACK_BUTTON) {
        if (newTagInputVal.length === 0) {
          let onTagRemove = this.get('onTagRemove'),
            removedTag = tags.popObject();

          if (onTagRemove) {
            onTagRemove(removedTag);
          }
        }
      }
    });

    newTagInput.on('blur', () => {
      let tags = this.get('tags'),
        newTagInputVal = newTagInput.val().trim();

      if (newTagInputVal.length > 0) {
        let onTagAdd = this.get('onTagAdd');

        tags.pushObject(newTagInputVal);

        if (onTagAdd) {
          onTagAdd(newTagInputVal);
        }
      }

      newTagInput.val('');
    });
  }
});
<commit_msg>Fixing lint issue<commit_after>import Ember from 'ember';
import layout from '../templates/components/tag-input';

const KEY_CODES = {
  BACK_BUTTON: 8,
  COMMA: 188,
  ENTER: 13,
  SPACE: 32
};

export default Ember.Component.extend({
  layout,

  classNames: ['emberTagInput'],

  tagName: 'ul',

  tags: Ember.A(),

  didInsertElement() {
    let container = this.$(),
      newTagInput = this.$('.js-ember-tag-input-new');

    container.on('click', () => {
      newTagInput.focus();
    });

    newTagInput.on('keydown', (e) => {
      let tags = this.get('tags'),
        newTagInputVal = newTagInput.val().trim();

      if (e.which === KEY_CODES.COMMA || e.which === KEY_CODES.SPACE || e.which === KEY_CODES.ENTER) {
        if (newTagInputVal.length > 0) {
          let onTagAdd = this.get('onTagAdd');

          tags.pushObject(newTagInputVal);
          newTagInput.val('');

          if (onTagAdd) {
            onTagAdd(newTagInputVal);
          }

          e.preventDefault();
        }
      } else if (e.which === KEY_CODES.BACK_BUTTON) {
        if (newTagInputVal.length === 0) {
          let onTagRemove = this.get('onTagRemove'),
            removedTag = tags.popObject();

          if (onTagRemove) {
            onTagRemove(removedTag);
          }
        }
      }
    });

    newTagInput.on('blur', () => {
      let tags = this.get('tags'),
        newTagInputVal = newTagInput.val().trim();

      if (newTagInputVal.length > 0) {
        let onTagAdd = this.get('onTagAdd');

        tags.pushObject(newTagInputVal);

        if (onTagAdd) {
          onTagAdd(newTagInputVal);
        }
      }

      newTagInput.val('');
    });
  }
});
<|endoftext|>


<commit_before>/*
 * grunt-scaffold
 * https://github.com/alex-seville/scaffold.js
 *
 * Copyright (c) 2013 alex-seville
 * Licensed under the MIT license.
 */

'use strict';

var publicjs = require("public.js");
var _ = require("underscore");

module.exports = function(grunt) {

  // Please see the Grunt documentation for more information regarding task
  // creation: http://gruntjs.com/creating-tasks

  grunt.registerMultiTask('public-js', 'Your task description goes here.', function() {
    // Merge task-specific and/or target-specific options with these defaults.
    var options = this.options({
      lintOptions: {}
    });

    if (!options.type){
      grunt.log.warn('You must provide a task type.');
      return false;
    }

    if (options.type === 'scaffold'){
      scaffolds.call(this,options,this.files);
    }else if (options.type === 'lint'){
      lint.call(this,options,this.files);
    }

  });

  function scaffolds(options,files){
    if (!options.template){
      grunt.log.warn('You must provide a template.');
      return false;
    }

    // Iterate over all specified file groups.
    files.forEach(function(f) {
      // Concat specified files.
      var src = f.src.filter(function(filepath) {
        // Warn on and remove invalid source files (if nonull was set).
        if (!grunt.file.exists(filepath)) {
          grunt.log.warn('Source file "' + filepath + '" not found.');
          return false;
        } else {
          return true;
        }
      }).map(function(filepath) {
        // Read file source.
        return grunt.file.read(filepath);
      });

      var output;

      if (src.length === 1 && !options.source ){
        output = publicjs.getPublic(src[0],{
          tree:true
        });
      }else{
        if (!options.source){
          grunt.log.warn('You must provide a configuration option for the main source file.');
          return false;
        }
        output = publicjs.getPublic(grunt.file.read(options.source),{
            dependencies: src,
            tree:true
          });
      }

      var template = grunt.file.read(options.template);
      var unitTest = _.template(template);
      var testStr = unitTest({data: output});
      grunt.file.write(f.dest,testStr);
      // Print a success message.
      grunt.log.writeln('Created test scaffolds');
    });
  }

  function lint(options,files){
    var errors=[];
    // Iterate over all specified file groups.
    files.forEach(function(f) {
      // Concat specified files.
      var src = f.src.filter(function(filepath) {
        // Warn on and remove invalid source files (if nonull was set).
        if (!grunt.file.exists(filepath)) {
          grunt.log.warn('Source file "' + filepath + '" not found.');
          return false;
        } else {
          return true;
        }
      }).map(function(filepath) {
        // Read file source.
        return grunt.file.read(filepath);
      });

      var output, dest = grunt.file.read(f.dest);

      var errorCallback = function(name,details){
        errors.push("Error when accessing "+details+"."+name+" in "+ f.dest);
      };

        if (src.length > 0 ){
          output = publicjs.getPublic(dest,{
            dependencies: src,
            errorCallback: errorCallback,
            tree:true
          });
        }else{
          output = publicjs.getPublic(dest,{
            errorCallback: errorCallback,
            tree:true
          });
        }

        //check exportOnly
        if (options.lintOptions.exportOnly){
          if (options.lintOptions.exportOnly.length === 0 && output.length !== 0){
            errors.push("Expected nothing to be exported, but saw: "+output.map(function(o){ return o.name; }));
          }else if (options.lintOptions.exportOnly.length > 0 && output.length === 0){
            errors.push("Nothing was exported.");
          }else{
            //we have exports, and we expect exports
            //we need to make sure that all expected were
            //exported and that only expected were exported
            //we should take all the leaf nodes and record their path value
            //then compare that against the expected array.
            //any results left, or any non matches should be recorded as an error.
            var getLeaves = function(curr){
              var ret=[];
              curr.forEach(function(c){
                if(c){
                  ret.push(c.currentPath);
                }
                if (c.children){
                  ret = ret.concat(getLeaves(c.children));
                }
                if (c.prototypes){
                  ret = ret.concat(getLeaves(c.prototypes));
                }
              });
              return ret;
            };
            var paths = getLeaves(output);
            options.lintOptions.exportOnly.forEach(function(eo){
              if (paths.indexOf(eo) > -1){

              }
            });
          }
        }
    });

    //display result
    if (errors.length > 0){
        grunt.log.warn("Public-lint error"+(errors.length > 1 ? "s" : "") + ": ");
        errors.forEach(function(e){
          grunt.log.warn(e);
        })
        grunt.fatal("Public-lint failed.");
      }
      grunt.log.writeln('Public-lint completed successfully.');
  }

};
<commit_msg>Update grunt-public.js<commit_after>/*
 * grunt-scaffold
 * https://github.com/alex-seville/scaffold.js
 *
 * Copyright (c) 2013 alex-seville
 * Licensed under the MIT license.
 */

'use strict';

var publicjs = require("public.js");
var _ = require("underscore");

module.exports = function(grunt) {

  // Please see the Grunt documentation for more information regarding task
  // creation: http://gruntjs.com/creating-tasks

  grunt.registerMultiTask('public-js', 'Your task description goes here.', function() {
    // Merge task-specific and/or target-specific options with these defaults.
    var options = this.options({
      lintOptions: {}
    });

    if (!options.type){
      grunt.log.warn('You must provide a task type.');
      return false;
    }

    if (options.type === 'scaffold'){
      scaffolds.call(this,options,this.files);
    }else if (options.type === 'lint'){
      lint.call(this,options,this.files);
    }

  });

  function scaffolds(options,files){
    if (!options.template){
      grunt.log.warn('You must provide a template.');
      return false;
    }

    // Iterate over all specified file groups.
    files.forEach(function(f) {
      // Concat specified files.
      var src = f.src.filter(function(filepath) {
        // Warn on and remove invalid source files (if nonull was set).
        if (!grunt.file.exists(filepath)) {
          grunt.log.warn('Source file "' + filepath + '" not found.');
          return false;
        } else {
          return true;
        }
      }).map(function(filepath) {
        // Read file source.
        return grunt.file.read(filepath);
      });

      var output;

      if (src.length === 1 && !options.source ){
        output = publicjs.getPublic(src[0],{
          tree:true
        });
      }else{
        if (!options.source){
          grunt.log.warn('You must provide a configuration option for the main source file.');
          return false;
        }
        output = publicjs.getPublic(grunt.file.read(options.source),{
            dependencies: src,
            tree:true
          });
      }

      var template = grunt.file.read(options.template);
      var unitTest = _.template(template);
      var testStr = unitTest({data: output});
      grunt.file.write(f.dest,testStr);
      // Print a success message.
      grunt.log.writeln('Created test scaffolds');
    });
  }

  function lint(options,files){
    var errors=[];
    // Iterate over all specified file groups.
    files.forEach(function(f) {
      // Concat specified files.
      var src = f.src.filter(function(filepath) {
        // Warn on and remove invalid source files (if nonull was set).
        if (!grunt.file.exists(filepath)) {
          grunt.log.warn('Source file "' + filepath + '" not found.');
          return false;
        } else {
          return true;
        }
      }).map(function(filepath) {
        // Read file source.
        return grunt.file.read(filepath);
      });

      var output, dest = grunt.file.read(f.dest);

      var errorCallback = function(name,details){
        errors.push("Error when accessing "+details+"."+name+" in "+ f.dest);
      };

        if (src.length > 0 ){
          output = publicjs.getPublic(dest,{
            dependencies: src,
            errorCallback: errorCallback,
            tree:true
          });
        }else{
          output = publicjs.getPublic(dest,{
            errorCallback: errorCallback,
            tree:true
          });
        }

        //check exportOnly
        if (options.lintOptions.exportOnly){
          if (options.lintOptions.exportOnly.length === 0 && output.length !== 0){
            errors.push("Expected nothing to be exported, but saw: "+output.map(function(o){ return o.name; }));
          }else if (options.lintOptions.exportOnly.length > 0 && output.length === 0){
            errors.push("Nothing was exported.");
          }else{
            //we have exports, and we expect exports
            //we need to make sure that all expected were
            //exported and that only expected were exported
            //we should take all the leaf nodes and record their path value
            //then compare that against the expected array.
            //any results left, or any non matches should be recorded as an error.
            var getLeaves = function(curr){
              var ret=[];
              curr.forEach(function(c){
                if(c){
                  ret.push(c.currentPath);
                }
                if (c.children){
                  ret = ret.concat(getLeaves(c.children));
                }
                if (c.prototypes){
                  ret = ret.concat(getLeaves(c.prototypes));
                }
              });
              return ret;
            };
            var paths = getLeaves(output);
            var onlys = options.lintOptions.exportOnly.slice(0);
            options.lintOptions.exportOnly.forEach(function(eo){
              var found = onlys.indexOf(eo);
              if (found > -1){
                paths.splice(found,1);
                onlys.splice(onlys.indexOf(eo),1);
              }
            });
            paths.forEach(function(p){
              errors.push("Didn't expect "+p+" to be exported in "+f.dest);
            });
            onlys.forEach(function(o){
              errors.push("Expected "+o+ " to be exported but it was not found in "+f.dest);
            });
          }
        }
    });

    //display result
    if (errors.length > 0){
        grunt.log.warn("Public-lint error"+(errors.length > 1 ? "s" : "") + ": ");
        errors.forEach(function(e){
          grunt.log.warn(e);
        })
        grunt.fatal("Public-lint failed.");
      }
      grunt.log.writeln('Public-lint completed successfully.');
  }

};
<|endoftext|>