<commit_before>
// SmoothScroll v0.9.1
// Licensed under the terms of the MIT license.

// People involved
// - Balazs Galambosi: maintainer (CHANGELOG.txt)
// - Patrick Brunner (patrickb1991@gmail.com)
// - Michael Herf: Pulse Algorithm
// - Frank Yan: Direction Switching Fixes
// - Ismael Barros: Keyboard Fixes

// Frame Variables
var frame         = false;
var noscrollframe = false;
var lastYOffset   = 0;
var lastXOffset   = 0;

// Scroll Variables (tweakable)
var framerate = 50;  // [Hz]
var animtime  = 400; // [px]
var stepsize  = 120; // [px]

// Pulse (less tweakable)
// ratio of 'tail' to 'acceleration'
var pulseAlgorithm = true;
var pulseScale     = 8;
var pulseNormalize = 1;

// Keyboard Settings
var keyboardsupport = true;
var disableKeyboard = false;
var arrowscroll     = 50; // [px]

// Excluded pages
var exclude = "";

// Arrays of timeouts
var up   = [];
var down = [];

// Other Variables
var scrolls;
var deltaX = 0;
var deltaY = 0;
var initdone = false;
var lastScrollTop  = 1337; // ad-hoc
var lastScrollLeft = 1337; // ad-hoc

var key = { up: 38, down: 40, spacebar: 32, pageup: 33, pagedown: 34, end: 35, home: 36 };

/***********************************************
 * SETTINGS
 ***********************************************/

var port = chrome.extension.connect({
    name: "smoothscroll"
});
port.onMessage.addListener(function (settings) {

    // NOTE: + converts to {Number}
    framerate = +settings.framerate;
    animtime  = +settings.animtime;
    stepsize  = +settings.scrollsz;
    exclude   = settings.exclude;
    pulseAlgorithm  = (settings.pulseAlgorithm == "true");
    pulseScale      = +settings.pulseScale;
    keyboardsupport = (settings.keyboardsupport == "true");
    arrowscroll     = +settings.arrscroll;

    scrolls = setupScrolls();
    computePulseScale();

    // it seems that sometimes settings come late
    // and we need to test again for excluded pages
    initTest();

    if (keyboardsupport && !disableKeyboard) {
        document.onkeydown = keydown;
    }

    // If extension settings were deleted somehow
    if (!framerate) {
        alert("SmoothScroll: Please restart Chrome");
    }
});

/***********************************************
 * INITIALIZE
 ***********************************************/

/**
 * Tests if smooth scrolling is allowed. Shuts down everything if not.
 */
function initTest() {

    // disable everything by default for built-in PDF Reader,
    // and keyboard support for google reader (spacebar conflict)
    var embed = document.getElementsByTagName('embed')[0];
    if (embed && embed.type === "application/pdf") {
        removeEvent("mousewheel", wheel);
        disableKeyboard = true;
    } else if (document.URL.indexOf("google.com/reader/view") > -1) {
        disableKeyboard = true;
    }

    // disable everything if the page is blacklisted
    if (exclude) {
        var domains = exclude.split(/[,\n] ?/);
        for (var i = domains.length; i--;) {
            if (document.URL.indexOf(domains[i]) > -1) {
                removeEvent("mousewheel", wheel);
                disableKeyboard = true;
                break;
            }
        }
    }

    // disable keyboard support if anything above requested it
    if (disableKeyboard) {
        document.onkeydown = null;
    }
}

/**
 * Fills up the scrolls array with easing values.
 * Uses pulse to make it smooth.
 */
function setupScrolls() {

    scrolls = [];

    var last = 0;
    var frames = Math.floor(framerate * animtime / 1000);

    for (var i = 0; i < frames; i++) {
        // scroll is [0, 1]
        var scroll = (i + 1) / frames;
        // transform [0, 1] -> [0, 1]:
        if (pulseAlgorithm) {
           scroll = pulse(scroll);
        }

        // scale and quantize to int so our pixel difference works:
        var iscroll = Math.floor(stepsize * scroll + 0.99);
        scrolls.push(iscroll - last);
        last = iscroll;
    }

    return scrolls;
}

/**
 * Sets up scrolls array, determines if frames are involved.
 */
function init() {

    var body = document.body;

    initTest();

    if (!scrolls) {
      scrolls = setupScrolls();
    }

    // Checks if this script is running in a frame
    if (top != self) {
        frame = true;
        // document.documentElement ?
        if (body.scrollHeight <= body.clientHeight + 10) {
            noscrollframe = true;
        }
    }

    /**
     * This fixes a bug where the areas left and right
     * to the content does not trigger the onmousewheel
     * event on some pages. Acid3 test is excluded.
     */
    if (document.URL !== "http://acid3.acidtests.org/") {
        var underlay = document.createElement('div');
        underlay.setAttribute( "style",
            "z-index: -1; position:absolute; top:0; left: 0; " +
            "width: 100%; height: " + body.scrollHeight + "px;" );
        body.appendChild(underlay);
    }
    initdone = true;
}

/***********************************************
 * EVENTS
 ***********************************************/

/**
 * Mouse wheel handler.
 * NOTE: function logic should be decomposed.
 * @param {Object} event
 */
function wheel(event) {

    if (!initdone) {
        init();
    }

    deltaX = event.wheelDeltaX || 0;
    deltaY = event.wheelDeltaY || 0;

    // normalize deltas
    deltaX /= 120;
    deltaY /= 120;

    // synaptics seems to send 1 sometimes,
    // and 120 other times (fix)
    if (Math.abs(deltaX) < 0.01) {
        deltaX *= 120;
    }
    if (Math.abs(deltaY) < 0.01) {
        deltaY *= 120;
    }

    var dir = (deltaY > 0) ? up : down;
    var elem = overflowingAncestor(event.target);

    if (!elem || (frame && noscrollframe)) {
        return true;
    }

    scrollArray(elem, dir, -deltaX, -deltaY);
    event.preventDefault();
}

/**
 * Keydown event handler.
 * @param {Object} event
 */
function keydown(event) {

    var target   = event.target;
    var modifier = event.ctrlKey || event.altKey || event.metaKey;

    // do nothing if user is editing text
    // or using a modifier key (except shift)
    if ( isNodeName(target, "input")    ||
         isNodeName(target, "textarea") ||
         target.isContentEditable       ||
         modifier ) {
      return true;
    }
    // spacebar should trigger button press
    if (isNodeName(target, "button") &&
        event.keyCode === key.spacebar) {
      return true;
    }

    var scale, dir, shift;
    var elem = overflowingAncestor(target);

    var clientHeight = target.clientHeight;

    if (elem === document.body) {
        clientHeight = window.innerHeight;
    }

    switch (event.keyCode) {
        case key.up:
            scale = -arrowscroll;
            dir = up;
            break;
        case key.down:
            scale = arrowscroll;
            dir = down;
            break;
        case key.spacebar: // (+ shift)
            shift = event.shiftKey ? 1 : -1;
            scale = -shift * clientHeight * 0.9;
            dir = (shift > 0) ? up : down;
            break;
        case key.pageup:
            scale = -clientHeight * 0.9;
            dir = up;
            break;
        case key.pagedown:
            scale = clientHeight * 0.9;
            dir = down;
            break;
        case key.home:
            scale = -target.scrollTop;
            dir = up;
            break;
        case key.end:
            var damt = target.scrollHeight - target.scrollTop - clientHeight;
            scale = (damt > 0) ? damt : 0;
            dir = down;
            break;
        default:
            return true; // a key we don't care about
    }
    scale /= stepsize;
    scale = (scale > 0) ? Math.ceil(scale) : Math.floor(scale);
    scrollArray(elem, dir, 0, scale);
    event.preventDefault();
}

/***********************************************
 * HELPERS
 ***********************************************/

function addEvent(type, fn, bubble) {
    window.addEventListener(type, fn, (bubble||false));
}

function removeEvent(type, fn, bubble) {
    window.removeEventListener(type, fn, (bubble||false));
}

function isNodeName(el, tag) {
    return el.nodeName.toLowerCase() === tag.toLowerCase();
}

function clearTimeouts(array) {
    while (array.length) {
        clearTimeout(array.pop());
    }
}

function overflowingAncestor(el) {
    var bodyScrollHeight = document.body.scrollHeight;
    do {
        if (bodyScrollHeight === el.scrollHeight) {
            return document.body;
        }
        else if (el.clientHeight + 10 < el.scrollHeight) {
            overflow = getComputedStyle(el, "").getPropertyValue("overflow");
            if (overflow === "scroll" || overflow === "auto") {
                return el;
            }
        }
    } while (el = el.parentNode);
}

/***********************************************
 * PULSE
 ***********************************************/

/**
 * Viscous fluid with a pulse for part and decay for the rest.
 * - Applies a fixed force over an interval (a damped acceleration), and
 * - Lets the exponential bleed away the velocity over a longer interval
 * - Michael Herf, http://stereopsis.com/stopping/
 */
function pulse_(x) {
    var val, start, expx;
    // test
    x = x * pulseScale;
    if (x < 1) { // acceleartion
        val = x - (1 - Math.exp(-x));
    } else {     // tail
        // the previous animation ended here:
        start = Math.exp(-1);
        // simple viscous drag
        x -= 1;
        expx = 1 - Math.exp(-x);
        val = start + (expx * (1 - start));
    }
    return val * pulseNormalize;
}

function computePulseScale() {
    pulseNormalize = 1 / pulse_(1);
}

/**
 * Viscous fluid with a pulse for part and decay for the rest
 */
function pulse(x) {
    if (x >= 1) return 1;
    if (x <= 0) return 0;

    if (pulseNormalize == 1) {
        computePulseScale();
    }
    return pulse_(x);
}

/************************************************
 * SCROLLING
 ************************************************/

/**
 * Pushes scroll actions to a given direction Array.
 */
function scrollArray(elem, dir, multiplyX, multiplyY, delay) {
    delay || (delay = 1000);
    clearTimeouts(dir === up ? down : up);

    function step() {

        var scale = scrolls[i++]; // linear or pulse

        var scrollLeft = elem.scrollLeft;
        var scrollTop  = elem.scrollTop;

        elem.scrollLeft = elem.scrollLeft + (multiplyX * scale);
        elem.scrollTop  = elem.scrollTop  + (multiplyY * scale);

        // scroll left failed (edge)
        if (elem.scrollLeft === scrollLeft) {
            multiplyX = 0;
        }
        // scroll top failed (edge)
        if (elem.scrollTop === scrollTop) {
            multiplyY = 0;
        }
        // if there's nothing left ot do
        if (!multiplyX && !multiplyY) {
            console.log("edge");
            clearTimeouts(dir);
        }

    }
    // populate directions array
    for (var i = scrolls.length; i--;) {
        dir.push(setTimeout(step, i * delay / framerate + 1));
    }
    i = 0; // reset so that step() can increment again
}

addEvent("mousewheel", wheel);
addEvent("DOMContentLoaded", init);
<commit_msg>removed unnecessary globals<commit_after>
// SmoothScroll v0.9.1
// Licensed under the terms of the MIT license.

// People involved
// - Balazs Galambosi: maintainer (CHANGELOG.txt)
// - Patrick Brunner (patrickb1991@gmail.com)
// - Michael Herf: Pulse Algorithm
// - Frank Yan: Direction Switching Fixes
// - Ismael Barros: Keyboard Fixes

// Frame Variables
var frame         = false;
var noscrollframe = false;

// Scroll Variables (tweakable)
var framerate = 50;  // [Hz]
var animtime  = 400; // [px]
var stepsize  = 120; // [px]

// Pulse (less tweakable)
// ratio of 'tail' to 'acceleration'
var pulseAlgorithm = true;
var pulseScale     = 8;
var pulseNormalize = 1;

// Keyboard Settings
var keyboardsupport = true;
var disableKeyboard = false;
var arrowscroll     = 50; // [px]

// Excluded pages
var exclude = "";

// Arrays of timeouts
var up   = [];
var down = [];

// Other Variables
var scrolls;
var deltaX = 0;
var deltaY = 0;
var initdone = false;

var key = { up: 38, down: 40, spacebar: 32, pageup: 33, pagedown: 34, end: 35, home: 36 };

/***********************************************
 * SETTINGS
 ***********************************************/

var port = chrome.extension.connect({
    name: "smoothscroll"
});
port.onMessage.addListener(function (settings) {

    // NOTE: + converts to {Number}
    framerate = +settings.framerate;
    animtime  = +settings.animtime;
    stepsize  = +settings.scrollsz;
    exclude   = settings.exclude;
    pulseAlgorithm  = (settings.pulseAlgorithm == "true");
    pulseScale      = +settings.pulseScale;
    keyboardsupport = (settings.keyboardsupport == "true");
    arrowscroll     = +settings.arrscroll;

    scrolls = setupScrolls();
    computePulseScale();

    // it seems that sometimes settings come late
    // and we need to test again for excluded pages
    initTest();

    if (keyboardsupport && !disableKeyboard) {
        document.onkeydown = keydown;
    }

    // If extension settings were deleted somehow
    if (!framerate) {
        alert("SmoothScroll: Please restart Chrome");
    }
});

/***********************************************
 * INITIALIZE
 ***********************************************/

/**
 * Tests if smooth scrolling is allowed. Shuts down everything if not.
 */
function initTest() {

    // disable everything by default for built-in PDF Reader,
    // and keyboard support for google reader (spacebar conflict)
    var embed = document.getElementsByTagName('embed')[0];
    if (embed && embed.type === "application/pdf") {
        removeEvent("mousewheel", wheel);
        disableKeyboard = true;
    } else if (document.URL.indexOf("google.com/reader/view") > -1) {
        disableKeyboard = true;
    }

    // disable everything if the page is blacklisted
    if (exclude) {
        var domains = exclude.split(/[,\n] ?/);
        for (var i = domains.length; i--;) {
            if (document.URL.indexOf(domains[i]) > -1) {
                removeEvent("mousewheel", wheel);
                disableKeyboard = true;
                break;
            }
        }
    }

    // disable keyboard support if anything above requested it
    if (disableKeyboard) {
        document.onkeydown = null;
    }
}

/**
 * Fills up the scrolls array with easing values.
 * Uses pulse to make it smooth.
 */
function setupScrolls() {

    scrolls = [];

    var last = 0;
    var frames = Math.floor(framerate * animtime / 1000);

    for (var i = 0; i < frames; i++) {
        // scroll is [0, 1]
        var scroll = (i + 1) / frames;
        // transform [0, 1] -> [0, 1]:
        if (pulseAlgorithm) {
           scroll = pulse(scroll);
        }

        // scale and quantize to int so our pixel difference works:
        var iscroll = Math.floor(stepsize * scroll + 0.99);
        scrolls.push(iscroll - last);
        last = iscroll;
    }

    return scrolls;
}

/**
 * Sets up scrolls array, determines if frames are involved.
 */
function init() {

    var body = document.body;

    initTest();

    if (!scrolls) {
      scrolls = setupScrolls();
    }

    // Checks if this script is running in a frame
    if (top != self) {
        frame = true;
        // document.documentElement ?
        if (body.scrollHeight <= body.clientHeight + 10) {
            noscrollframe = true;
        }
    }

    /**
     * This fixes a bug where the areas left and right
     * to the content does not trigger the onmousewheel
     * event on some pages. Acid3 test is excluded.
     */
    if (document.URL !== "http://acid3.acidtests.org/") {
        var underlay = document.createElement('div');
        underlay.setAttribute( "style",
            "z-index: -1; position:absolute; top:0; left: 0; " +
            "width: 100%; height: " + body.scrollHeight + "px;" );
        body.appendChild(underlay);
    }
    initdone = true;
}

/***********************************************
 * EVENTS
 ***********************************************/

/**
 * Mouse wheel handler.
 * NOTE: function logic should be decomposed.
 * @param {Object} event
 */
function wheel(event) {

    if (!initdone) {
        init();
    }

    deltaX = event.wheelDeltaX || 0;
    deltaY = event.wheelDeltaY || 0;

    // normalize deltas
    deltaX /= 120;
    deltaY /= 120;

    // synaptics seems to send 1 sometimes,
    // and 120 other times (fix)
    if (Math.abs(deltaX) < 0.01) {
        deltaX *= 120;
    }
    if (Math.abs(deltaY) < 0.01) {
        deltaY *= 120;
    }

    var dir = (deltaY > 0) ? up : down;
    var elem = overflowingAncestor(event.target);

    if (!elem || (frame && noscrollframe)) {
        return true;
    }

    scrollArray(elem, dir, -deltaX, -deltaY);
    event.preventDefault();
}

/**
 * Keydown event handler.
 * @param {Object} event
 */
function keydown(event) {

    var target   = event.target;
    var modifier = event.ctrlKey || event.altKey || event.metaKey;

    // do nothing if user is editing text
    // or using a modifier key (except shift)
    if ( isNodeName(target, "input")    ||
         isNodeName(target, "textarea") ||
         target.isContentEditable       ||
         modifier ) {
      return true;
    }
    // spacebar should trigger button press
    if (isNodeName(target, "button") &&
        event.keyCode === key.spacebar) {
      return true;
    }

    var scale, dir, shift;
    var elem = overflowingAncestor(target);

    var clientHeight = target.clientHeight;

    if (elem === document.body) {
        clientHeight = window.innerHeight;
    }

    switch (event.keyCode) {
        case key.up:
            scale = -arrowscroll;
            dir = up;
            break;
        case key.down:
            scale = arrowscroll;
            dir = down;
            break;
        case key.spacebar: // (+ shift)
            shift = event.shiftKey ? 1 : -1;
            scale = -shift * clientHeight * 0.9;
            dir = (shift > 0) ? up : down;
            break;
        case key.pageup:
            scale = -clientHeight * 0.9;
            dir = up;
            break;
        case key.pagedown:
            scale = clientHeight * 0.9;
            dir = down;
            break;
        case key.home:
            scale = -target.scrollTop;
            dir = up;
            break;
        case key.end:
            var damt = target.scrollHeight - target.scrollTop - clientHeight;
            scale = (damt > 0) ? damt : 0;
            dir = down;
            break;
        default:
            return true; // a key we don't care about
    }
    scale /= stepsize;
    scale = (scale > 0) ? Math.ceil(scale) : Math.floor(scale);
    scrollArray(elem, dir, 0, scale);
    event.preventDefault();
}

/***********************************************
 * HELPERS
 ***********************************************/

function addEvent(type, fn, bubble) {
    window.addEventListener(type, fn, (bubble||false));
}

function removeEvent(type, fn, bubble) {
    window.removeEventListener(type, fn, (bubble||false));
}

function isNodeName(el, tag) {
    return el.nodeName.toLowerCase() === tag.toLowerCase();
}

function clearTimeouts(array) {
    while (array.length) {
        clearTimeout(array.pop());
    }
}

function overflowingAncestor(el) {
    var bodyScrollHeight = document.body.scrollHeight;
    do {
        if (bodyScrollHeight === el.scrollHeight) {
            return document.body;
        }
        else if (el.clientHeight + 10 < el.scrollHeight) {
            overflow = getComputedStyle(el, "").getPropertyValue("overflow");
            if (overflow === "scroll" || overflow === "auto") {
                return el;
            }
        }
    } while (el = el.parentNode);
}

/***********************************************
 * PULSE
 ***********************************************/

/**
 * Viscous fluid with a pulse for part and decay for the rest.
 * - Applies a fixed force over an interval (a damped acceleration), and
 * - Lets the exponential bleed away the velocity over a longer interval
 * - Michael Herf, http://stereopsis.com/stopping/
 */
function pulse_(x) {
    var val, start, expx;
    // test
    x = x * pulseScale;
    if (x < 1) { // acceleartion
        val = x - (1 - Math.exp(-x));
    } else {     // tail
        // the previous animation ended here:
        start = Math.exp(-1);
        // simple viscous drag
        x -= 1;
        expx = 1 - Math.exp(-x);
        val = start + (expx * (1 - start));
    }
    return val * pulseNormalize;
}

function computePulseScale() {
    pulseNormalize = 1 / pulse_(1);
}

/**
 * Viscous fluid with a pulse for part and decay for the rest
 */
function pulse(x) {
    if (x >= 1) return 1;
    if (x <= 0) return 0;

    if (pulseNormalize == 1) {
        computePulseScale();
    }
    return pulse_(x);
}

/************************************************
 * SCROLLING
 ************************************************/

/**
 * Pushes scroll actions to a given direction Array.
 */
function scrollArray(elem, dir, multiplyX, multiplyY, delay) {
    delay || (delay = 1000);
    clearTimeouts(dir === up ? down : up);

    function step() {

        var scale = scrolls[i++]; // linear or pulse

        var scrollLeft = elem.scrollLeft;
        var scrollTop  = elem.scrollTop;

        elem.scrollLeft = elem.scrollLeft + (multiplyX * scale);
        elem.scrollTop  = elem.scrollTop  + (multiplyY * scale);

        // scroll left failed (edge)
        if (elem.scrollLeft === scrollLeft) {
            multiplyX = 0;
        }
        // scroll top failed (edge)
        if (elem.scrollTop === scrollTop) {
            multiplyY = 0;
        }
        // if there's nothing left ot do
        if (!multiplyX && !multiplyY) {
            console.log("edge");
            clearTimeouts(dir);
        }

    }
    // populate directions array
    for (var i = scrolls.length; i--;) {
        dir.push(setTimeout(step, i * delay / framerate + 1));
    }
    i = 0; // reset so that step() can increment again
}

addEvent("mousewheel", wheel);
addEvent("DOMContentLoaded", init);
<|endoftext|>


<commit_before>(function(Two) {

  var root = this;
  var getComputedMatrix = Two.Utils.getComputedMatrix;
  var _ = Two.Utils;

  var canvas = (root.document ? root.document.createElement('canvas') : { getContext: _.identity });
  var ctx = canvas.getContext('2d');

  var Text = Two.Text = function(message, x, y, styles) {

    Two.Shape.call(this);

    this._renderer.type = 'text';
    this._renderer.flagFill = _.bind(Text.FlagFill, this);
    this._renderer.flagStroke = _.bind(Text.FlagStroke, this);

    this.value = message;

    if (_.isNumber(x)) {
        this.translation.x = x;
    }
    if (_.isNumber(y)) {
        this.translation.y = y;
    }

    if (!_.isObject(styles)) {
      return this;
    }

    _.each(Two.Text.Properties, function(property) {

      if (property in styles) {
        this[property] = styles[property];
      }

    }, this);

  };

  _.extend(Two.Text, {

    Properties: [
      'value', 'family', 'size', 'leading', 'alignment', 'linewidth', 'style',
      'weight', 'decoration', 'baseline', 'opacity', 'visible', 'fill', 'stroke'
    ],

    FlagFill: function() {
      this._flagFill = true;
    },

    FlagStroke: function() {
      this._flagStroke = true;
    },

    MakeObservable: function(object) {

      Two.Shape.MakeObservable(object);

      _.each(Two.Text.Properties.slice(0, 12), Two.Utils.defineProperty, object);

      Object.defineProperty(object, 'fill', {
        enumerable: true,
        get: function() {
          return this._fill;
        },
        set: function(f) {

          if (this._fill instanceof Two.Gradient
            || this._fill instanceof Two.LinearGradient
            || this._fill instanceof Two.RadialGradient
            || this._fill instanceof Two.Texture) {
            this._fill.unbind(Two.Events.change, this._renderer.flagFill);
          }

          this._fill = f;
          this._flagFill = true;

          if (this._fill instanceof Two.Gradient
            || this._fill instanceof Two.LinearGradient
            || this._fill instanceof Two.RadialGradient
            || this._fill instanceof Two.Texture) {
            this._fill.bind(Two.Events.change, this._renderer.flagFill);
          }

        }
      });

      Object.defineProperty(object, 'stroke', {
        enumerable: true,
        get: function() {
          return this._stroke;
        },
        set: function(f) {

          if (this._stroke instanceof Two.Gradient
            || this._stroke instanceof Two.LinearGradient
            || this._stroke instanceof Two.RadialGradient
            || this._stroke instanceof Two.Texture) {
            this._stroke.unbind(Two.Events.change, this._renderer.flagStroke);
          }

          this._stroke = f;
          this._flagStroke = true;

          if (this._stroke instanceof Two.Gradient
            || this._stroke instanceof Two.LinearGradient
            || this._stroke instanceof Two.RadialGradient
            || this._stroke instanceof Two.Texture) {
            this._stroke.bind(Two.Events.change, this._renderer.flagStroke);
          }

        }
      });

      Object.defineProperty(object, 'clip', {
        enumerable: true,
        get: function() {
          return this._clip;
        },
        set: function(v) {
          this._clip = v;
          this._flagClip = true;
        }
      });

    }

  });

  _.extend(Two.Text.prototype, Two.Shape.prototype, {

    // Flags
    // http://en.wikipedia.org/wiki/Flag

    _flagValue: true,
    _flagFamily: true,
    _flagSize: true,
    _flagLeading: true,
    _flagAlignment: true,
    _flagBaseline: true,
    _flagStyle: true,
    _flagWeight: true,
    _flagDecoration: true,

    _flagFill: true,
    _flagStroke: true,
    _flagLinewidth: true,
    _flagOpacity: true,
    _flagVisible: true,

    _flagClip: false,

    // Underlying Properties

    _value: '',
    _family: 'sans-serif',
    _size: 13,
    _leading: 17,
    _alignment: 'center',
    _baseline: 'middle',
    _style: 'normal',
    _weight: 500,
    _decoration: 'none',

    _fill: '#000',
    _stroke: 'transparent',
    _linewidth: 1,
    _opacity: 1,
    _visible: true,

    _clip: false,

    remove: function() {

      if (!this.parent) {
        return this;
      }

      this.parent.remove(this);

      return this;

    },

    clone: function(parent) {

      var parent = parent || this.parent;

      var clone = new Two.Text(this.value);
      clone.translation.copy(this.translation);
      clone.rotation = this.rotation;
      clone.scale = this.scale;

      _.each(Two.Text.Properties, function(property) {
        clone[property] = this[property];
      }, this);

      if (parent) {
        parent.add(clone);
      }

      return clone;

    },

    toObject: function() {

      var result = {
        translation: this.translation.toObject(),
        rotation: this.rotation,
        scale: this.scale
      };

      _.each(Two.Text.Properties, function(property) {
        result[property] = this[property];
      }, this);

      return result;

    },

    noStroke: function() {
      this.stroke = 'transparent';
      return this;
    },

    noFill: function() {
      this.fill = 'transparent';
      return this;
    },

    /**
     * A shim to not break `getBoundingClientRect` calls. TODO: Implement a
     * way to calculate proper bounding boxes of `Two.Text`.
     */
    getBoundingClientRect: function(shallow) {

      var matrix, border, l, x, y, i, v;

      var left = Infinity, right = -Infinity,
          top = Infinity, bottom = -Infinity;

      // TODO: Update this to not __always__ update. Just when it needs to.
      this._update(true);

      matrix = !!shallow ? this._matrix : getComputedMatrix(this);

      v = matrix.multiply(0, 0, 1);

      return {
        top: v.x,
        left: v.y,
        right: v.x,
        bottom: v.y,
        width: 0,
        height: 0
      };

    },

    flagReset: function() {

      this._flagValue = this._flagFamily = this._flagSize =
        this._flagLeading = this._flagAlignment = this._flagFill =
        this._flagStroke = this._flagLinewidth = this._flagOpaicty =
        this._flagVisible = this._flagClip = this._flagDecoration =
        this._flagBaseline = false;

      Two.Shape.prototype.flagReset.call(this);

      return this;

    }

  });

  Two.Text.MakeObservable(Two.Text.prototype);

})((typeof global !== 'undefined' ? global : this).Two);
<commit_msg>Update text.js<commit_after>(function(Two) {

  var root = typeof window != 'undefined' ? window : typeof global != 'undefined' ? global : null;
  var getComputedMatrix = Two.Utils.getComputedMatrix;
  var _ = Two.Utils;

  var canvas = (root.document ? root.document.createElement('canvas') : { getContext: _.identity });
  var ctx = canvas.getContext('2d');

  var Text = Two.Text = function(message, x, y, styles) {

    Two.Shape.call(this);

    this._renderer.type = 'text';
    this._renderer.flagFill = _.bind(Text.FlagFill, this);
    this._renderer.flagStroke = _.bind(Text.FlagStroke, this);

    this.value = message;

    if (_.isNumber(x)) {
        this.translation.x = x;
    }
    if (_.isNumber(y)) {
        this.translation.y = y;
    }

    if (!_.isObject(styles)) {
      return this;
    }

    _.each(Two.Text.Properties, function(property) {

      if (property in styles) {
        this[property] = styles[property];
      }

    }, this);

  };

  _.extend(Two.Text, {

    Properties: [
      'value', 'family', 'size', 'leading', 'alignment', 'linewidth', 'style',
      'weight', 'decoration', 'baseline', 'opacity', 'visible', 'fill', 'stroke'
    ],

    FlagFill: function() {
      this._flagFill = true;
    },

    FlagStroke: function() {
      this._flagStroke = true;
    },

    MakeObservable: function(object) {

      Two.Shape.MakeObservable(object);

      _.each(Two.Text.Properties.slice(0, 12), Two.Utils.defineProperty, object);

      Object.defineProperty(object, 'fill', {
        enumerable: true,
        get: function() {
          return this._fill;
        },
        set: function(f) {

          if (this._fill instanceof Two.Gradient
            || this._fill instanceof Two.LinearGradient
            || this._fill instanceof Two.RadialGradient
            || this._fill instanceof Two.Texture) {
            this._fill.unbind(Two.Events.change, this._renderer.flagFill);
          }

          this._fill = f;
          this._flagFill = true;

          if (this._fill instanceof Two.Gradient
            || this._fill instanceof Two.LinearGradient
            || this._fill instanceof Two.RadialGradient
            || this._fill instanceof Two.Texture) {
            this._fill.bind(Two.Events.change, this._renderer.flagFill);
          }

        }
      });

      Object.defineProperty(object, 'stroke', {
        enumerable: true,
        get: function() {
          return this._stroke;
        },
        set: function(f) {

          if (this._stroke instanceof Two.Gradient
            || this._stroke instanceof Two.LinearGradient
            || this._stroke instanceof Two.RadialGradient
            || this._stroke instanceof Two.Texture) {
            this._stroke.unbind(Two.Events.change, this._renderer.flagStroke);
          }

          this._stroke = f;
          this._flagStroke = true;

          if (this._stroke instanceof Two.Gradient
            || this._stroke instanceof Two.LinearGradient
            || this._stroke instanceof Two.RadialGradient
            || this._stroke instanceof Two.Texture) {
            this._stroke.bind(Two.Events.change, this._renderer.flagStroke);
          }

        }
      });

      Object.defineProperty(object, 'clip', {
        enumerable: true,
        get: function() {
          return this._clip;
        },
        set: function(v) {
          this._clip = v;
          this._flagClip = true;
        }
      });

    }

  });

  _.extend(Two.Text.prototype, Two.Shape.prototype, {

    // Flags
    // http://en.wikipedia.org/wiki/Flag

    _flagValue: true,
    _flagFamily: true,
    _flagSize: true,
    _flagLeading: true,
    _flagAlignment: true,
    _flagBaseline: true,
    _flagStyle: true,
    _flagWeight: true,
    _flagDecoration: true,

    _flagFill: true,
    _flagStroke: true,
    _flagLinewidth: true,
    _flagOpacity: true,
    _flagVisible: true,

    _flagClip: false,

    // Underlying Properties

    _value: '',
    _family: 'sans-serif',
    _size: 13,
    _leading: 17,
    _alignment: 'center',
    _baseline: 'middle',
    _style: 'normal',
    _weight: 500,
    _decoration: 'none',

    _fill: '#000',
    _stroke: 'transparent',
    _linewidth: 1,
    _opacity: 1,
    _visible: true,

    _clip: false,

    remove: function() {

      if (!this.parent) {
        return this;
      }

      this.parent.remove(this);

      return this;

    },

    clone: function(parent) {

      var parent = parent || this.parent;

      var clone = new Two.Text(this.value);
      clone.translation.copy(this.translation);
      clone.rotation = this.rotation;
      clone.scale = this.scale;

      _.each(Two.Text.Properties, function(property) {
        clone[property] = this[property];
      }, this);

      if (parent) {
        parent.add(clone);
      }

      return clone;

    },

    toObject: function() {

      var result = {
        translation: this.translation.toObject(),
        rotation: this.rotation,
        scale: this.scale
      };

      _.each(Two.Text.Properties, function(property) {
        result[property] = this[property];
      }, this);

      return result;

    },

    noStroke: function() {
      this.stroke = 'transparent';
      return this;
    },

    noFill: function() {
      this.fill = 'transparent';
      return this;
    },

    /**
     * A shim to not break `getBoundingClientRect` calls. TODO: Implement a
     * way to calculate proper bounding boxes of `Two.Text`.
     */
    getBoundingClientRect: function(shallow) {

      var matrix, border, l, x, y, i, v;

      var left = Infinity, right = -Infinity,
          top = Infinity, bottom = -Infinity;

      // TODO: Update this to not __always__ update. Just when it needs to.
      this._update(true);

      matrix = !!shallow ? this._matrix : getComputedMatrix(this);

      v = matrix.multiply(0, 0, 1);

      return {
        top: v.x,
        left: v.y,
        right: v.x,
        bottom: v.y,
        width: 0,
        height: 0
      };

    },

    flagReset: function() {

      this._flagValue = this._flagFamily = this._flagSize =
        this._flagLeading = this._flagAlignment = this._flagFill =
        this._flagStroke = this._flagLinewidth = this._flagOpaicty =
        this._flagVisible = this._flagClip = this._flagDecoration =
        this._flagBaseline = false;

      Two.Shape.prototype.flagReset.call(this);

      return this;

    }

  });

  Two.Text.MakeObservable(Two.Text.prototype);

})((typeof global !== 'undefined' ? global : this).Two);
<|endoftext|>


<commit_before>'use strict'

var extend = require('xtend/mutable')

function CardType (name, config) {
  extend(this, {name: name}, config)
}

CardType.prototype.cvcLength = 3

CardType.prototype.luhn = true

CardType.prototype.groupPattern = /(\d{1,4})(\d{1,4})?(\d{1,4})?(\d{1,4})?/

CardType.prototype.group = function (number) {
  return (number.match(this.groupPattern) || [])
    .slice(1)
    .filter(identity)
}

CardType.prototype.test = function (number, eager) {
  return this[eager ? 'eagerPattern' : 'pattern'].test(number)
}

module.exports = CardType

function identity (value) {
  return value
}
<commit_msg>Export @ top<commit_after>'use strict'

var extend = require('xtend/mutable')

module.exports = CardType

function CardType (name, config) {
  extend(this, {name: name}, config)
}

CardType.prototype.cvcLength = 3

CardType.prototype.luhn = true

CardType.prototype.groupPattern = /(\d{1,4})(\d{1,4})?(\d{1,4})?(\d{1,4})?/

CardType.prototype.group = function (number) {
  return (number.match(this.groupPattern) || [])
    .slice(1)
    .filter(identity)
}

CardType.prototype.test = function (number, eager) {
  return this[eager ? 'eagerPattern' : 'pattern'].test(number)
}

function identity (value) {
  return value
}
<|endoftext|>


<commit_before>Udon = (typeof Udon === 'undefined') ? {} : Udon;

Udon.foldl = function(fn, z, xs) {
    var len = xs.length, i;
    for (i = 0; i < len; i++) z = fn(z, xs[i]);
    return z;
};

Udon.foldr = function(fn, z, xs) {
    var i = xs.length;
    while (i--) z = fn(xs[i], z);
    return z;
};

Udon.map = function(fn, xs) {
    var ys = [], i = xs.length;
    while (i--) ys[i] = fn(xs[i]);
    return ys;
};

Udon.filter = function(fn, xs) {
    var ys = [], len = xs.length, i, e;
    for (i = 0; i < len; i++) {
        e = xs[i];
        if (fn(e)) ys.push(e);
    }
    return ys;
};

Udon.unfoldr = function(step, seed) {
    var output  = [], result;
    while (result = step(seed)) {
        output.push(result[0]);
        seed = result[1];
    }
    return output;
};

Udon.zipWith = function(fn, xs, ys) {
    var xsl = xs.length, ysl = ys.length,
        len = xsl > ysl ? ysl : xsl, zs = [], i;
    for (i = 0; i < len; i++) zs[i] = fn(xs[i], ys[i]);
    return zs;
};

Udon.zip = function(xs, ys) {
    return Udon.zipWith(function(x, y) { return [x, y]; });
};
<commit_msg>Add partition function.<commit_after>Udon = (typeof Udon === 'undefined') ? {} : Udon;

Udon.foldl = function(fn, z, xs) {
    var len = xs.length, i;
    for (i = 0; i < len; i++) z = fn(z, xs[i]);
    return z;
};

Udon.foldr = function(fn, z, xs) {
    var i = xs.length;
    while (i--) z = fn(xs[i], z);
    return z;
};

Udon.map = function(fn, xs) {
    var ys = [], i = xs.length;
    while (i--) ys[i] = fn(xs[i]);
    return ys;
};

Udon.filter = function(fn, xs) {
    var ys = [], len = xs.length, i, e;
    for (i = 0; i < len; i++) {
        e = xs[i];
        if (fn(e)) ys.push(e);
    }
    return ys;
};

Udon.partition = function(fn, xs) {
    var ts = [], fs = [], len = xs.length, i, e;
    for (i = 0; i < len; i++) {
        e = xs[i];
        (fn(e) ? ts : fs).push(e);
    }
    return [ts, fs];
};

Udon.unfoldr = function(step, seed) {
    var output  = [], result;
    while (result = step(seed)) {
        output.push(result[0]);
        seed = result[1];
    }
    return output;
};

Udon.zipWith = function(fn, xs, ys) {
    var xsl = xs.length, ysl = ys.length,
        len = xsl > ysl ? ysl : xsl, zs = [], i;
    for (i = 0; i < len; i++) zs[i] = fn(xs[i], ys[i]);
    return zs;
};

Udon.zip = function(xs, ys) {
    return Udon.zipWith(function(x, y) { return [x, y]; });
};
<|endoftext|>


<commit_before>(function() {

// relies on global var WORKER_ID

var updateRate = 10, timeoutRate = 180,
    testTimeout, pauseTimer, testResults = {},
    workQueueId, workerId=WORKER_ID;

jQuery( doWork );

if ( window.addEventListener ) {
    window.addEventListener( "message", handleMessage, false );
} else if ( window.attachEvent ) {
    window.attachEvent( "onmessage", handleMessage );
}

var cmds = {
    run_test: function(params) {
        testResults = {};
        workQueueId = params.work_queue_id;
        log("Running: " +
            params.name + " at " + params.url +
            " [" + workQueueId.toString() + "]");

        var iframe = document.createElement("iframe");
        iframe.width = 1000;
        iframe.height = 600;
        iframe.className = "test";
        iframe.src = params.url + '?_=' + (new Date).getTime();
        jQuery("#iframes").append( iframe );

        var loadTimeout = 10000;
        var failedToLoad = setTimeout(function() {
            runtimeError('Failed to load the test suite in ' + loadTimeout/1000 + ' seconds');
        }, loadTimeout);

        jQuery(iframe).load(function(e) {
            clearTimeout(failedToLoad);
        });

        // The iframe must communicate back to us
        // with window.top.postMessage.
        // See handleMessage() for how those are received.

        // Timeout after a period of time
        testTimeout = setTimeout(function() {
            runtimeError('Timed out waiting for test results');
        }, timeoutRate * 1000 );
    },
    restart: function() {
        var noCache = true;
        window.location.reload(noCache);
    },
    change_rate: function( num ) {
        updateRate = parseInt( num );
    }
};

function doWork() {
    workQueueId = null;
    msg("Getting work from server...");
    retrySend("/work/query",
              {worker_id: workerId, user_agent: navigator.userAgent},
               doWork, doServerCmd);
}

function doServerCmd( data ) {
    if ( data.cmd ) {
        if ( typeof cmds[ data.cmd ] === "function" ) {
            cmds[ data.cmd ].apply( cmds, data.args );
        } else {
            log("Received an unknown command: " + data.cmd);
        }
    } else {
        clearTimeout( pauseTimer );

        var run_msg = data.desc || "No command from server.";

        msg(run_msg);

        var timeLeft = updateRate;

        pauseTimer = setTimeout(function leftTimer(){
            msg(run_msg + " Checking again in " + timeLeft + " seconds.");
            if ( timeLeft-- >= 1 ) {
                pauseTimer = setTimeout( leftTimer, 1000 );
            } else {
                doWork();
            }
        }, 1000);
    }
}

function done() {
    cancelTest();
    setTimeout(doWork, 3);
}

function cancelTest() {
    if ( testTimeout ) {
        clearTimeout( testTimeout );
        testTimeout = 0;
    }

    jQuery("iframe").remove();
}

function runtimeError(errorMsg) {
    cancelTest();
    var msg = {
        test_run_error: true,
        test_run_error_msg: errorMsg
    }
    log(msg.test_run_error_msg);
    retrySend('/work/submit_results', {
            work_queue_id: workQueueId,
            results: JSON.stringify(msg)
        },
        runtimeError, doWork );
}

function parseQueryStr(qs) {
    var obj = {},
        vars = qs.split("&");
    jQuery.each(vars, function(i, val) {
        var parts = val.split('=');
        obj[parts[0]] = decodeURI(parts[1]);
    });
    return obj;
}

function handleMessage(msg){
    var obj = parseQueryStr(msg.data);
    switch (obj.action) {
        case 'hello':
            testResults.user_agent = obj.user_agent;
            break;
        case 'set_test':
            testResults._current_test = obj.name;
            break;
        case 'set_module':
            testResults._current_module = obj.name;
            break;
        case 'log':
            if (typeof(testResults.tests) === 'undefined') {
                testResults.tests = [];
            }
            testResults.tests.push({
                module: testResults._current_module,
                test: testResults._current_test,
                result: obj.result == 'true' ? true: false,
                message: obj.message,
                stacktrace: obj.stacktrace
            });
            break;
        case 'done':
            log("failures: " + obj.failures + "; total: " + obj.total);
            testResults.failures = parseInt(obj.failures, 10);
            testResults.total = parseInt(obj.total, 10);
            retrySend( '/work/submit_results',
                        {work_queue_id: workQueueId,
                         results: JSON.stringify(testResults)},
                        function() {
                            handleMessage(msg);
                        }, done );
            break;
        default:
            throw new Error("Unknown action: " + obj.action);
            break;
    }
}

var errorOut = 0;

function retrySend( url, data, retry, success ) {
    jQuery.ajax({
        type: "POST",
        url: url,
        timeout: 10000,
        cache: false,
        data: data,
        error: function() {
            if ( errorOut++ > 4 ) {
                cmds.restart();
            } else {
                msg("Error connecting to server, retrying...");
                setTimeout( retry, 15000 );
            }
        },
        success: function(){
            errorOut = 0;
            msg("Sent data to server successfully");
            success.apply( this, arguments );
        },
        dataType: 'json'
    });
}

function log( txt ) {
    jQuery("#history").prepend( "
" +
        (new Date).toString().replace(/^\w+ /, "").replace(/:[^:]+$/, "") +
        ": " + txt + "
" );
    msg( txt );
}

function msg( txt ) {
    jQuery("#msg").html( "[worker=" + workerId.toString() + "] " + txt );
}

})();
<commit_msg>Increased load timeout to 2 min<commit_after>(function() {

// relies on global var WORKER_ID

var updateRate = 10, timeoutRate = 180,
    testTimeout, pauseTimer, testResults = {},
    workQueueId, workerId=WORKER_ID;

jQuery( doWork );

if ( window.addEventListener ) {
    window.addEventListener( "message", handleMessage, false );
} else if ( window.attachEvent ) {
    window.attachEvent( "onmessage", handleMessage );
}

var cmds = {
    run_test: function(params) {
        testResults = {};
        workQueueId = params.work_queue_id;
        log("Running: " +
            params.name + " at " + params.url +
            " [" + workQueueId.toString() + "]");

        var iframe = document.createElement("iframe");
        iframe.width = 1000;
        iframe.height = 600;
        iframe.className = "test";
        iframe.src = params.url + '?_=' + (new Date).getTime();
        jQuery("#iframes").append( iframe );

        var loadTimeout = 1000 * 60 * 2; // 2 min
        var failedToLoad = setTimeout(function() {
            runtimeError('Failed to load the test suite in ' + loadTimeout/60000 + ' minutes');
        }, loadTimeout);

        jQuery(iframe).load(function(e) {
            clearTimeout(failedToLoad);
        });

        // The iframe must communicate back to us
        // with window.top.postMessage.
        // See handleMessage() for how those are received.

        // Timeout after a period of time
        testTimeout = setTimeout(function() {
            runtimeError('Timed out waiting for test results');
        }, timeoutRate * 1000 );
    },
    restart: function() {
        var noCache = true;
        window.location.reload(noCache);
    },
    change_rate: function( num ) {
        updateRate = parseInt( num );
    }
};

function doWork() {
    workQueueId = null;
    msg("Getting work from server...");
    retrySend("/work/query",
              {worker_id: workerId, user_agent: navigator.userAgent},
               doWork, doServerCmd);
}

function doServerCmd( data ) {
    if ( data.cmd ) {
        if ( typeof cmds[ data.cmd ] === "function" ) {
            cmds[ data.cmd ].apply( cmds, data.args );
        } else {
            log("Received an unknown command: " + data.cmd);
        }
    } else {
        clearTimeout( pauseTimer );

        var run_msg = data.desc || "No command from server.";

        msg(run_msg);

        var timeLeft = updateRate;

        pauseTimer = setTimeout(function leftTimer(){
            msg(run_msg + " Checking again in " + timeLeft + " seconds.");
            if ( timeLeft-- >= 1 ) {
                pauseTimer = setTimeout( leftTimer, 1000 );
            } else {
                doWork();
            }
        }, 1000);
    }
}

function done() {
    cancelTest();
    setTimeout(doWork, 3);
}

function cancelTest() {
    if ( testTimeout ) {
        clearTimeout( testTimeout );
        testTimeout = 0;
    }

    jQuery("iframe").remove();
}

function runtimeError(errorMsg) {
    cancelTest();
    var msg = {
        test_run_error: true,
        test_run_error_msg: errorMsg
    }
    log(msg.test_run_error_msg);
    retrySend('/work/submit_results', {
            work_queue_id: workQueueId,
            results: JSON.stringify(msg)
        },
        runtimeError, doWork );
}

function parseQueryStr(qs) {
    var obj = {},
        vars = qs.split("&");
    jQuery.each(vars, function(i, val) {
        var parts = val.split('=');
        obj[parts[0]] = decodeURI(parts[1]);
    });
    return obj;
}

function handleMessage(msg){
    var obj = parseQueryStr(msg.data);
    switch (obj.action) {
        case 'hello':
            testResults.user_agent = obj.user_agent;
            break;
        case 'set_test':
            testResults._current_test = obj.name;
            break;
        case 'set_module':
            testResults._current_module = obj.name;
            break;
        case 'log':
            if (typeof(testResults.tests) === 'undefined') {
                testResults.tests = [];
            }
            testResults.tests.push({
                module: testResults._current_module,
                test: testResults._current_test,
                result: obj.result == 'true' ? true: false,
                message: obj.message,
                stacktrace: obj.stacktrace
            });
            break;
        case 'done':
            log("failures: " + obj.failures + "; total: " + obj.total);
            testResults.failures = parseInt(obj.failures, 10);
            testResults.total = parseInt(obj.total, 10);
            retrySend( '/work/submit_results',
                        {work_queue_id: workQueueId,
                         results: JSON.stringify(testResults)},
                        function() {
                            handleMessage(msg);
                        }, done );
            break;
        default:
            throw new Error("Unknown action: " + obj.action);
            break;
    }
}

var errorOut = 0;

function retrySend( url, data, retry, success ) {
    jQuery.ajax({
        type: "POST",
        url: url,
        timeout: 10000,
        cache: false,
        data: data,
        error: function() {
            if ( errorOut++ > 4 ) {
                cmds.restart();
            } else {
                msg("Error connecting to server, retrying...");
                setTimeout( retry, 15000 );
            }
        },
        success: function(){
            errorOut = 0;
            msg("Sent data to server successfully");
            success.apply( this, arguments );
        },
        dataType: 'json'
    });
}

function log( txt ) {
    jQuery("#history").prepend( "
" +
        (new Date).toString().replace(/^\w+ /, "").replace(/:[^:]+$/, "") +
        ": " + txt + "
" );
    msg( txt );
}

function msg( txt ) {
    jQuery("#msg").html( "[worker=" + workerId.toString() + "] " + txt );
}

})();
<|endoftext|>


<commit_before>define([
    'json!langCodes',
    'underscore',
    'jquery',
    'jquery.bootstrap-popout'
], function (
    langCodes,
    _,
    $
) {
    RegExp.escape = function(s) {
        return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
    };

    $.fn.stopLink = function() {
        // stops anchor tags from clicking through
        this.click(function (e) {
            e.preventDefault();
        });
        return this;
    };

    $.fn.fdHelp = function () {
        // creates a help popover, requires twitter bootstrap
        this.append($('<i />').addClass('icon-question-sign'))
            .popout({
                trigger: 'hover',
                html: true
            });
        return this;
    };

    var that = {};

    // deep extend
    that.extend = function () {
        var args = Array.prototype.slice.call(arguments);

        return $.extend.apply(null, [true, {}].concat(args));
    };

    that.langCodeToName = {};
    _.each(langCodes, function (lang) {
        var name = lang.names[0];
        that.langCodeToName[lang.three] = name;
        that.langCodeToName[lang.two] = name;
    });

    that.XPATH_REFERENCES = [
        "relevantAttr",
        "calculateAttr",
        "constraintAttr",
        "dataParent",
        "repeat_count"
    ];

    that.getTemplateObject = function (selector, params) {
        return $(_.template($(selector).text(), params));
    };

    /**
     * Check if value is a valid XML attribute value (additionally disallow all
     * ' and ")
     */
    that.isValidAttributeValue = function (value) {
        return (/^[^<&'"]*$/).test(value);
    };

    // Simple Event Framework
    // Just run your object through this function to make it event aware.
    // Adapted from 'JavaScript: The Good Parts' chapter 5
    that.eventuality = function (that) {
        var registry = {};
        /**
         * Fire event, calling all registered handlers and unbind `one` handlers
         */
        that.fire = function (event) {
            var array,
                func,
                handler,
                i,
                type = typeof event === 'string' ? event : event.type;
            if (registry.hasOwnProperty(type)) {
                array = registry[type];
                for (i = 0; i < array.length; i += 1) {
                    handler = array[i];
                    func = handler.method;
                    if (typeof func === 'string') {
                        func = this[func];
                    }
                    func.apply(this, handler.parameters || [event]);
                }
            }
            return this;
        };
        /**
         * Register an event handler to be called each time an event is fired.
         */
        that.on = function (type, method, parameters, bindingContext) {
            var handler = {
                method: method,
                parameters: parameters,
                bindingContext: bindingContext || method
            };
            if (registry.hasOwnProperty(type)) {
                registry[type].push(handler);
            } else {
                registry[type] = [handler];
            }
            return this;
        };
        /**
         * Unbind an event handler for a given binding context
         *
         * @param bindingContext - the binding context or method that was
         *        passed to `on`.
         * @param type - optional event type. If undefined, all handlers
         *        for the given binding context will be unbound.
         */
        that.unbind = function (bindingContext, type) {
            if (_.isUndefined(type)) {
                registry = _.object(_.map(registry, function (handlers, type, reg) {
                    handlers = _.filter(handlers, function (handler) {
                        return handler.bindingContext !== bindingContext;
                    });
                    return [type, handlers];
                }));
            } else if (registry.hasOwnProperty(type)) {
                registry[type] = _.filter(registry[type], function (handler) {
                    return handler.bindingContext !== bindingContext;
                });
            }
            return this;
        };
        return that;
    };

    that.pluralize = function (noun, n) {
        return noun + (n !== 1 ? 's' : '');
    };

    /* jshint bitwise: false */
    that.get_guid = function() {
        // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript
        var S4 = function() {
            return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
        };
        return (S4()+S4()+S4()+S4()+S4()+S4()+S4()+S4());
    };

    that.generate_xmlns_uuid = function () {
        var CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
        var uuid = [], r, i;

		// rfc4122 requires these characters
		uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
		uuid[14] = '4';

		// Fill in random data.  At i==19 set the high bits of clock sequence as
		// per rfc4122, sec. 4.1.5
		for (i = 0; i < 36; i++) {
			if (!uuid[i]) {
				r = Math.floor((Math.random()*16));
				uuid[i] = CHARS[(i === 19) ? (r & 0x3) | 0x8 : r & 0xf];
			}
		}
		return uuid.toString().replace(/,/g,'');
    };
    /* jshint bitwise: true */

    that.isValidElementName = function (name) {
        // HT: http://stackoverflow.com/questions/2519845/how-to-check-if-string-is-a-valid-xml-element-name
        var elementNameRegex = /^(?!XML)[a-zA-Z][\w-]*$/;
        return elementNameRegex.test(name);
    };

    /**
     * Converts true to 'true()' and false to 'false()'. Returns null for all else.
     * @param req
     */
    that.createXPathBoolFromJS = function(req) {
        if(req === true || req === 'true') {
            return 'true()';
        }else if (req === false || req === 'false') {
            return 'false()';
        } else {
            return null;
        }
    };

    that.getOneOrFail = function (list, infoMsg) {
        if (list.length === 0) {
            throw ("No match for " + infoMsg + " found!");
        } else if (list.length > 1) {
            throw ("Multiple matches for " + infoMsg + " found!");
        }
        return list[0];
    };

    that.reduceToOne = function (list, func, infoMsg) {
        return that.getOneOrFail(_(list).filter(func), infoMsg);
    };

    // a wrapper for object properties that triggers the form change event when
    // sub-properties are changed
    that.BoundPropertyMap = function (form, data) {
        this._form = form;
        this._data = data || {};
    };
    that.BoundPropertyMap.prototype = {
        clone: function () {
            return new that.BoundPropertyMap(this._form, this._data);
        },
        setAttr: function (name, val) {
            this._data[name] = val;
            if (this._form) {
                this._form.fire({
                    type: 'change'
                });
            }
        },
        getAttr: function (name, default_) {
            if (name in this._data) {
                return this._data[name];
            } else {
                return default_;
            }
        }
    };

    that.getCaretPosition = function (ctrl) {
        var pos = 0;
        if (ctrl.createTextRange) {
            ctrl.focus ();
            var sel = document.selection.createRange ();
            sel.moveStart ('character', -ctrl.value.length);
            pos = sel.text.length;
        } else if (typeof ctrl.selectionStart !== 'undefined') {
            pos = ctrl.selectionStart;
        }
        return pos;
    };

    that.setCaretPosition = function (ctrl, start, end){
        if (end === null || end === undefined) {
            end = start;
        }
        if (ctrl.setSelectionRange) {
            ctrl.focus();
            ctrl.setSelectionRange(start, end);
        } else if (ctrl.createTextRange) {
            var range = ctrl.createTextRange();
            range.collapse(true);
            range.moveStart('character', start);
            range.moveEnd('character', end);
            range.select();
        }
    };

    that.insertTextAtCursor = function (jqctrl, text, select) {
        var ctrl = jqctrl[0],
            pos = that.getCaretPosition(ctrl),
            front = ctrl.value.substring(0, pos),
            back = ctrl.value.substring(pos, ctrl.value.length),
            start = select ? pos : pos + text.length;
        jqctrl.val(front + text + back).change();
        pos = pos + text.length;
        that.setCaretPosition(ctrl, start, pos);
    };

    return that;
});

<commit_msg>Add xml diff function to utils<commit_after>define([
    'json!langCodes',
    'underscore',
    'equivalent-xml',
    'jsdiff',
    'jquery',
    'jquery.bootstrap-popout'
], function (
    langCodes,
    _,
    EquivalentXml,
    jsdiff,
    $
) {
    RegExp.escape = function(s) {
        return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
    };

    $.fn.stopLink = function() {
        // stops anchor tags from clicking through
        this.click(function (e) {
            e.preventDefault();
        });
        return this;
    };

    $.fn.fdHelp = function () {
        // creates a help popover, requires twitter bootstrap
        this.append($('<i />').addClass('icon-question-sign'))
            .popout({
                trigger: 'hover',
                html: true
            });
        return this;
    };

    var that = {};

    // deep extend
    that.extend = function () {
        var args = Array.prototype.slice.call(arguments);

        return $.extend.apply(null, [true, {}].concat(args));
    };

    that.langCodeToName = {};
    _.each(langCodes, function (lang) {
        var name = lang.names[0];
        that.langCodeToName[lang.three] = name;
        that.langCodeToName[lang.two] = name;
    });

    that.XPATH_REFERENCES = [
        "relevantAttr",
        "calculateAttr",
        "constraintAttr",
        "dataParent",
        "repeat_count"
    ];

    that.getTemplateObject = function (selector, params) {
        return $(_.template($(selector).text(), params));
    };

    /**
     * Check if value is a valid XML attribute value (additionally disallow all
     * ' and ")
     */
    that.isValidAttributeValue = function (value) {
        return (/^[^<&'"]*$/).test(value);
    };

    // Simple Event Framework
    // Just run your object through this function to make it event aware.
    // Adapted from 'JavaScript: The Good Parts' chapter 5
    that.eventuality = function (that) {
        var registry = {};
        /**
         * Fire event, calling all registered handlers and unbind `one` handlers
         */
        that.fire = function (event) {
            var array,
                func,
                handler,
                i,
                type = typeof event === 'string' ? event : event.type;
            if (registry.hasOwnProperty(type)) {
                array = registry[type];
                for (i = 0; i < array.length; i += 1) {
                    handler = array[i];
                    func = handler.method;
                    if (typeof func === 'string') {
                        func = this[func];
                    }
                    func.apply(this, handler.parameters || [event]);
                }
            }
            return this;
        };
        /**
         * Register an event handler to be called each time an event is fired.
         */
        that.on = function (type, method, parameters, bindingContext) {
            var handler = {
                method: method,
                parameters: parameters,
                bindingContext: bindingContext || method
            };
            if (registry.hasOwnProperty(type)) {
                registry[type].push(handler);
            } else {
                registry[type] = [handler];
            }
            return this;
        };
        /**
         * Unbind an event handler for a given binding context
         *
         * @param bindingContext - the binding context or method that was
         *        passed to `on`.
         * @param type - optional event type. If undefined, all handlers
         *        for the given binding context will be unbound.
         */
        that.unbind = function (bindingContext, type) {
            if (_.isUndefined(type)) {
                registry = _.object(_.map(registry, function (handlers, type, reg) {
                    handlers = _.filter(handlers, function (handler) {
                        return handler.bindingContext !== bindingContext;
                    });
                    return [type, handlers];
                }));
            } else if (registry.hasOwnProperty(type)) {
                registry[type] = _.filter(registry[type], function (handler) {
                    return handler.bindingContext !== bindingContext;
                });
            }
            return this;
        };
        return that;
    };

    that.pluralize = function (noun, n) {
        return noun + (n !== 1 ? 's' : '');
    };

    /* jshint bitwise: false */
    that.get_guid = function() {
        // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript
        var S4 = function() {
            return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
        };
        return (S4()+S4()+S4()+S4()+S4()+S4()+S4()+S4());
    };

    that.generate_xmlns_uuid = function () {
        var CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
        var uuid = [], r, i;

		// rfc4122 requires these characters
		uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
		uuid[14] = '4';

		// Fill in random data.  At i==19 set the high bits of clock sequence as
		// per rfc4122, sec. 4.1.5
		for (i = 0; i < 36; i++) {
			if (!uuid[i]) {
				r = Math.floor((Math.random()*16));
				uuid[i] = CHARS[(i === 19) ? (r & 0x3) | 0x8 : r & 0xf];
			}
		}
		return uuid.toString().replace(/,/g,'');
    };
    /* jshint bitwise: true */

    that.isValidElementName = function (name) {
        // HT: http://stackoverflow.com/questions/2519845/how-to-check-if-string-is-a-valid-xml-element-name
        var elementNameRegex = /^(?!XML)[a-zA-Z][\w-]*$/;
        return elementNameRegex.test(name);
    };

    /**
     * Converts true to 'true()' and false to 'false()'. Returns null for all else.
     * @param req
     */
    that.createXPathBoolFromJS = function(req) {
        if(req === true || req === 'true') {
            return 'true()';
        }else if (req === false || req === 'false') {
            return 'false()';
        } else {
            return null;
        }
    };

    that.getOneOrFail = function (list, infoMsg) {
        if (list.length === 0) {
            throw ("No match for " + infoMsg + " found!");
        } else if (list.length > 1) {
            throw ("Multiple matches for " + infoMsg + " found!");
        }
        return list[0];
    };

    that.reduceToOne = function (list, func, infoMsg) {
        return that.getOneOrFail(_(list).filter(func), infoMsg);
    };

    // a wrapper for object properties that triggers the form change event when
    // sub-properties are changed
    that.BoundPropertyMap = function (form, data) {
        this._form = form;
        this._data = data || {};
    };
    that.BoundPropertyMap.prototype = {
        clone: function () {
            return new that.BoundPropertyMap(this._form, this._data);
        },
        setAttr: function (name, val) {
            this._data[name] = val;
            if (this._form) {
                this._form.fire({
                    type: 'change'
                });
            }
        },
        getAttr: function (name, default_) {
            if (name in this._data) {
                return this._data[name];
            } else {
                return default_;
            }
        }
    };

    that.getCaretPosition = function (ctrl) {
        var pos = 0;
        if (ctrl.createTextRange) {
            ctrl.focus ();
            var sel = document.selection.createRange ();
            sel.moveStart ('character', -ctrl.value.length);
            pos = sel.text.length;
        } else if (typeof ctrl.selectionStart !== 'undefined') {
            pos = ctrl.selectionStart;
        }
        return pos;
    };

    that.setCaretPosition = function (ctrl, start, end){
        if (end === null || end === undefined) {
            end = start;
        }
        if (ctrl.setSelectionRange) {
            ctrl.focus();
            ctrl.setSelectionRange(start, end);
        } else if (ctrl.createTextRange) {
            var range = ctrl.createTextRange();
            range.collapse(true);
            range.moveStart('character', start);
            range.moveEnd('character', end);
            range.select();
        }
    };

    that.insertTextAtCursor = function (jqctrl, text, select) {
        var ctrl = jqctrl[0],
            pos = that.getCaretPosition(ctrl),
            front = ctrl.value.substring(0, pos),
            back = ctrl.value.substring(pos, ctrl.value.length),
            start = select ? pos : pos + text.length;
        jqctrl.val(front + text + back).change();
        pos = pos + text.length;
        that.setCaretPosition(ctrl, start, pos);
    };

    that.xmlDiff = function (localForm, serverForm, opts) {
        function cleanForDiff (value) {
            // convert leading tabs to spaces
            value = value.replace(/^\t+/mg, function (match) {
                return match.replace(/\t/g, "  ");
            });
            // add newline at end of file if missing
            if (!value.match(/\n$/)) {
                value = value + "\n";
            }
            return value;
        }
        opts = opts || {};
        if (opts.normalize_xmlns) {
            var xmlns = $($.parseXML(serverForm)).find('data').attr('xmlns');
            localForm = localForm.replace(/(data[^>]+xmlns=")(.+?)"/,
                                    '$1' + xmlns + '"');
        }
        localForm = cleanForDiff(localForm);
        serverForm = cleanForDiff(serverForm);
        var patch = jsdiff.createPatch("", localForm, serverForm, "Local Form", "Server Form");
        patch = patch.replace(/^Index:/,
                "XML " + (opts.not ? "should not be equivalent" : "mismatch"));
        return patch;
    };

    return that;
});

<|endoftext|>


<commit_before>"use strict";
var global = require("./global.js");
var ASSERT = require("./assert.js");
var es5 = require("./es5.js");
var haveGetters = (function(){
    try {
        var o = {};
        es5.defineProperty(o, "f", {
            get: function () {
                return 3;
            }
        });
        return o.f === 3;
    }
    catch (e) {
        return false;
    }

})();

var canEvaluate = (function() {
    //Cannot feature detect CSP without triggering
    //violations

    //So assume CSP if environment is browser. This is reasonable
    //because promise throughput doesn't matter in browser and
    //promisifcation is mostly interesting to node.js anyway
    if (typeof window !== "undefined" && window !== null &&
        typeof window.document !== "undefined" &&
        typeof navigator !== "undefined" && navigator !== null &&
        typeof navigator.appName === "string" &&
        window === global) {
        return false;
    }
    return true;
})();

function deprecated(msg) {
    if (typeof console !== "undefined" && console !== null &&
        typeof console.warn === "function") {
        console.warn("Bluebird: " + msg);
    }
}

var errorObj = {e: {}};
//Try catch is not supported in optimizing
//compiler, so it is isolated
function tryCatch1(fn, receiver, arg) {
    ASSERT(typeof fn === "function");
    try {
        return fn.call(receiver, arg);
    }
    catch (e) {
        errorObj.e = e;
        return errorObj;
    }
}

function tryCatch2(fn, receiver, arg, arg2) {
    ASSERT(typeof fn === "function");
    try {
        return fn.call(receiver, arg, arg2);
    }
    catch (e) {
        errorObj.e = e;
        return errorObj;
    }
}

function tryCatchApply(fn, args, receiver) {
    ASSERT(typeof fn === "function");
    try {
        return fn.apply(receiver, args);
    }
    catch (e) {
        errorObj.e = e;
        return errorObj;
    }
}

//Un-magical enough that using this doesn't prevent
//extending classes from outside using any convention
var inherits = function(Child, Parent) {
    var hasProp = {}.hasOwnProperty;

    function T() {
        this.constructor = Child;
        this.constructor$ = Parent;
        for (var propertyName in Parent.prototype) {
            if (hasProp.call(Parent.prototype, propertyName) &&
                propertyName.charAt(propertyName.length-1) !== "$"
           ) {
                this[propertyName + "$"] = Parent.prototype[propertyName];
            }
        }
    }
    T.prototype = Parent.prototype;
    Child.prototype = new T();
    return Child.prototype;
};

function asString(val) {
    return typeof val === "string" ? val : ("" + val);
}

function isPrimitive(val) {
    return val == null || val === true || val === false ||
        typeof val === "string" || typeof val === "number";

}

function isObject(value) {
    return !isPrimitive(value);
}

function maybeWrapAsError(maybeError) {
    if (!isPrimitive(maybeError)) return maybeError;

    return new Error(asString(maybeError));
}

function withAppended(target, appendee) {
    var len = target.length;
    var ret = new Array(len + 1);
    var i;
    for (i = 0; i < len; ++i) {
        ret[i] = target[i];
    }
    ret[i] = appendee;
    return ret;
}

function notEnumerableProp(obj, name, value) {
    var descriptor = {
        value: value,
        configurable: true,
        enumerable: false,
        writable: true
    };
    es5.defineProperty(obj, name, descriptor);
    return obj;
}

var wrapsPrimitiveReceiver = (function() {
    return this !== "string";
}).call("string");

function thrower(r) {
    throw r;
}

var ret = {
    thrower: thrower,
    isArray: es5.isArray,
    haveGetters: haveGetters,
    notEnumerableProp: notEnumerableProp,
    isPrimitive: isPrimitive,
    isObject: isObject,
    canEvaluate: canEvaluate,
    deprecated: deprecated,
    errorObj: errorObj,
    tryCatch1: tryCatch1,
    tryCatch2: tryCatch2,
    tryCatchApply: tryCatchApply,
    inherits: inherits,
    withAppended: withAppended,
    asString: asString,
    maybeWrapAsError: maybeWrapAsError,
    wrapsPrimitiveReceiver: wrapsPrimitiveReceiver
};

module.exports = ret;
<commit_msg>Check for primitiveness before attempting to define a property<commit_after>"use strict";
var global = require("./global.js");
var ASSERT = require("./assert.js");
var es5 = require("./es5.js");
var haveGetters = (function(){
    try {
        var o = {};
        es5.defineProperty(o, "f", {
            get: function () {
                return 3;
            }
        });
        return o.f === 3;
    }
    catch (e) {
        return false;
    }

})();

var canEvaluate = (function() {
    //Cannot feature detect CSP without triggering
    //violations

    //So assume CSP if environment is browser. This is reasonable
    //because promise throughput doesn't matter in browser and
    //promisifcation is mostly interesting to node.js anyway
    if (typeof window !== "undefined" && window !== null &&
        typeof window.document !== "undefined" &&
        typeof navigator !== "undefined" && navigator !== null &&
        typeof navigator.appName === "string" &&
        window === global) {
        return false;
    }
    return true;
})();

function deprecated(msg) {
    if (typeof console !== "undefined" && console !== null &&
        typeof console.warn === "function") {
        console.warn("Bluebird: " + msg);
    }
}

var errorObj = {e: {}};
//Try catch is not supported in optimizing
//compiler, so it is isolated
function tryCatch1(fn, receiver, arg) {
    ASSERT(typeof fn === "function");
    try {
        return fn.call(receiver, arg);
    }
    catch (e) {
        errorObj.e = e;
        return errorObj;
    }
}

function tryCatch2(fn, receiver, arg, arg2) {
    ASSERT(typeof fn === "function");
    try {
        return fn.call(receiver, arg, arg2);
    }
    catch (e) {
        errorObj.e = e;
        return errorObj;
    }
}

function tryCatchApply(fn, args, receiver) {
    ASSERT(typeof fn === "function");
    try {
        return fn.apply(receiver, args);
    }
    catch (e) {
        errorObj.e = e;
        return errorObj;
    }
}

//Un-magical enough that using this doesn't prevent
//extending classes from outside using any convention
var inherits = function(Child, Parent) {
    var hasProp = {}.hasOwnProperty;

    function T() {
        this.constructor = Child;
        this.constructor$ = Parent;
        for (var propertyName in Parent.prototype) {
            if (hasProp.call(Parent.prototype, propertyName) &&
                propertyName.charAt(propertyName.length-1) !== "$"
           ) {
                this[propertyName + "$"] = Parent.prototype[propertyName];
            }
        }
    }
    T.prototype = Parent.prototype;
    Child.prototype = new T();
    return Child.prototype;
};

function asString(val) {
    return typeof val === "string" ? val : ("" + val);
}

function isPrimitive(val) {
    return val == null || val === true || val === false ||
        typeof val === "string" || typeof val === "number";

}

function isObject(value) {
    return !isPrimitive(value);
}

function maybeWrapAsError(maybeError) {
    if (!isPrimitive(maybeError)) return maybeError;

    return new Error(asString(maybeError));
}

function withAppended(target, appendee) {
    var len = target.length;
    var ret = new Array(len + 1);
    var i;
    for (i = 0; i < len; ++i) {
        ret[i] = target[i];
    }
    ret[i] = appendee;
    return ret;
}

function notEnumerableProp(obj, name, value) {
    if (isPrimitive(obj)) return obj;
    var descriptor = {
        value: value,
        configurable: true,
        enumerable: false,
        writable: true
    };
    es5.defineProperty(obj, name, descriptor);
    return obj;
}

var wrapsPrimitiveReceiver = (function() {
    return this !== "string";
}).call("string");

function thrower(r) {
    throw r;
}

var ret = {
    thrower: thrower,
    isArray: es5.isArray,
    haveGetters: haveGetters,
    notEnumerableProp: notEnumerableProp,
    isPrimitive: isPrimitive,
    isObject: isObject,
    canEvaluate: canEvaluate,
    deprecated: deprecated,
    errorObj: errorObj,
    tryCatch1: tryCatch1,
    tryCatch2: tryCatch2,
    tryCatchApply: tryCatchApply,
    inherits: inherits,
    withAppended: withAppended,
    asString: asString,
    maybeWrapAsError: maybeWrapAsError,
    wrapsPrimitiveReceiver: wrapsPrimitiveReceiver
};

module.exports = ret;
<|endoftext|>


<commit_before>/* @flow */

/**
 * Utilties
 */

// export default for holding the Vue reference
var exports: any = {}
export default exports

/**
 * warn
 */
export function warn (msg: string, err?: Error) {
  if (window.console) {
    console.warn('[vue-validator] ' + msg)
    if (err) {
      console.warn(err.stack)
    }
  }
}

/**
 * empty
 */
export function empty (target: Array<any> | Object): boolean {
  if (target === null || target === undefined) { return true }

  if (Array.isArray(target)) {
    if (target.length > 0) { return false }
    if (target.length === 0) { return true }
  } else if (exports.Vue.util.isPlainObject(target)) {
    let key
    for (key in target) {
      if (exports.Vue.util.hasOwn(target, key)) { return false }
    }
  }

  return true
}

/**
 * each
 */
export function each (target: Array<any> | Object, iterator: Function, context?: Object) {
  if (Array.isArray(target)) {
    for (let i = 0; i < target.length; i++) {
      iterator.call(context || target[i], target[i], i)
    }
  } else if (exports.Vue.util.isPlainObject(target)) {
    const hasOwn = exports.Vue.util.hasOwn
    let key
    for (key in target) {
      if (hasOwn(target, key)) {
        iterator.call(context || target[key], target[key], key)
      }
    }
  }
}

/**
 * pull
 */
export function pull (arr: Array<any>, item: Object): any | null {
  const index = exports.Vue.util.indexOf(arr, item)
  return ~index ? arr.splice(index, 1) : null
}

/**
 * attr
 *
 */
export function attr (el: any, name: string): string | null {
  return el ? el.getAttribute(name) : null
}

/**
 * trigger
 */
export function trigger (el: any, event: string, args?: Object) {
  const e: any = document.createEvent('HTMLEvents')
  e.initEvent(event, true, false)

  if (args) {
    let prop
    for (prop in args) {
      e[prop] = args[prop]
    }
  }

  // Due to Firefox bug, events fired on disabled
  // non-attached form controls can throw errors
  try { el.dispatchEvent(e) } catch (e) {}
}

/**
 * Togging classes
 */
export function toggleClasses (el: Element, key: string, fn: Function) {
  key = key.trim()
  if (key.indexOf(' ') === -1) {
    fn(el, key)
    return
  }

  const keys = key.split(/\s+/)
  for (let i = 0, l = keys.length; i < l; i++) {
    fn(el, keys[i])
  }
}
<commit_msg>:boom: update: remove utils<commit_after>/* @flow */

/**
 * warn
 */
export function warn (msg: string, err?: Error) {
  if (window.console) {
    console.warn('[vue-validator] ' + msg)
    if (err) {
      console.warn(err.stack)
    }
  }
}
<|endoftext|>


<commit_before>  /* Utility methods, most of which are pulled from underscore.js. */

  // Shortcut function for checking if an object has a given property directly
  // on itself (in other words, not on a prototype).
  has = function (obj, key) {
    return hasOwnProp.call(obj, key);
  };

  // The cornerstone, an `each` implementation, aka `forEach`.
  // Handles objects with the built-in `forEach`, arrays, and raw objects.
  // Delegates to **ECMAScript 5**'s native `forEach` if available.
  each = function (obj, iterator, context) {
    if (obj == null) {
      return;
    }
    if (nativeForEach && obj.forEach === nativeForEach) {
      obj.forEach(iterator, context);
    } else if (obj.length === +obj.length) {
      for (var i = 0, l = obj.length; i < l; i++) {
        if (iterator.call(context, obj[i], i, obj) === breaker) {
          return;
        }
      }
    } else {
      for (var key in obj) {
        if (has(obj, key)) {
          if (iterator.call(context, obj[key], key, obj) === breaker) {
            return;
          }
        }
      }
    }
  };

  // Extend a given object with all the properties in passed-in object(s).
  extend = function (obj) {
    each(slice.call(arguments, 1), function (source) {
      for (var prop in source) {
        obj[prop] = source[prop];
      }
    });
    return obj;
  };

  // Is a given value an array?
  // Delegates to ECMA5's native Array.isArray
  // switched to ===, not sure why underscore used ==
  isArray = nativeIsArray || function (obj) {
    return toString.call(obj) === '[object Array]';
  };

  // Is a given variable an object?
  isObject = function (obj) {
    return obj === Object(obj);
  };

  // switched to ===, not sure why underscore used ==
  isString = function (obj) {
    return toString.call(obj) === '[object String]';
  };

  // switched to ===, not sure why underscore used ==
  isNumber = function (obj) {
    return toString.call(obj) === '[object Number]';
  };

  // switched to ===, not sure why underscore used ==
  if (typeof (/./) !== 'function') {
    isFunction = function (obj) {
      return typeof obj === 'function';
    };
  } else {
    isFunction = function (obj) {
      return toString.call(obj) === '[object Function]';
    };
  }

  // Is a given value an ejs object?
  // Yes if object and has "_type", "_self", and "toString" properties
  isEJSObject = function (obj) {
    return (isObject(obj) &&
      has(obj, '_type') &&
      has(obj, '_self') &&
      has(obj, 'toString'));
  },

  isQuery = function (obj) {
    return (isEJSObject(obj) && obj._type() === 'query');
  },

  isFilter = function (obj) {
    return (isEJSObject(obj) && obj._type() === 'filter');
  },

  isFacet = function (obj) {
    return (isEJSObject(obj) && obj._type() === 'facet');
  },

  isComputedProperty = function (obj) {
    return (isEJSObject(obj) && obj._type() === 'computed property');
  },

  isGeoPoint = function (obj) {
    return (isEJSObject(obj) && obj._type() === 'geo point');
  },

  isIndexedShape = function (obj) {
    return (isEJSObject(obj) && obj._type() === 'indexed shape');
  },

  isShape = function (obj) {
    return (isEJSObject(obj) && obj._type() === 'shape');
  };

  isSort = function (obj) {
    return (isEJSObject(obj) && obj._type() === 'sort');
  };
  <commit_msg>Small syntax fix in utils.<commit_after>  /* Utility methods, most of which are pulled from underscore.js. */

  // Shortcut function for checking if an object has a given property directly
  // on itself (in other words, not on a prototype).
  has = function (obj, key) {
    return hasOwnProp.call(obj, key);
  };

  // The cornerstone, an `each` implementation, aka `forEach`.
  // Handles objects with the built-in `forEach`, arrays, and raw objects.
  // Delegates to **ECMAScript 5**'s native `forEach` if available.
  each = function (obj, iterator, context) {
    if (obj == null) {
      return;
    }
    if (nativeForEach && obj.forEach === nativeForEach) {
      obj.forEach(iterator, context);
    } else if (obj.length === +obj.length) {
      for (var i = 0, l = obj.length; i < l; i++) {
        if (iterator.call(context, obj[i], i, obj) === breaker) {
          return;
        }
      }
    } else {
      for (var key in obj) {
        if (has(obj, key)) {
          if (iterator.call(context, obj[key], key, obj) === breaker) {
            return;
          }
        }
      }
    }
  };

  // Extend a given object with all the properties in passed-in object(s).
  extend = function (obj) {
    each(slice.call(arguments, 1), function (source) {
      for (var prop in source) {
        obj[prop] = source[prop];
      }
    });
    return obj;
  };

  // Is a given value an array?
  // Delegates to ECMA5's native Array.isArray
  // switched to ===, not sure why underscore used ==
  isArray = nativeIsArray || function (obj) {
    return toString.call(obj) === '[object Array]';
  };

  // Is a given variable an object?
  isObject = function (obj) {
    return obj === Object(obj);
  };

  // switched to ===, not sure why underscore used ==
  isString = function (obj) {
    return toString.call(obj) === '[object String]';
  };

  // switched to ===, not sure why underscore used ==
  isNumber = function (obj) {
    return toString.call(obj) === '[object Number]';
  };

  // switched to ===, not sure why underscore used ==
  if (typeof (/./) !== 'function') {
    isFunction = function (obj) {
      return typeof obj === 'function';
    };
  } else {
    isFunction = function (obj) {
      return toString.call(obj) === '[object Function]';
    };
  }

  // Is a given value an ejs object?
  // Yes if object and has "_type", "_self", and "toString" properties
  isEJSObject = function (obj) {
    return (isObject(obj) &&
      has(obj, '_type') &&
      has(obj, '_self') &&
      has(obj, 'toString'));
  };

  isQuery = function (obj) {
    return (isEJSObject(obj) && obj._type() === 'query');
  };

  isFilter = function (obj) {
    return (isEJSObject(obj) && obj._type() === 'filter');
  };

  isFacet = function (obj) {
    return (isEJSObject(obj) && obj._type() === 'facet');
  };

  isComputedProperty = function (obj) {
    return (isEJSObject(obj) && obj._type() === 'computed property');
  };

  isGeoPoint = function (obj) {
    return (isEJSObject(obj) && obj._type() === 'geo point');
  };

  isIndexedShape = function (obj) {
    return (isEJSObject(obj) && obj._type() === 'indexed shape');
  };

  isShape = function (obj) {
    return (isEJSObject(obj) && obj._type() === 'shape');
  };

  isSort = function (obj) {
    return (isEJSObject(obj) && obj._type() === 'sort');
  };
  <|endoftext|>


<commit_before>import CircularJSON from 'circular-json-es6'

function cached (fn) {
  const cache = Object.create(null)
  return function cachedFn (str) {
    const hit = cache[str]
    return hit || (cache[str] = fn(str))
  }
}

var classifyRE = /(?:^|[-_\/])(\w)/g
export const classify = cached((str) => {
  return str.replace(classifyRE, toUpper)
})

const camelizeRE = /-(\w)/g
export const camelize = cached((str) => {
  return str.replace(camelizeRE, toUpper)
})

function toUpper (_, c) {
  return c ? c.toUpperCase() : ''
}

export function inDoc (node) {
  if (!node) return false
  var doc = node.ownerDocument.documentElement
  var parent = node.parentNode
  return doc === node ||
    doc === parent ||
    !!(parent && parent.nodeType === 1 && (doc.contains(parent)))
}

/**
 * Stringify/parse data using CircularJSON.
 */

export const UNDEFINED = '__vue_devtool_undefined__'

export function stringify (data) {
  return CircularJSON.stringify(data, replacer)
}

function replacer (key, val) {
  if (val === undefined) {
    return UNDEFINED
  } else {
    return sanitize(val)
  }
}

export function parse (data) {
  return CircularJSON.parse(data, (k, v) => {
    if (v === UNDEFINED) {
      return undefined
    } else {
      return v
    }
  })
}

/**
 * Sanitize data to be posted to the other side.
 * Since the message posted is sent with structured clone,
 * we need to filter out any types that might cause an error.
 *
 * @param {*} data
 * @return {*}
 */

function sanitize (data) {
  if (
    !isPrimitive(data) &&
    !Array.isArray(data) &&
    !isPlainObject(data)
  ) {
    // handle types that will probably cause issues in
    // the structured clone
    return Object.prototype.toString.call(data)
  } else {
    return data
  }
}

export function isPlainObject (obj) {
  return Object.prototype.toString.call(obj) === '[object Object]'
}

function isPrimitive (data) {
  if (data == null) {
    return true
  }
  const type = typeof data
  return (
    type === 'string' ||
    type === 'number' ||
    type === 'boolean' ||
    data instanceof RegExp
  )
}
<commit_msg>revert revivier<commit_after>import CircularJSON from 'circular-json-es6'

function cached (fn) {
  const cache = Object.create(null)
  return function cachedFn (str) {
    const hit = cache[str]
    return hit || (cache[str] = fn(str))
  }
}

var classifyRE = /(?:^|[-_\/])(\w)/g
export const classify = cached((str) => {
  return str.replace(classifyRE, toUpper)
})

const camelizeRE = /-(\w)/g
export const camelize = cached((str) => {
  return str.replace(camelizeRE, toUpper)
})

function toUpper (_, c) {
  return c ? c.toUpperCase() : ''
}

export function inDoc (node) {
  if (!node) return false
  var doc = node.ownerDocument.documentElement
  var parent = node.parentNode
  return doc === node ||
    doc === parent ||
    !!(parent && parent.nodeType === 1 && (doc.contains(parent)))
}

/**
 * Stringify/parse data using CircularJSON.
 */

export const UNDEFINED = '__vue_devtool_undefined__'

export function stringify (data) {
  return CircularJSON.stringify(data, replacer)
}

function replacer (key, val) {
  if (val === undefined) {
    return UNDEFINED
  } else {
    return sanitize(val)
  }
}

export function parse (data) {
  return CircularJSON.parse(data)
}

/**
 * Sanitize data to be posted to the other side.
 * Since the message posted is sent with structured clone,
 * we need to filter out any types that might cause an error.
 *
 * @param {*} data
 * @return {*}
 */

function sanitize (data) {
  if (
    !isPrimitive(data) &&
    !Array.isArray(data) &&
    !isPlainObject(data)
  ) {
    // handle types that will probably cause issues in
    // the structured clone
    return Object.prototype.toString.call(data)
  } else {
    return data
  }
}

export function isPlainObject (obj) {
  return Object.prototype.toString.call(obj) === '[object Object]'
}

function isPrimitive (data) {
  if (data == null) {
    return true
  }
  const type = typeof data
  return (
    type === 'string' ||
    type === 'number' ||
    type === 'boolean' ||
    data instanceof RegExp
  )
}
<|endoftext|>


<commit_before>/**
 *  Copyright (c) 2015, David Sheldrick.
 *  All rights reserved.
 *
 *  This source code is licensed under the BSD-style license found in the
 *  LICENSE file in the root directory of this source tree.
 */

export function extend(obj, ...others) {
  for (let other of others) {
    for (let prop of Object.keys(other)) {
      obj[prop] = other[prop];
    }
  }
  return obj;
}

export function symbolValues (obj) {
  return Object.getOwnPropertySymbols(obj).map(s => obj[s]);
}

export function equals (a, b) {
  return a === b
         || Object.is && Object.is(a, b)
         || (a && a.equals && a.equals(b))
         || false;
}

export function withPrototype (obj, proto) {
  obj.prototype = proto;
  return obj;
}
<commit_msg>Use state-of-the-art equality checks. Yay JS!<commit_after>/**
 *  Copyright (c) 2015, David Sheldrick.
 *  All rights reserved.
 *
 *  This source code is licensed under the BSD-style license found in the
 *  LICENSE file in the root directory of this source tree.
 */

export function extend(obj, ...others) {
  for (let other of others) {
    for (let prop of Object.keys(other)) {
      obj[prop] = other[prop];
    }
  }
  return obj;
}

export function symbolValues (obj) {
  return Object.getOwnPropertySymbols(obj).map(s => obj[s]);
}

function _type(obj) {
  return Object.prototype.toString.call(obj).slice(8, -1);
}

function _is(a, b) {
  // SameValue algorithm
  if (a === b) { // Steps 1-5, 7-10
    // Steps 6.b-6.e: +0 != -0
    return a !== 0 || 1 / a === 1 / b;
  } else {
    // Step 6.a: NaN == NaN
    return a !== a && b !== b;
  }
}

function _equals(a, b, stackA, stackB) {
  var typeA = _type(a);
  if (typeA !== _type(b)) {
    return false;
  }

  if (typeA === 'Boolean' || typeA === 'Number' || typeA === 'String') {
    return typeof a === 'object' ?
      typeof b === 'object' && equals(a.valueOf(), b.valueOf()) :
      false;
  }

  if (typeA === 'RegExp') {
    // RegExp equality algorithm: http://stackoverflow.com/a/10776635
    return (a.source === b.source) &&
           (a.global === b.global) &&
           (a.ignoreCase === b.ignoreCase) &&
           (a.multiline === b.multiline) &&
           (a.sticky === b.sticky) &&
           (a.unicode === b.unicode);
  }

  if (Object(a) === a) {
    if (typeA === 'Date' && a.getTime() !== b.getTime()) {
      return false;
    }

    var keysA = Object.keys(a);
    if (keysA.length !== Object.keys(b).length) {
      return false;
    }

    if (!stackA) {
      stackA = [];
      stackB = [];
    }

    var idx = stackA.length - 1;
    while (idx >= 0) {
      if (stackA[idx] === a) {
        return stackB[idx] === b;
      }
      idx -= 1;
    }

    stackA[stackA.length] = a;
    stackB[stackB.length] = b;
    idx = keysA.length - 1;
    while (idx >= 0) {
      var key = keysA[idx];
      if (!Object.hasOwnProperty(key, b) || !equals(b[key], a[key], stackA, stackB)) {
        return false;
      }
      idx -= 1;
    }
    stackA.pop();
    stackB.pop();
    return true;
  }
  return false;
}

export function equals (a, b, stackA, stackB) {
  if ((Object.is && Object.is(a, b)) || _is(a, b)) {
    return true;
  }
  if (!(a && b)) return false;

  return (typeof a.equals === 'function' && a.equals(b))
         || (typeof b.equals === 'function' && b.equals(a))
         || _equals(a, b, stackA, stackB)
         || false;
}

export function withPrototype (obj, proto) {
  obj.prototype = proto;
  return obj;
}
<|endoftext|>


<commit_before>/*
 * menrva
 * https://github.com/phadej/menrva
 *
 * Copyright (c) 2014 Oleg Grenrus
 * Licensed under the MIT license.
 */

"use strict";

function identity(x) {
  return x;
}

function pluck(arr, property) {
  var len = arr.length;
  var res = new Array(len);
  for (var i = 0; i < len; i++) {
    res[i] = arr[i][property];
  }
  return res;
}

module.exports = {
  identity: identity,
  pluck: pluck,
};
<commit_msg>util.values<commit_after>/*
 * menrva
 * https://github.com/phadej/menrva
 *
 * Copyright (c) 2014 Oleg Grenrus
 * Licensed under the MIT license.
 */

"use strict";

function identity(x) {
  return x;
}

function pluck(arr, property) {
  var len = arr.length;
  var res = new Array(len);
  for (var i = 0; i < len; i++) {
    res[i] = arr[i][property];
  }
  return res;
}

function values(obj) {
  var arr = [];
  for (var k in obj) {
    arr.push(obj[k]);
  }
  return arr;
}

module.exports = {
  identity: identity,
  pluck: pluck,
  values: values,
};
<|endoftext|>