<commit_before>/*
 * Copyright 2013 The Polymer Authors. All rights reserved.
 * Use of this source code is governed by a BSD-style
 * license that can be found in the LICENSE file.
 */

/**
 * Implements `document.register`
 * @module CustomElements
*/

/**
 * Polyfilled extensions to the `document` object.
 * @class Document
*/

(function(scope) {

// imports

if (!scope) {
  scope = window.CustomElements = {flags:{}};
}
var flags = scope.flags;

// native document.register?

var hasNative = Boolean(document.webkitRegister || document.register);
var useNative = !flags.register && hasNative;

if (useNative) {

  // normalize
  document.register = document.register || document.webkitRegister;

  // stub
  var nop = function() {};

  // exports
  scope.registry = {};
  scope.upgradeElement = nop;

  scope.watchShadow = nop;
  scope.upgrade = nop;
  scope.upgradeAll = nop;
  scope.upgradeSubtree = nop;
  scope.observeDocument = nop;
  scope.upgradeDocument = nop;
  scope.takeRecords = nop;

} else {

  /**
   * Registers a custom tag name with the document.
   *
   * When a registered element is created, a `readyCallback` method is called
   * in the scope of the element. The `readyCallback` method can be specified on
   * either `options.prototype` or `options.lifecycle` with the latter taking
   * precedence.
   *
   * @method register
   * @param {String} name The tag name to register. Must include a dash ('-'),
   *    for example 'x-component'.
   * @param {Object} options
   *    @param {String} [options.extends]
   *      (_off spec_) Tag name of an element to extend (or blank for a new
   *      element). This parameter is not part of the specification, but instead
   *      is a hint for the polyfill because the extendee is difficult to infer.
   *      Remember that the input prototype must chain to the extended element's
   *      prototype (or HTMLElement.prototype) regardless of the value of
   *      `extends`.
   *    @param {Object} options.prototype The prototype to use for the new
   *      element. The prototype must inherit from HTMLElement.
   *    @param {Object} [options.lifecycle]
   *      Callbacks that fire at important phases in the life of the custom
   *      element.
   *
   * @example
   *      FancyButton = document.register("fancy-button", {
   *        extends: 'button',
   *        prototype: Object.create(HTMLButtonElement.prototype, {
   *          readyCallback: {
   *            value: function() {
   *              console.log("a fancy-button was created",
   *            }
   *          }
   *        })
   *      });
   * @return {Function} Constructor for the newly registered type.
   */
  function register(name, options) {
    //console.warn('document.register("' + name + '", ', options, ')');
    // construct a defintion out of options
    // TODO(sjmiles): probably should clone options instead of mutating it
    var definition = options || {};
    if (!name) {
      // TODO(sjmiles): replace with more appropriate error (EricB can probably
      // offer guidance)
      throw new Error('document.register: first argument `name` must not be empty');
    }
    if (name.indexOf('-') < 0) {
      // TODO(sjmiles): replace with more appropriate error (EricB can probably
      // offer guidance)
      throw new Error('document.register: first argument `name` must contain a dash (\'-\'). Argument was \'' + String(name) + '\'.');
    }
    // record name
    definition.name = name;
    // must have a prototype, default to an extension of HTMLElement
    // TODO(sjmiles): probably should throw if no prototype, check spec
    if (!definition.prototype) {
      // TODO(sjmiles): replace with more appropriate error (EricB can probably
      // offer guidance)
      throw new Error('Options missing required prototype property');
    }
    // ensure a lifecycle object so we don't have to null test it
    definition.lifecycle = definition.lifecycle || {};
    // build a list of ancestral custom elements (for native base detection)
    // TODO(sjmiles): we used to need to store this, but current code only
    // uses it in 'resolveTagName': it should probably be inlined
    definition.ancestry = ancestry(definition.extends);
    // extensions of native specializations of HTMLElement require localName
    // to remain native, and use secondary 'is' specifier for extension type
    resolveTagName(definition);
    // some platforms require modifications to the user-supplied prototype
    // chain
    resolvePrototypeChain(definition);
    // overrides to implement attributeChanged callback
    overrideAttributeApi(definition.prototype);
    // 7.1.5: Register the DEFINITION with DOCUMENT
    registerDefinition(name, definition);
    // 7.1.7. Run custom element constructor generation algorithm with PROTOTYPE
    // 7.1.8. Return the output of the previous step.
    definition.ctor = generateConstructor(definition);
    definition.ctor.prototype = definition.prototype;
    // force our .constructor to be our actual constructor
    definition.prototype.constructor = definition.ctor;
    // if initial parsing is complete
    if (scope.ready) {
      // upgrade any pre-existing nodes of this type
      scope.upgradeAll(document);
    }
    return definition.ctor;
  }

  function ancestry(extnds) {
    var extendee = registry[extnds];
    if (extendee) {
      return ancestry(extendee.extends).concat([extendee]);
    }
    return [];
  }

  function resolveTagName(definition) {
    // if we are explicitly extending something, that thing is our
    // baseTag, unless it represents a custom component
    var baseTag = definition.extends;
    // if our ancestry includes custom components, we only have a
    // baseTag if one of them does
    for (var i=0, a; (a=definition.ancestry[i]); i++) {
      baseTag = a.is && a.tag;
    }
    // our tag is our baseTag, if it exists, and otherwise just our name
    definition.tag = baseTag || definition.name;
    if (baseTag) {
      // if there is a base tag, use secondary 'is' specifier
      definition.is = definition.name;
    }
  }

  function resolvePrototypeChain(definition) {
    // if we don't support __proto__ we need to locate the native level
    // prototype for precise mixing in
    if (!Object.__proto__) {
      // default prototype
      var native = HTMLElement.prototype;
      // work out prototype when using type-extension
      if (definition.is) {
        var inst = document.createElement(definition.tag);
        native = Object.getPrototypeOf(inst);
      }
      // ensure __proto__ reference is installed at each point on the prototype
      // chain.
      // NOTE: On platforms without __proto__, a mixin strategy is used instead
      // of prototype swizzling. In this case, this generated __proto__ provides
      // limited support for prototype traversal.
      var proto = definition.prototype, ancestor;
      while (proto && (proto !== native)) {
        var ancestor = Object.getPrototypeOf(proto);
        proto.__proto__ = ancestor;
        proto = ancestor;
      }
    }
    // cache this in case of mixin
    definition.native = native;
  }

  // SECTION 4

  function instantiate(definition) {
    // 4.a.1. Create a new object that implements PROTOTYPE
    // 4.a.2. Let ELEMENT by this new object
    //
    // the custom element instantiation algorithm must also ensure that the
    // output is a valid DOM element with the proper wrapper in place.
    //
    return upgrade(domCreateElement(definition.tag), definition);
  }

  function upgrade(element, definition) {
    // some definitions specify an 'is' attribute
    if (definition.is) {
      element.setAttribute('is', definition.is);
    }
    // make 'element' implement definition.prototype
    implement(element, definition);
    // flag as upgraded
    element.__upgraded__ = true;
    // there should never be a shadow root on element at this point
    // we require child nodes be upgraded before `created`
    scope.upgradeSubtree(element);
    // lifecycle management
    created(element);
    // OUTPUT
    return element;
  }

  function implement(element, definition) {
    // prototype swizzling is best
    if (Object.__proto__) {
      element.__proto__ = definition.prototype;
    } else {
      // where above we can re-acquire inPrototype via
      // getPrototypeOf(Element), we cannot do so when
      // we use mixin, so we install a magic reference
      customMixin(element, definition.prototype, definition.native);
      element.__proto__ = definition.prototype;
    }
  }

  function customMixin(inTarget, inSrc, inNative) {
    // TODO(sjmiles): 'used' allows us to only copy the 'youngest' version of
    // any property. This set should be precalculated. We also need to
    // consider this for supporting 'super'.
    var used = {};
    // start with inSrc
    var p = inSrc;
    // sometimes the default is HTMLUnknownElement.prototype instead of
    // HTMLElement.prototype, so we add a test
    // the idea is to avoid mixing in native prototypes, so adding
    // the second test is WLOG
    while (p !== inNative && p !== HTMLUnknownElement.prototype) {
      var keys = Object.getOwnPropertyNames(p);
      for (var i=0, k; k=keys[i]; i++) {
        if (!used[k]) {
          Object.defineProperty(inTarget, k,
              Object.getOwnPropertyDescriptor(p, k));
          used[k] = 1;
        }
      }
      p = Object.getPrototypeOf(p);
    }
  }

  function created(element) {
    // invoke createdCallback
    if (element.createdCallback) {
      element.createdCallback();
    }
  }

  // attribute watching

  function overrideAttributeApi(prototype) {
    // overrides to implement callbacks
    // TODO(sjmiles): should support access via .attributes NamedNodeMap
    // TODO(sjmiles): preserves user defined overrides, if any
    var setAttribute = prototype.setAttribute;
    prototype.setAttribute = function(name, value) {
      changeAttribute.call(this, name, value, setAttribute);
    }
    var removeAttribute = prototype.removeAttribute;
    prototype.removeAttribute = function(name, value) {
      changeAttribute.call(this, name, value, removeAttribute);
    }
  }

  function changeAttribute(name, value, operation) {
    var oldValue = this.getAttribute(name);
    operation.apply(this, arguments);
    if (this.attributeChangedCallback
        && (this.getAttribute(name) !== oldValue)) {
      this.attributeChangedCallback(name, oldValue);
    }
  }

  // element registry (maps tag names to definitions)

  var registry = {};

  function registerDefinition(name, definition) {
    registry[name] = definition;
  }

  function generateConstructor(definition) {
    return function() {
      return instantiate(definition);
    };
  }

  function createElement(tag, typeExtension) {
    // TODO(sjmiles): ignore 'tag' when using 'typeExtension', we could
    // error check it, or perhaps there should only ever be one argument
    var definition = registry[typeExtension || tag];
    if (definition) {
      return new definition.ctor();
    }
    return domCreateElement(tag);
  }

  function upgradeElement(element) {
    if (!element.__upgraded__ && (element.nodeType === Node.ELEMENT_NODE)) {
      var type = element.getAttribute('is') || element.localName;
      var definition = registry[type];
      return definition && upgrade(element, definition);
    }
  }

  function cloneNode(deep) {
    // call original clone
    var n = domCloneNode.call(this, deep);
    // upgrade the element and subtree
    scope.upgradeAll(n);
    // return the clone
    return n;
  }
  // capture native createElement before we override it

  var domCreateElement = document.createElement.bind(document);

  // capture native cloneNode before we override it

  var domCloneNode = Node.prototype.cloneNode;

  // exports

  document.register = register;
  document.createElement = createElement; // override
  Node.prototype.cloneNode = cloneNode; // override

  scope.registry = registry;

  /**
   * Upgrade an element to a custom element. Upgrading an element
   * causes the custom prototype to be applied, an `is` attribute
   * to be attached (as needed), and invocation of the `readyCallback`.
   * `upgrade` does nothing if the element is already upgraded, or
   * if it matches no registered custom tag name.
   *
   * @method ugprade
   * @param {Element} element The element to upgrade.
   * @return {Element} The upgraded element.
   */
  scope.upgrade = upgradeElement;
}

scope.hasNative = hasNative;
scope.useNative = useNative;

})(window.CustomElements);
<commit_msg>Address same issue as PR 57. Android browser is not supported, but implemented fix since it's trivial.<commit_after>/*
 * Copyright 2013 The Polymer Authors. All rights reserved.
 * Use of this source code is governed by a BSD-style
 * license that can be found in the LICENSE file.
 */

/**
 * Implements `document.register`
 * @module CustomElements
*/

/**
 * Polyfilled extensions to the `document` object.
 * @class Document
*/

(function(scope) {

// imports

if (!scope) {
  scope = window.CustomElements = {flags:{}};
}
var flags = scope.flags;

// native document.register?

var hasNative = Boolean(document.webkitRegister || document.register);
var useNative = !flags.register && hasNative;

if (useNative) {

  // normalize
  document.register = document.register || document.webkitRegister;

  // stub
  var nop = function() {};

  // exports
  scope.registry = {};
  scope.upgradeElement = nop;

  scope.watchShadow = nop;
  scope.upgrade = nop;
  scope.upgradeAll = nop;
  scope.upgradeSubtree = nop;
  scope.observeDocument = nop;
  scope.upgradeDocument = nop;
  scope.takeRecords = nop;

} else {

  /**
   * Registers a custom tag name with the document.
   *
   * When a registered element is created, a `readyCallback` method is called
   * in the scope of the element. The `readyCallback` method can be specified on
   * either `options.prototype` or `options.lifecycle` with the latter taking
   * precedence.
   *
   * @method register
   * @param {String} name The tag name to register. Must include a dash ('-'),
   *    for example 'x-component'.
   * @param {Object} options
   *    @param {String} [options.extends]
   *      (_off spec_) Tag name of an element to extend (or blank for a new
   *      element). This parameter is not part of the specification, but instead
   *      is a hint for the polyfill because the extendee is difficult to infer.
   *      Remember that the input prototype must chain to the extended element's
   *      prototype (or HTMLElement.prototype) regardless of the value of
   *      `extends`.
   *    @param {Object} options.prototype The prototype to use for the new
   *      element. The prototype must inherit from HTMLElement.
   *    @param {Object} [options.lifecycle]
   *      Callbacks that fire at important phases in the life of the custom
   *      element.
   *
   * @example
   *      FancyButton = document.register("fancy-button", {
   *        extends: 'button',
   *        prototype: Object.create(HTMLButtonElement.prototype, {
   *          readyCallback: {
   *            value: function() {
   *              console.log("a fancy-button was created",
   *            }
   *          }
   *        })
   *      });
   * @return {Function} Constructor for the newly registered type.
   */
  function register(name, options) {
    //console.warn('document.register("' + name + '", ', options, ')');
    // construct a defintion out of options
    // TODO(sjmiles): probably should clone options instead of mutating it
    var definition = options || {};
    if (!name) {
      // TODO(sjmiles): replace with more appropriate error (EricB can probably
      // offer guidance)
      throw new Error('document.register: first argument `name` must not be empty');
    }
    if (name.indexOf('-') < 0) {
      // TODO(sjmiles): replace with more appropriate error (EricB can probably
      // offer guidance)
      throw new Error('document.register: first argument `name` must contain a dash (\'-\'). Argument was \'' + String(name) + '\'.');
    }
    // record name
    definition.name = name;
    // must have a prototype, default to an extension of HTMLElement
    // TODO(sjmiles): probably should throw if no prototype, check spec
    if (!definition.prototype) {
      // TODO(sjmiles): replace with more appropriate error (EricB can probably
      // offer guidance)
      throw new Error('Options missing required prototype property');
    }
    // ensure a lifecycle object so we don't have to null test it
    definition.lifecycle = definition.lifecycle || {};
    // build a list of ancestral custom elements (for native base detection)
    // TODO(sjmiles): we used to need to store this, but current code only
    // uses it in 'resolveTagName': it should probably be inlined
    definition.ancestry = ancestry(definition.extends);
    // extensions of native specializations of HTMLElement require localName
    // to remain native, and use secondary 'is' specifier for extension type
    resolveTagName(definition);
    // some platforms require modifications to the user-supplied prototype
    // chain
    resolvePrototypeChain(definition);
    // overrides to implement attributeChanged callback
    overrideAttributeApi(definition.prototype);
    // 7.1.5: Register the DEFINITION with DOCUMENT
    registerDefinition(name, definition);
    // 7.1.7. Run custom element constructor generation algorithm with PROTOTYPE
    // 7.1.8. Return the output of the previous step.
    definition.ctor = generateConstructor(definition);
    definition.ctor.prototype = definition.prototype;
    // force our .constructor to be our actual constructor
    definition.prototype.constructor = definition.ctor;
    // if initial parsing is complete
    if (scope.ready) {
      // upgrade any pre-existing nodes of this type
      scope.upgradeAll(document);
    }
    return definition.ctor;
  }

  function ancestry(extnds) {
    var extendee = registry[extnds];
    if (extendee) {
      return ancestry(extendee.extends).concat([extendee]);
    }
    return [];
  }

  function resolveTagName(definition) {
    // if we are explicitly extending something, that thing is our
    // baseTag, unless it represents a custom component
    var baseTag = definition.extends;
    // if our ancestry includes custom components, we only have a
    // baseTag if one of them does
    for (var i=0, a; (a=definition.ancestry[i]); i++) {
      baseTag = a.is && a.tag;
    }
    // our tag is our baseTag, if it exists, and otherwise just our name
    definition.tag = baseTag || definition.name;
    if (baseTag) {
      // if there is a base tag, use secondary 'is' specifier
      definition.is = definition.name;
    }
  }

  function resolvePrototypeChain(definition) {
    // if we don't support __proto__ we need to locate the native level
    // prototype for precise mixing in
    if (!Object.__proto__) {
      // default prototype
      var nativePrototype = HTMLElement.prototype;
      // work out prototype when using type-extension
      if (definition.is) {
        var inst = document.createElement(definition.tag);
        nativePrototype = Object.getPrototypeOf(inst);
      }
      // ensure __proto__ reference is installed at each point on the prototype
      // chain.
      // NOTE: On platforms without __proto__, a mixin strategy is used instead
      // of prototype swizzling. In this case, this generated __proto__ provides
      // limited support for prototype traversal.
      var proto = definition.prototype, ancestor;
      while (proto && (proto !== nativePrototype)) {
        var ancestor = Object.getPrototypeOf(proto);
        proto.__proto__ = ancestor;
        proto = ancestor;
      }
    }
    // cache this in case of mixin
    definition.native = nativePrototype;
  }

  // SECTION 4

  function instantiate(definition) {
    // 4.a.1. Create a new object that implements PROTOTYPE
    // 4.a.2. Let ELEMENT by this new object
    //
    // the custom element instantiation algorithm must also ensure that the
    // output is a valid DOM element with the proper wrapper in place.
    //
    return upgrade(domCreateElement(definition.tag), definition);
  }

  function upgrade(element, definition) {
    // some definitions specify an 'is' attribute
    if (definition.is) {
      element.setAttribute('is', definition.is);
    }
    // make 'element' implement definition.prototype
    implement(element, definition);
    // flag as upgraded
    element.__upgraded__ = true;
    // there should never be a shadow root on element at this point
    // we require child nodes be upgraded before `created`
    scope.upgradeSubtree(element);
    // lifecycle management
    created(element);
    // OUTPUT
    return element;
  }

  function implement(element, definition) {
    // prototype swizzling is best
    if (Object.__proto__) {
      element.__proto__ = definition.prototype;
    } else {
      // where above we can re-acquire inPrototype via
      // getPrototypeOf(Element), we cannot do so when
      // we use mixin, so we install a magic reference
      customMixin(element, definition.prototype, definition.native);
      element.__proto__ = definition.prototype;
    }
  }

  function customMixin(inTarget, inSrc, inNative) {
    // TODO(sjmiles): 'used' allows us to only copy the 'youngest' version of
    // any property. This set should be precalculated. We also need to
    // consider this for supporting 'super'.
    var used = {};
    // start with inSrc
    var p = inSrc;
    // sometimes the default is HTMLUnknownElement.prototype instead of
    // HTMLElement.prototype, so we add a test
    // the idea is to avoid mixing in native prototypes, so adding
    // the second test is WLOG
    while (p !== inNative && p !== HTMLUnknownElement.prototype) {
      var keys = Object.getOwnPropertyNames(p);
      for (var i=0, k; k=keys[i]; i++) {
        if (!used[k]) {
          Object.defineProperty(inTarget, k,
              Object.getOwnPropertyDescriptor(p, k));
          used[k] = 1;
        }
      }
      p = Object.getPrototypeOf(p);
    }
  }

  function created(element) {
    // invoke createdCallback
    if (element.createdCallback) {
      element.createdCallback();
    }
  }

  // attribute watching

  function overrideAttributeApi(prototype) {
    // overrides to implement callbacks
    // TODO(sjmiles): should support access via .attributes NamedNodeMap
    // TODO(sjmiles): preserves user defined overrides, if any
    var setAttribute = prototype.setAttribute;
    prototype.setAttribute = function(name, value) {
      changeAttribute.call(this, name, value, setAttribute);
    }
    var removeAttribute = prototype.removeAttribute;
    prototype.removeAttribute = function(name, value) {
      changeAttribute.call(this, name, value, removeAttribute);
    }
  }

  function changeAttribute(name, value, operation) {
    var oldValue = this.getAttribute(name);
    operation.apply(this, arguments);
    if (this.attributeChangedCallback
        && (this.getAttribute(name) !== oldValue)) {
      this.attributeChangedCallback(name, oldValue);
    }
  }

  // element registry (maps tag names to definitions)

  var registry = {};

  function registerDefinition(name, definition) {
    registry[name] = definition;
  }

  function generateConstructor(definition) {
    return function() {
      return instantiate(definition);
    };
  }

  function createElement(tag, typeExtension) {
    // TODO(sjmiles): ignore 'tag' when using 'typeExtension', we could
    // error check it, or perhaps there should only ever be one argument
    var definition = registry[typeExtension || tag];
    if (definition) {
      return new definition.ctor();
    }
    return domCreateElement(tag);
  }

  function upgradeElement(element) {
    if (!element.__upgraded__ && (element.nodeType === Node.ELEMENT_NODE)) {
      var type = element.getAttribute('is') || element.localName;
      var definition = registry[type];
      return definition && upgrade(element, definition);
    }
  }

  function cloneNode(deep) {
    // call original clone
    var n = domCloneNode.call(this, deep);
    // upgrade the element and subtree
    scope.upgradeAll(n);
    // return the clone
    return n;
  }
  // capture native createElement before we override it

  var domCreateElement = document.createElement.bind(document);

  // capture native cloneNode before we override it

  var domCloneNode = Node.prototype.cloneNode;

  // exports

  document.register = register;
  document.createElement = createElement; // override
  Node.prototype.cloneNode = cloneNode; // override

  scope.registry = registry;

  /**
   * Upgrade an element to a custom element. Upgrading an element
   * causes the custom prototype to be applied, an `is` attribute
   * to be attached (as needed), and invocation of the `readyCallback`.
   * `upgrade` does nothing if the element is already upgraded, or
   * if it matches no registered custom tag name.
   *
   * @method ugprade
   * @param {Element} element The element to upgrade.
   * @return {Element} The upgraded element.
   */
  scope.upgrade = upgradeElement;
}

scope.hasNative = hasNative;
scope.useNative = useNative;

})(window.CustomElements);
<|endoftext|>


<commit_before>if(undefined === Hoa)
    var Hoa = {};

Hoa.Graph = (Hoa.Graph || function ( __document__, __width__, __height__ ) {

    var paper   = this;
    var Element = function ( name ) {

        var that      = this;
        var translate = null;

        this.type = name;

        this.parent = __document__;

        this.node = document.createElementNS(
            'http://www.w3.org/2000/svg',
            name
        );

        this.append = function ( element ) {

            that.node.appendChild(element.node);
            element.parent = that;

            return that;
        };

        this.remove = function ( element ) {

            that.node.removeChild(element.node);
            element.parent = null;

            return that;
        };

        this.attr = function ( object ) {

            if('string' === typeof object)
                return that.node.getAttribute(object);

            for(key in object)
                that.node.setAttribute(key, object[key]);

            return that;
        };

        this.getBBox = function ( ) {

            var bbox = that.node.getBBox();

            if(null === translate)
                return bbox;

            return {
                height: bbox.height,
                width : bbox.width,
                x     : bbox.x + translate.x,
                y     : bbox.y + translate.y
            };
        };

        this.move = function ( x, y ) {

            var dx   = null;
            var dy   = null;
            var bbox = that.getBBox();
            var type = that.type;

            if('string' === typeof x) {

                sign = x.charAt(0);

                if('+' === sign || '-' === sign) {

                    dx = parseInt(x);
                    x  = bbox.x + dx;
                }
                else
                    x = parseInt(x);
            }

            if('string' === typeof y) {

                sign = y.charAt(0);

                if('+' === sign || '-' === sign) {

                    dy = parseInt(y);
                    y  = bbox.y + dy;
                }
                else
                    y = parseInt(y);
            }

            if('g' === type || 'path' === type) {

                if(null === dx)
                    dx = x - bbox.x;

                if(null === dy)
                    dy = y - bbox.y;

                if(null === translate)
                    translate = {x: dx, y: dy};
                else {

                    translate.x += dx;
                    translate.y += dy;
                }

                that.attr({
                    transform: 'translate(' +
                        translate.x + ', ' +
                        translate.y +
                    ')'
                });

                return that;
            }

            if('text' === type) {

                if(null !== dx)
                    x += dx + bbox.width / 2;

                if(null !== dy)
                    y += dy + bbox.height / 2;
            }

            that.attr({x: x, y: y});

            return that;
        };

        return this;
    };

    this.element = function ( name ) {

        var element = new Element(name);
        svg.append(element);

        return element;
    };

    this.rect = function ( x, y, width, height, radius, text ) {

        var group = new Element('g');
        svg.append(group);

        var rect = new Element('rect');
        rect.attr({
            x             : x,
            y             : y,
            width         : width,
            height        : height,
            rx            : radius || 3,
            ry            : radius || 3,
            fill          : 'url(#boxFill)',
            stroke        : '#fff',
            'stroke-width': '2px',
            filter        : 'url(#shadow)'
        });
        group.append(rect);

        if(undefined !== text) {

            var textBox = paper.text(x + width / 2, y + height / 2, text)
                               .attr({fill: '#ffffbe'});
            group.append(textBox);
        }

        return group;
    };

    this.circle = function ( cx, cy, r ) {

        var circle = new Element('circle');
        circle.attr({
            cx: cx,
            cy: cy,
            r : r || 10
        });
        svg.append(circle);

        return circle;
    };

    this.text = function ( x, y, text ) {

        var text_ = new Element('text');
        text_.attr({
            x                  : x,
            y                  : y,
            fill               : '#000',
            'text-anchor'      : 'middle',
            'dominant-baseline': 'middle'
        });
        text_.node.textContent = text;
        svg.append(text_);

        return text_;
    };

    this.path = function ( ) {

        var path = new Element('path');
        path.attr({
            fill          : 'none',
            stroke        : '#000',
            'stroke-width': '1px'
        });
        svg.append(path);

        return path;
    };

    this.grid = function ( x, y, width, height, columns, lines ) {

        var matrix      = [];
        var columnWidth = width / columns;
        var lineHeight  = height / lines;
        var stepX       = columnWidth / 2;
        var accX        = x;
        var accY        = y + lineHeight / 2;

        for(var l = 0; l < lines; ++l) {

            accX       = x;
            matrix[l]  = [];

            for(var c = 0; c < columns; ++c) {

                matrix[l][c] = {x: accX += stepX, y: accY};
                accX += stepX;
            }

            accY += lineHeight;
        }

        return {

            push: new function ( ) {

                var lastPosition = - 1;

                return function ( element, ix, iy ) {

                    var position = null;

                    if(undefined === iy)
                        position = ix || null;
                    else if(undefined !== ix)
                        position = iy * columns + ix;

                    if(null === position)
                        position = lastPosition + 1;

                    var point = matrix[Math.floor(position / columns)]
                                      [position % columns];
                    var bbox  = element.getBBox();
                    element.move(
                        point.x - bbox.width / 2,
                        point.y - bbox.height / 2
                    );
                    lastPosition = position;

                    return element;
                };
            }
        };
    };

    this.link = new function ( ) {

        var compute = function ( from, to ) {

            var fromBbox = from.getBBox();
            var toBbox   = to.getBBox();
            var fx       = fromBbox.x;
            var fy       = fromBbox.y;
            var fw       = fromBbox.width;
            var fh       = fromBbox.height;
            var tx       = toBbox.x;
            var tw       = toBbox.width;
            var fw2      = fw / 2;
            var fh2      = fh / 2;
            var ax       = fx + fw2;
            var by       = toBbox.y + toBbox.height / 2;
            var cx       = tx       + tw            / 2;
            var cy       = fy + fh2;
            var d        = fw2 / (cx - ax) * (cy - by);

            var points = {
                fromX  : fx + fw,
                fromY  : (fy + fh / 2) - d,
                toX    : tx,
                toY    : by + d,
                markerX: 1
            };

            if(points.fromX > points.toX) {

                var dd          = d * 2;
                points.fromX   -= fw;
                points.fromY   += dd;
                points.toX     += tw;
                points.toY     -= dd;
                points.markerX  = -1;
            }

            points.fromCX = points.toX - (points.toX - points.fromX) / 2;
            points.fromCY = points.fromY;
            points.toCX   = points.fromCX;
            points.toCY   = points.toY;

            return points;
        };

        this.between = function ( from, to, text ) {

            var link    = paper.path()
                               .attr({'marker-end': 'url(#arrow)'})
            var textBox = null;

            if(undefined !== text)
                textBox = paper.text(0, 0, text)
                               .attr({
                                   fill: '#f18d05',
                                   'font-size': '80%'
                               })

            var out     = {};
            out.element = link;
            out.text    = textBox;
            out.repaint = (function ( from, to, line ) {

                return function ( ) {

                    var points = compute(from, to);
                    line.attr({
                        d: 'M ' + points.fromX  + ',' + points.fromY  +
                           ' C' + points.fromCX + ',' + points.fromCY +
                           ' '  + points.toCX   + ',' + points.toCY   +
                           ' '  + (points.toX - 8 * points.markerX)
                                                + ',' + points.toY
                    });

                    if(null !== textBox)
                        textBox.move(
                            (points.fromX + points.toX) / 2,
                            (points.fromY + points.toY) / 2 - 20
                        );

                    return this;
                };
            })(from, to, link);

            out.repaint();

            return out;
        };
    };

    var svg = new Element('svg');
    svg.attr({
        version: '1.1',
        width  :  __width__,
        height : __height__
    });
    __document__.appendChild(svg.node);

    if(0 !== __width__ && 0 !== __height__) {

        __document__.style.width  = __width__ + 'px';
        __document__.style.height = __height__ + 'px';
    }

    this.svg = svg;

    return this;
});
<commit_msg>Remove @width and @height and use @viewBox.<commit_after>if(undefined === Hoa)
    var Hoa = {};

Hoa.Graph = (Hoa.Graph || function ( __document__, __width__, __height__ ) {

    var paper   = this;
    var Element = function ( name ) {

        var that      = this;
        var translate = null;

        this.type = name;

        this.parent = __document__;

        this.node = document.createElementNS(
            'http://www.w3.org/2000/svg',
            name
        );

        this.append = function ( element ) {

            that.node.appendChild(element.node);
            element.parent = that;

            return that;
        };

        this.remove = function ( element ) {

            that.node.removeChild(element.node);
            element.parent = null;

            return that;
        };

        this.attr = function ( object ) {

            if('string' === typeof object)
                return that.node.getAttribute(object);

            for(key in object)
                that.node.setAttribute(key, object[key]);

            return that;
        };

        this.getBBox = function ( ) {

            var bbox = that.node.getBBox();

            if(null === translate)
                return bbox;

            return {
                height: bbox.height,
                width : bbox.width,
                x     : bbox.x + translate.x,
                y     : bbox.y + translate.y
            };
        };

        this.move = function ( x, y ) {

            var dx   = null;
            var dy   = null;
            var bbox = that.getBBox();
            var type = that.type;

            if('string' === typeof x) {

                sign = x.charAt(0);

                if('+' === sign || '-' === sign) {

                    dx = parseInt(x);
                    x  = bbox.x + dx;
                }
                else
                    x = parseInt(x);
            }

            if('string' === typeof y) {

                sign = y.charAt(0);

                if('+' === sign || '-' === sign) {

                    dy = parseInt(y);
                    y  = bbox.y + dy;
                }
                else
                    y = parseInt(y);
            }

            if('g' === type || 'path' === type) {

                if(null === dx)
                    dx = x - bbox.x;

                if(null === dy)
                    dy = y - bbox.y;

                if(null === translate)
                    translate = {x: dx, y: dy};
                else {

                    translate.x += dx;
                    translate.y += dy;
                }

                that.attr({
                    transform: 'translate(' +
                        translate.x + ', ' +
                        translate.y +
                    ')'
                });

                return that;
            }

            if('text' === type) {

                if(null !== dx)
                    x += dx + bbox.width / 2;

                if(null !== dy)
                    y += dy + bbox.height / 2;
            }

            that.attr({x: x, y: y});

            return that;
        };

        return this;
    };

    this.element = function ( name ) {

        var element = new Element(name);
        svg.append(element);

        return element;
    };

    this.rect = function ( x, y, width, height, radius, text ) {

        var group = new Element('g');
        svg.append(group);

        var rect = new Element('rect');
        rect.attr({
            x             : x,
            y             : y,
            width         : width,
            height        : height,
            rx            : radius || 3,
            ry            : radius || 3,
            fill          : 'url(#boxFill)',
            stroke        : '#fff',
            'stroke-width': '2px',
            filter        : 'url(#shadow)'
        });
        group.append(rect);

        if(undefined !== text) {

            var textBox = paper.text(x + width / 2, y + height / 2, text)
                               .attr({fill: '#ffffbe'});
            group.append(textBox);
        }

        return group;
    };

    this.circle = function ( cx, cy, r ) {

        var circle = new Element('circle');
        circle.attr({
            cx: cx,
            cy: cy,
            r : r || 10
        });
        svg.append(circle);

        return circle;
    };

    this.text = function ( x, y, text ) {

        var text_ = new Element('text');
        text_.attr({
            x                  : x,
            y                  : y,
            fill               : '#000',
            'text-anchor'      : 'middle',
            'dominant-baseline': 'middle'
        });
        text_.node.textContent = text;
        svg.append(text_);

        return text_;
    };

    this.path = function ( ) {

        var path = new Element('path');
        path.attr({
            fill          : 'none',
            stroke        : '#000',
            'stroke-width': '1px'
        });
        svg.append(path);

        return path;
    };

    this.grid = function ( x, y, width, height, columns, lines ) {

        var matrix      = [];
        var columnWidth = width / columns;
        var lineHeight  = height / lines;
        var stepX       = columnWidth / 2;
        var accX        = x;
        var accY        = y + lineHeight / 2;

        for(var l = 0; l < lines; ++l) {

            accX       = x;
            matrix[l]  = [];

            for(var c = 0; c < columns; ++c) {

                matrix[l][c] = {x: accX += stepX, y: accY};
                accX += stepX;
            }

            accY += lineHeight;
        }

        return {

            push: new function ( ) {

                var lastPosition = - 1;

                return function ( element, ix, iy ) {

                    var position = null;

                    if(undefined === iy)
                        position = ix || null;
                    else if(undefined !== ix)
                        position = iy * columns + ix;

                    if(null === position)
                        position = lastPosition + 1;

                    var point = matrix[Math.floor(position / columns)]
                                      [position % columns];
                    var bbox  = element.getBBox();
                    element.move(
                        point.x - bbox.width / 2,
                        point.y - bbox.height / 2
                    );
                    lastPosition = position;

                    return element;
                };
            }
        };
    };

    this.link = new function ( ) {

        var compute = function ( from, to ) {

            var fromBbox = from.getBBox();
            var toBbox   = to.getBBox();
            var fx       = fromBbox.x;
            var fy       = fromBbox.y;
            var fw       = fromBbox.width;
            var fh       = fromBbox.height;
            var tx       = toBbox.x;
            var tw       = toBbox.width;
            var fw2      = fw / 2;
            var fh2      = fh / 2;
            var ax       = fx + fw2;
            var by       = toBbox.y + toBbox.height / 2;
            var cx       = tx       + tw            / 2;
            var cy       = fy + fh2;
            var d        = fw2 / (cx - ax) * (cy - by);

            var points = {
                fromX  : fx + fw,
                fromY  : (fy + fh / 2) - d,
                toX    : tx,
                toY    : by + d,
                markerX: 1
            };

            if(points.fromX > points.toX) {

                var dd          = d * 2;
                points.fromX   -= fw;
                points.fromY   += dd;
                points.toX     += tw;
                points.toY     -= dd;
                points.markerX  = -1;
            }

            points.fromCX = points.toX - (points.toX - points.fromX) / 2;
            points.fromCY = points.fromY;
            points.toCX   = points.fromCX;
            points.toCY   = points.toY;

            return points;
        };

        this.between = function ( from, to, text ) {

            var link    = paper.path()
                               .attr({'marker-end': 'url(#arrow)'})
            var textBox = null;

            if(undefined !== text)
                textBox = paper.text(0, 0, text)
                               .attr({
                                   fill: '#f18d05',
                                   'font-size': '80%'
                               })

            var out     = {};
            out.element = link;
            out.text    = textBox;
            out.repaint = (function ( from, to, line ) {

                return function ( ) {

                    var points = compute(from, to);
                    line.attr({
                        d: 'M ' + points.fromX  + ',' + points.fromY  +
                           ' C' + points.fromCX + ',' + points.fromCY +
                           ' '  + points.toCX   + ',' + points.toCY   +
                           ' '  + (points.toX - 8 * points.markerX)
                                                + ',' + points.toY
                    });

                    if(null !== textBox)
                        textBox.move(
                            (points.fromX + points.toX) / 2,
                            (points.fromY + points.toY) / 2 - 20
                        );

                    return this;
                };
            })(from, to, link);

            out.repaint();

            return out;
        };
    };

    var svg = new Element('svg');
    svg.attr({
        version: '1.1',
        viewBox: '0 0 ' + __width__ + ' ' + __height__
    });
    __document__.appendChild(svg.node);

    this.svg = svg;

    return this;
});
<|endoftext|>


<commit_before>const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const LodashModuleReplacementPlugin = require('lodash-webpack-plugin');

module.exports = {
  devtool: 'source-map',
  entry: [
    './src/index'
  ],
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'bundle.js'
  },
  plugins: [
    new LodashModuleReplacementPlugin(),
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.DefinePlugin({
      'process.env': {
        'NODE_ENV': JSON.stringify('production')
      }
    }),
    new HtmlWebpackPlugin({
      filename: 'index.html',
      title: 'Tab Editor'
    })
  ],
  module: {
    loaders: [{
      test: /\.js$/,
      loaders: ['babel'],
      include: path.join(__dirname, 'src')
    },
    {
      test: /\.json$/, loader: 'json'
    },
    {
      test: /\.css/, loaders: ['style', 'css']
    }]
  }
};
<commit_msg>opt in to caching for _.uniqBy<commit_after>const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const LodashModuleReplacementPlugin = require('lodash-webpack-plugin');

module.exports = {
  devtool: 'source-map',
  entry: [
    './src/index'
  ],
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'bundle.js'
  },
  plugins: [
    new LodashModuleReplacementPlugin({
      caching: true
    }),
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.DefinePlugin({
      'process.env': {
        'NODE_ENV': JSON.stringify('production')
      }
    }),
    new HtmlWebpackPlugin({
      filename: 'index.html',
      title: 'Tab Editor'
    })
  ],
  module: {
    loaders: [{
      test: /\.js$/,
      loaders: ['babel'],
      include: path.join(__dirname, 'src')
    },
    {
      test: /\.json$/, loader: 'json'
    },
    {
      test: /\.css/, loaders: ['style', 'css']
    }]
  }
};
<|endoftext|>


<commit_before>'use strict';

import React from 'react';

class Header extends React.Component {

  constructor(props) {
    super(props);
  }

  render() {
    var title = {
      fontSize: "20px",
      color: "white",
      padding: "20px",
      color: "black"
    }
    return (

TrySnippetssss

    );
  }

}

export default Header;
<commit_msg>header removed extra sss<commit_after>'use strict';

import React from 'react';

class Header extends React.Component {

  constructor(props) {
    super(props);
  }

  render() {
    var title = {
      fontSize: "20px",
      color: "white",
      padding: "20px",
      color: "black"
    }
    return (

TrySnippets

    );
  }

}

export default Header;
<|endoftext|>


<commit_before>'use strict';

const assert = require('assert');
const frete = require('./frete');

describe("Frete", function () {
    it('Set default options', function () {
        let defaultOptions = frete.defaultOptions;
        let expected = {
            sCepOrigem: '',
            sCdMaoPropria: 'N',
            sCdAvisoRecebimento: 'N',

            sDsSenha: '',
            nCdEmpresa: '',

            nCdServico: ''
        };

        assert.deepEqual(defaultOptions, expected);

        frete.cepOrigem('13467460').servico([
            frete.codigos.sedex,
            frete.codigos.sedex10,
            frete.codigos.pac
        ]);

        assert.notDeepEqual(defaultOptions, expected);

        expected.sCepOrigem = '13467460';
        expected.nCdServico = [ 40010, 40215, 41106 ];

        assert.deepEqual(defaultOptions, expected);
    });

    it('Request .prazo() ok', function (done) {
        let f = frete();

        f.prazo('13466321', function (err, results) {
            if (err) return done(err);

            let services = f.options.nCdServico;
            let hasAllServices = true;

            services.forEach(function (service) {
                let hasService = false;
                for (let i = 0; i < results.length; ++i) {
                    if (results[i].codigo == service) {
                        hasService = true;
                        break;
                    }
                }

                if (!hasService) {
                    hasAllServices = false;
                }
            });

            assert.equal(hasAllServices, true);
            done()
        });
    });

    it('Requests .prazo() validation errors', function (done) {
        let f = frete().servico('');

        f.prazo('13466321', function (err) {
            assert.equal(/Validation error/.test(err.message), true)
            assert.equal(/Required option: nCdServico has invalid value/.test(err.message), true)
            assert.equal(/Expected a valid: string/.test(err.message), true)

            f.servico(frete.codigos.sedex);

            assert.throws(function () {
                f.cepOrigem('');
            }, /Invalid string value/)

            f.options.sCepOrigem = '';

            f.prazo('13466321', function (err) {
                assert.equal(/Required option: sCepOrigem has invalid value/.test(err.message), true)
                done()
            });
        });
    });

    it('Request .preco()', function (done) {
        let f = frete();

        f
            .peso(1)
            .formato(1)
            .comprimento(16)
            .altura(2)
            .largura(11)
            .diametro(1)
            .maoPropria('N')
            .valorDeclarado(50)
            .avisoRecebimento('S');

        f.preco('13466321', function (err, results) {
            if (err) return done(err);

            let services = f.options.nCdServico;
            let hasAllServices = true;

            services.forEach(function (service) {
                let hasService = false;
                for (let i = 0; i < results.length; ++i) {
                    if (results[i].codigo == service) {
                        hasService = true;
                        break;
                    }
                }

                if (!hasService) {
                    hasAllServices = false;
                }
            });

            assert.equal(hasAllServices, true);

            done();
        });
    });

    it('Request .precoPrazo()', function (done) {
        let f = frete();

        f
            .peso(1)
            .formato(1)
            .comprimento(16)
            .altura(2)
            .largura(11)
            .diametro(1)
            .maoPropria('N')
            .valorDeclarado(50)
            .avisoRecebimento('S');

        f.precoPrazo('13466321', function (err, results) {
            if (err) return done(err);

            let services = f.options.nCdServico;
            let hasAllServices = true;

            services.forEach(function (service) {
                let hasService = false;
                for (let i = 0; i < results.length; ++i) {
                    if (results[i].codigo == service) {
                        hasService = true;
                        break;
                    }
                }

                if (!hasService) {
                    hasAllServices = false;
                }
            });

            assert.equal(hasAllServices, true);

            done();
        });
    });
});
<commit_msg>add test for correios error<commit_after>'use strict';

const assert = require('assert');
const frete = require('./frete');

describe("Frete", function () {
    it('Set default options', function () {
        let defaultOptions = frete.defaultOptions;
        let expected = {
            sCepOrigem: '',
            sCdMaoPropria: 'N',
            sCdAvisoRecebimento: 'N',

            sDsSenha: '',
            nCdEmpresa: '',

            nCdServico: ''
        };

        assert.deepEqual(defaultOptions, expected);

        frete.cepOrigem('13467460').servico([
            frete.codigos.sedex,
            frete.codigos.sedex10,
            frete.codigos.pac
        ]);

        assert.notDeepEqual(defaultOptions, expected);

        expected.sCepOrigem = '13467460';
        expected.nCdServico = [ 40010, 40215, 41106 ];

        assert.deepEqual(defaultOptions, expected);
    });

    it('Request .prazo() ok', function (done) {
        let f = frete();

        f.prazo('13466321', function (err, results) {
            if (err) return done(err);

            let services = f.options.nCdServico;
            let hasAllServices = true;

            services.forEach(function (service) {
                let hasService = false;
                for (let i = 0; i < results.length; ++i) {
                    if (results[i].codigo == service) {
                        hasService = true;
                        break;
                    }
                }

                if (!hasService) {
                    hasAllServices = false;
                }
            });

            assert.equal(hasAllServices, true);
            done()
        });
    });

    it('Requests .prazo() validation errors', function (done) {
        let f = frete().servico('');

        f.prazo('13466321', function (err) {
            assert.equal(/Validation error/.test(err.message), true)
            assert.equal(/Required option: nCdServico has invalid value/.test(err.message), true)
            assert.equal(/Expected a valid: string/.test(err.message), true)

            f.servico(frete.codigos.sedex);

            assert.throws(function () {
                f.cepOrigem('');
            }, /Invalid string value/)

            f.options.sCepOrigem = '';

            f.prazo('13466321', function (err) {
                assert.equal(/Required option: sCepOrigem has invalid value/.test(err.message), true)
                done()
            });
        });
    });

    it('Requests .prazo() correios error', function (done) {
        let f = frete();

        f.prazo('555555', function (err) {
            assert(/CEP de destino inexistente, consulte o Busca CEP./.test(err.message), true);
            assert(/Serviço indisponível para o trecho informado/.test(err.message), true);
            done();
        });
    });

    it('Request .preco()', function (done) {
        let f = frete();

        f
            .peso(1)
            .formato(1)
            .comprimento(16)
            .altura(2)
            .largura(11)
            .diametro(1)
            .maoPropria('N')
            .valorDeclarado(50)
            .avisoRecebimento('S');

        f.preco('13466321', function (err, results) {
            if (err) return done(err);

            let services = f.options.nCdServico;
            let hasAllServices = true;

            services.forEach(function (service) {
                let hasService = false;
                for (let i = 0; i < results.length; ++i) {
                    if (results[i].codigo == service) {
                        hasService = true;
                        break;
                    }
                }

                if (!hasService) {
                    hasAllServices = false;
                }
            });

            assert.equal(hasAllServices, true);

            done();
        });
    });

    it('Request .precoPrazo()', function (done) {
        let f = frete();

        f
            .peso(1)
            .formato(1)
            .comprimento(16)
            .altura(2)
            .largura(11)
            .diametro(1)
            .maoPropria('N')
            .valorDeclarado(50)
            .avisoRecebimento('S');

        f.precoPrazo('13466321', function (err, results) {
            if (err) return done(err);

            let services = f.options.nCdServico;
            let hasAllServices = true;

            services.forEach(function (service) {
                let hasService = false;
                for (let i = 0; i < results.length; ++i) {
                    if (results[i].codigo == service) {
                        hasService = true;
                        break;
                    }
                }

                if (!hasService) {
                    hasAllServices = false;
                }
            });

            assert.equal(hasAllServices, true);

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


<commit_before>'use strict';

/**
 * Download the release and store files in
 * tmp/downloads/
 *
 * (c) 2015 Matthias Hannig
 */

// == Load libraries
var logSymbols = require('log-symbols');
var Promise    = require('promise');
var http       = require('http');
var fs         = require('fs');

/**
 * Download release archive and signature.
 *
 * @return Promise
 */
var loadRelease = function(repositoryUrl) {
  return function(release) {
    console.log(logSymbols.info + ' Downloading release...');
    var promise = new Promise(function(resolve, reject){

      var archiveUrl    = repositoryUrl + '/' + release.file;
      var signatureUrl  = repositoryUrl + '/' + release.file + '.sig';

      var archiveFile   = fs.createWriteStream(
        process.cwd() + '/tmp/downloads/' + release.file
      );

      var signatureFile = fs.createWriteStream(
        process.cwd() + '/tmp/downloads/' + release.file + '.sig'
      );

      var reqArchive = http.get(archiveUrl, function(res){
        if(res.statusCode == 200) {
          res.pipe(archiveFile);
        }
        else {
          console.error(logSymbols.error + ' Could not download archive.');
          reject('archive download filed');
        }

        res.on('end', function(){
          console.log(logSymbols.success + ' Archive ' + release.file + ' downloaded.');
        });
      });

      var reqSignature = http.get(signatureUrl, function(res){
        res.pipe(signatureFile);
        res.on('end', function(){
          console.log(logSymbols.success + ' Archive signature downloaded.');
        });
      });

    });
    return promise;
  };
};

// == Export module
module.exports = loadRelease;

<commit_msg>download with progress.<commit_after>'use strict';

/**
 * Download the release and store files in
 * tmp/downloads/
 *
 * (c) 2015 Matthias Hannig
 */

// == Load libraries
var logSymbols = require('log-symbols');
var Promise    = require('promise');
var fs         = require('fs');

var ProgressBar  = require('progress');
var request      = require('request');

// == Helper

/**
 * Download files
 * @return Promise
 */
var downloadFile = function( filename, url ) {
  var promise = new Promise(function(resolve, reject){

    var file = fs.createWriteStream(
      process.cwd() + '/tmp/downloads/' + filename
    );

    // Start download with progress bar
    request
      .get(url)
      .on('response',function(res) {
        // Create progress bar
        var total = parseInt(res.headers['content-length'], 10);
        var bar = new ProgressBar('  [:bar] :percent :etas', {
          complete: '=',
          incomplete: ' ',
          width: 40,
          total: total
        });

        res.on('data', function(chunk) {
          bar.tick(chunk.length);
        });
      })
      .on('error',function(err) {
        reject(err);
      })
      .pipe(file)
      .on('error', function(err) {
        reject(err);
      })
      .on('close', function() {
        console.log(logSymbols.success + ' finished downloading ' + filename);
        resolve(filename);
      });
  });
  return promise;
};

/**
 * Download archive signature.
 */

/**
 * Download release archive.
 *
 * @return Promise
 */
var loadRelease = function(repositoryUrl) {
  return function(release) {
    console.log(logSymbols.info + ' Downloading reelease archive');
    var promise = new Promise(function(resolve, reject){

      // Download release
      var archiveUrl       = repositoryUrl + '/' + release.file;
      var archiveFilename  = release.file;

      var sigUrl       = repositoryUrl + '/' + release.file + '.sig';
      var sigFilename  = release.file + '.sig';

      Promise.all([
        downloadFile(archiveFilename, archiveUrl        ),
        downloadFile(sigFilename,     sigUrl,      false) // no progress
      ])
        .then(
          function(result){
            resolve(release);
          },
          function(err){
            reject(err);
          }
        );
    });
    return promise;
  };
};

// == Export module
module.exports = loadRelease;

<|endoftext|>


<commit_before>

function configureEditor(editorId)
{
    // configure ace editor
    var editor = ace.edit(editorId);
    editor.setTheme("ace/theme/GitHub");
    editor.getSession().setMode("ace/mode/python");
    editor.getSession().setUseSoftTabs(true);
    return editor
}

$( document ).ready(function() {

    var responseEditor = configureEditor("response-editor");

    $( "#test-form" ).submit(function( event )
    {

        // Stop form from submitting normally
        event.preventDefault();
        var $form = $( this );
        var data = $form.serialize();
        var url = $form.attr( "action" );

        var posting = $.post( url, data );

        posting.done(function( data ) {
            $( "#unit-tests ul" ).append( "
" + data + "
" );
        });
    });

    $("#response-form").submit(function ( event)
    {
        console.log("response form submitted");
        // Stop form from submitting normally
        event.preventDefault();
        var $form = $( this );

        var code = responseEditor.getValue();
        console.log(code);
        $("#user_code").val(code);
        var data = $form.serialize();
        var url = $form.attr( "action" );

        $.post( url, data );
    });
});

<commit_msg>updated tutor.py to submit study response form after copying response from editor div to hidden form<commit_after>

function configureEditor(editorId)
{
    // configure ace editor
    var editor = ace.edit(editorId);
    editor.setTheme("ace/theme/GitHub");
    editor.getSession().setMode("ace/mode/python");
    editor.getSession().setUseSoftTabs(true);
    return editor
}

$( document ).ready(function() {

    var responseEditor = configureEditor("response-editor");

    $( "#test-form" ).submit(function( event )
    {

        // Stop form from submitting normally
        event.preventDefault();
        var $form = $( this );
        var data = $form.serialize();
        var url = $form.attr( "action" );

        var posting = $.post( url, data );

        posting.done(function( data ) {
            $( "#unit-tests ul" ).append( "
" + data + "
" );
        });
    });

    $("#response-form").submit(function ( event)
    {
        console.log("response form submitted");
        // Stop form from submitting normally
        event.preventDefault();
        var $form = $( this );

        var code = responseEditor.getValue();
        console.log(code);
        $("#user_code").val(code);
        var data = $form.serialize();
        var url = $form.attr( "action" );
        $('form').unbind().submit();     });
});

<|endoftext|>


<commit_before>/* get list of plots to work on... */

$(document).ready(function() {
    load_all_plots();

    var categories = JSON.parse($('#cea-dashboard-add-plot').attr('data-cea-categories'));
    console.log("assigned categories!");
    console.log(categories);

    $("[id|=cea-plot-category]").on("change", function(){
        let category_name = this.value;
        $("[id|=cea-plot-name]").empty();
        $.each(categories[category_name]["plots"], function(i, p){
            console.log(p);
            $("[id|=cea-plot-name]").append($("<option></option>").attr("value", p.id).text(p.name));
        });

        console.log(categories[category_name]["plots"]);
    });

    $("#cea-dashboard-edit-plot").on("show.bs.modal", function (e) {
        let plot_index = e.relatedTarget.dataset.plotIndex;
        let dashboard_index = e.relatedTarget.dataset.dashboardIndex;
        let url = `plot-parameters/${dashboard_index}/${plot_index}`;
        $.get(url, function (data) {
            $("#cea-dashboard-edit-plot-form").html(data)
                .attr("action", url)
                .attr("method", "POST");
            $(".selectpicker").selectpicker({"actionsBox": true});
            $(".js-switch").each(function(_, checkbox){
                console.log("setting up Switchery");
                console.log(checkbox);
                switcher = new Switchery(checkbox);
            });
        }).fail(function (data) {
            console.log("something went terribly wrong?!");
            console.log(data);
        });
    });

    $("#cea-dashboard-replace-plot").on("show.bs.modal", function (e) {
        let plot_index = e.relatedTarget.dataset.plotIndex;
        let dashboard_index = e.relatedTarget.dataset.dashboardIndex;
        let url = `replace-plot/${dashboard_index}/${plot_index}`;
        $("#cea-dashboard-replace-plot-form").attr("action", url)
            .attr("method", "POST");
    });

    $("#cea-dashboard-edit-plot-form").submit(function (e) {
        e.preventDefault();
        $.post($("#cea-dashboard-edit-plot-form").attr("action"), get_parameter_values(), function(data){
            console.log(data);
            location.reload();
        }, "json");
        return false;
    });

    $("#dashboard-selector").val(window.location.href.split('/').pop().replace(/[^0-9]/g, ''))
        .change(function () {
            let value = $(this).val();
            if(value === "manage") {
                window.location.href = "./manage";
            } else if(value !== "new") {
                window.location.href = `./${value}`;
            }
        });
});

function load_all_plots() {
    $(".cea-plot").map(function() {
        let dashboard_index = this.dataset.ceaDashboardIndex;
        let plot_index = this.dataset.ceaPlotIndex;
        let content_div = $(`#x_content-${dashboard_index}-${plot_index}`);

        $.get(`../div/${dashboard_index}/${plot_index}`, function(data){
            content_div.children().replaceWith(data);
            $('#table-btn-'+plot_index).show();
        }).fail(function(data) {
            // Server error
            if (data.status === 500) {
                content_div.children().replaceWith("ERROR: " + $(data.responseText).filter("p").text());
                console.log("error creating plot: ", `#x_content-${dashboard_index}-${plot_index}`);
                console.log(data);
            }
            // Missing files
            if (data.status === 404) {
                content_div.children().replaceWith(data.responseText);
            }
        });
    });
}

function duplicate_dashboard(dashboard_index) {
    $.get(`./duplicate/${dashboard_index}`, {}, function(html) {
        $('#cea-prompt .modal-content').html(html);
        $('#cea-prompt').modal({'show': true, 'backdrop': 'static'});
    });
}

function add_new_dashboard() {
    $.get("new", function (html) {
        $("#cea-prompt .modal-content").html(html);
        $("#cea-prompt").modal({"show": true, "backdrop": "static"});
    });
}

function open_table(element) {
    let style = document.styleSheets[0].ownerNode.cloneNode();
    let height = 500;
    let width = 900;
    let table = window.open(`../table/${element.dataset.dashboardIndex}/${element.dataset.plotIndex}`,
        'popUpWindow', `height=${height},width=${width},location=no,menubar=no,status=no,titlebar=no,resizable`);
    table.onload = function() {
        table.document.title = `City Energy Analyst | ${element.dataset.plotTitle} Table`;
        table.document.body.innerHTML = table.document.body.innerHTML || '
Table does not exist.
';
        table.document.body.innerHTML = `<h1>${element.dataset.plotTitle}</h1><br>${table.document.body.innerHTML}`;
        table.document.head.append(style);
    }
}

window.addEventListener('resize', function () {
    console.log('resizing');
    $.each($('.plotly-graph-div.js-plotly-plot'), function () {
        Plotly.Plots.resize($(this).attr('id'));
    });
});<commit_msg>Allow multiple table popup<commit_after>/* get list of plots to work on... */

$(document).ready(function() {
    load_all_plots();

    var categories = JSON.parse($('#cea-dashboard-add-plot').attr('data-cea-categories'));
    console.log("assigned categories!");
    console.log(categories);

    $("[id|=cea-plot-category]").on("change", function(){
        let category_name = this.value;
        $("[id|=cea-plot-name]").empty();
        $.each(categories[category_name]["plots"], function(i, p){
            console.log(p);
            $("[id|=cea-plot-name]").append($("<option></option>").attr("value", p.id).text(p.name));
        });

        console.log(categories[category_name]["plots"]);
    });

    $("#cea-dashboard-edit-plot").on("show.bs.modal", function (e) {
        let plot_index = e.relatedTarget.dataset.plotIndex;
        let dashboard_index = e.relatedTarget.dataset.dashboardIndex;
        let url = `plot-parameters/${dashboard_index}/${plot_index}`;
        $.get(url, function (data) {
            $("#cea-dashboard-edit-plot-form").html(data)
                .attr("action", url)
                .attr("method", "POST");
            $(".selectpicker").selectpicker({"actionsBox": true});
            $(".js-switch").each(function(_, checkbox){
                console.log("setting up Switchery");
                console.log(checkbox);
                switcher = new Switchery(checkbox);
            });
        }).fail(function (data) {
            console.log("something went terribly wrong?!");
            console.log(data);
        });
    });

    $("#cea-dashboard-replace-plot").on("show.bs.modal", function (e) {
        let plot_index = e.relatedTarget.dataset.plotIndex;
        let dashboard_index = e.relatedTarget.dataset.dashboardIndex;
        let url = `replace-plot/${dashboard_index}/${plot_index}`;
        $("#cea-dashboard-replace-plot-form").attr("action", url)
            .attr("method", "POST");
    });

    $("#cea-dashboard-edit-plot-form").submit(function (e) {
        e.preventDefault();
        $.post($("#cea-dashboard-edit-plot-form").attr("action"), get_parameter_values(), function(data){
            console.log(data);
            location.reload();
        }, "json");
        return false;
    });

    $("#dashboard-selector").val(window.location.href.split('/').pop().replace(/[^0-9]/g, ''))
        .change(function () {
            let value = $(this).val();
            if(value === "manage") {
                window.location.href = "./manage";
            } else if(value !== "new") {
                window.location.href = `./${value}`;
            }
        });
});

function load_all_plots() {
    $(".cea-plot").map(function() {
        let dashboard_index = this.dataset.ceaDashboardIndex;
        let plot_index = this.dataset.ceaPlotIndex;
        let content_div = $(`#x_content-${dashboard_index}-${plot_index}`);

        $.get(`../div/${dashboard_index}/${plot_index}`, function(data){
            content_div.children().replaceWith(data);
            $('#table-btn-'+plot_index).show();
        }).fail(function(data) {
            // Server error
            if (data.status === 500) {
                content_div.children().replaceWith("ERROR: " + $(data.responseText).filter("p").text());
                console.log("error creating plot: ", `#x_content-${dashboard_index}-${plot_index}`);
                console.log(data);
            }
            // Missing files
            if (data.status === 404) {
                content_div.children().replaceWith(data.responseText);
            }
        });
    });
}

function duplicate_dashboard(dashboard_index) {
    $.get(`./duplicate/${dashboard_index}`, {}, function(html) {
        $('#cea-prompt .modal-content').html(html);
        $('#cea-prompt').modal({'show': true, 'backdrop': 'static'});
    });
}

function add_new_dashboard() {
    $.get("new", function (html) {
        $("#cea-prompt .modal-content").html(html);
        $("#cea-prompt").modal({"show": true, "backdrop": "static"});
    });
}

function open_table(element) {
    let style = document.styleSheets[0].ownerNode.cloneNode();
    let height = 500;
    let width = 900;
    let table = window.open(`../table/${element.dataset.dashboardIndex}/${element.dataset.plotIndex}`,
        `table-${element.dataset.dashboardIndex}-${element.dataset.plotIndex}`,
        `height=${height},width=${width},location=no,menubar=no,status=no,titlebar=no,resizable`);
    table.onload = function() {
        table.document.title = `City Energy Analyst | ${element.dataset.plotTitle} Table`;
        table.document.body.innerHTML = table.document.body.innerHTML || '
Table does not exist.
';
        table.document.body.innerHTML = `<h1>${element.dataset.plotTitle}</h1><br>${table.document.body.innerHTML}`;
        table.document.head.append(style);
    }
}

window.addEventListener('resize', function () {
    console.log('resizing');
    $.each($('.plotly-graph-div.js-plotly-plot'), function () {
        Plotly.Plots.resize($(this).attr('id'));
    });
});<|endoftext|>


<commit_before>import PropTypes from 'prop-types'
import React from 'react'
import { findDOMNode } from 'react-dom'
import cn from 'classnames'

import Selection, { getBoundsForNode, isEvent } from './Selection'
import dates from './utils/dates'
import * as TimeSlotUtils from './utils/TimeSlots'
import { isSelected } from './utils/selection'

import { notify } from './utils/helpers'
import * as DayEventLayout from './utils/DayEventLayout'
import TimeSlotGroup from './TimeSlotGroup'
import TimeGridEvent from './TimeGridEvent'

class DayColumn extends React.Component {
  state = { selecting: false, timeIndicatorPosition: null }

  constructor(...args) {
    super(...args)

    this.slotMetrics = TimeSlotUtils.getSlotMetrics(this.props)
  }

  componentDidMount() {
    this.props.selectable && this._selectable()

    if (this.props.isNow) {
      this.setTimeIndicatorPositionUpdateInterval()
    }
  }

  componentWillUnmount() {
    this._teardownSelectable()
    this.clearTimeIndicatorInterval()
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.selectable && !this.props.selectable) this._selectable()
    if (!nextProps.selectable && this.props.selectable)
      this._teardownSelectable()

    this.slotMetrics = this.slotMetrics.update(nextProps)
  }

  componentDidUpdate(prevProps, prevState) {
    if (prevProps.isNow !== this.props.isNow) {
      this.clearTimeIndicatorInterval()

      if (this.props.isNow) {
        this.setTimeIndicatorPositionUpdateInterval(
          prevState.timeIndicatorPosition === this.state.timeIndicatorPosition
        )
      }
    }
  }

  intervalTriggered = false
  /**
   * @param tail {Boolean} - whether `positionTimeIndicator` call should be
   *   deferred or called upon setting interval (`true` - if deferred);
   */
  setTimeIndicatorPositionUpdateInterval(tail = false) {
    if (!this.intervalTriggered && !tail) {
      this.positionTimeIndicator()
    }

    this._timeIndicatorTimeout = window.setTimeout(() => {
      this.intervalTriggered = true
      this.positionTimeIndicator()
      this.setTimeIndicatorPositionUpdateInterval()
    }, 60000)
  }

  clearTimeIndicatorInterval() {
    this.intervalTriggered = false
    window.clearTimeout(this._timeIndicatorTimeout)
  }

  positionTimeIndicator() {
    const { min, max, getNow } = this.props
    const current = getNow()

    if (current >= min && current <= max) {
      const { top } = this.slotMetrics.getRange(current, current)
      this.setState({ timeIndicatorPosition: top })
    } else {
      this.clearTimeIndicatorInterval()
    }
  }

  render() {
    const {
      max,
      rtl,
      isNow,
      resource,
      accessors,
      localizer,
      getters: { dayProp, ...getters },
      components: { eventContainerWrapper: EventContainer, ...components },
    } = this.props

    let { slotMetrics } = this
    let { selecting, top, height, startDate, endDate } = this.state

    let selectDates = { start: startDate, end: endDate }

    const { className, style } = dayProp(max)

    return (

        {slotMetrics.groups.map((grp, idx) => (
          <TimeSlotGroup
            key={idx}
            group={grp}
            resource={resource}
            getters={getters}
            components={components}
          />
        ))}
        <EventContainer
          localizer={localizer}
          resource={resource}
          accessors={accessors}
          getters={getters}
          components={components}
          slotMetrics={slotMetrics}
        >

            {this.renderEvents()}

        </EventContainer>

        {selecting && (

            {localizer.format(selectDates, 'selectRangeFormat')}

        )}
        {isNow && (
          <div
            className="rbc-current-time-indicator"
            style={{ top: `${this.state.timeIndicatorPosition}%` }}
          />
        )}

    )
  }

  renderEvents = () => {
    let {
      events,
      rtl: isRtl,
      selected,
      accessors,
      localizer,
      getters,
      components,
      step,
      timeslots,
    } = this.props

    const { slotMetrics } = this
    const { messages } = localizer

    let styledEvents = DayEventLayout.getStyledEvents({
      events,
      accessors,
      slotMetrics,
      minimumStartDifference: Math.ceil((step * timeslots) / 2),
    })

    return styledEvents.map(({ event, style }, idx) => {
      let end = accessors.end(event)
      let start = accessors.start(event)
      let format = 'eventTimeRangeFormat'
      let label

      const startsBeforeDay = slotMetrics.startsBeforeDay(start)
      const startsAfterDay = slotMetrics.startsAfterDay(end)

      if (startsBeforeDay) format = 'eventTimeRangeEndFormat'
      else if (startsAfterDay) format = 'eventTimeRangeStartFormat'

      if (startsBeforeDay && startsAfterDay) label = messages.allDay
      else label = localizer.format({ start, end }, format)

      let continuesEarlier = startsBeforeDay || slotMetrics.startsBefore(start)
      let continuesLater = startsAfterDay || slotMetrics.startsAfter(end)

      return (
        <TimeGridEvent
          style={style}
          event={event}
          label={label}
          key={'evt_' + idx}
          getters={getters}
          isRtl={isRtl}
          components={components}
          continuesEarlier={continuesEarlier}
          continuesLater={continuesLater}
          accessors={accessors}
          selected={isSelected(event, selected)}
          onClick={e => this._select(event, e)}
          onDoubleClick={e => this._doubleClick(event, e)}
        />
      )
    })
  }

  _selectable = () => {
    let node = findDOMNode(this)
    let selector = (this._selector = new Selection(() => findDOMNode(this), {
      longPressThreshold: this.props.longPressThreshold,
    }))

    let maybeSelect = box => {
      let onSelecting = this.props.onSelecting
      let current = this.state || {}
      let state = selectionState(box)
      let { startDate: start, endDate: end } = state

      if (onSelecting) {
        if (
          (dates.eq(current.startDate, start, 'minutes') &&
            dates.eq(current.endDate, end, 'minutes')) ||
          onSelecting({ start, end }) === false
        )
          return
      }

      if (
        this.state.start !== state.start ||
        this.state.end !== state.end ||
        this.state.selecting !== state.selecting
      ) {
        this.setState(state)
      }
    }

    let selectionState = point => {
      let currentSlot = this.slotMetrics.closestSlotFromPoint(
        point,
        getBoundsForNode(node)
      )

      if (!this.state.selecting) this._initialSlot = currentSlot

      let initialSlot = this._initialSlot
      if (initialSlot === currentSlot)
        currentSlot = this.slotMetrics.nextSlot(initialSlot)

      const selectRange = this.slotMetrics.getRange(
        dates.min(initialSlot, currentSlot),
        dates.max(initialSlot, currentSlot)
      )

      return {
        ...selectRange,
        selecting: true,

        top: `${selectRange.top}%`,
        height: `${selectRange.height}%`,
      }
    }

    let selectorClicksHandler = (box, actionType) => {
      if (!isEvent(findDOMNode(this), box)) {
        const { startDate, endDate } = selectionState(box)
        this._selectSlot({
          startDate,
          endDate,
          action: actionType,
          box,
        })
      }
      this.setState({ selecting: false })
    }

    selector.on('selecting', maybeSelect)
    selector.on('selectStart', maybeSelect)

    selector.on('beforeSelect', box => {
      if (this.props.selectable !== 'ignoreEvents') return

      return !isEvent(findDOMNode(this), box)
    })

    selector.on('click', box => selectorClicksHandler(box, 'click'))

    selector.on('doubleClick', box => selectorClicksHandler(box, 'doubleClick'))

    selector.on('select', bounds => {
      if (this.state.selecting) {
        this._selectSlot({ ...this.state, action: 'select', bounds })
        this.setState({ selecting: false })
      }
    })

    selector.on('reset', () => {
      if (this.state.selecting) {
        this.setState({ selecting: false })
      }
    })
  }

  _teardownSelectable = () => {
    if (!this._selector) return
    this._selector.teardown()
    this._selector = null
  }

  _selectSlot = ({ startDate, endDate, action, bounds, box }) => {
    let current = startDate,
      slots = []

    while (dates.lte(current, endDate)) {
      slots.push(current)
      current = dates.add(current, this.props.step, 'minutes')
    }

    notify(this.props.onSelectSlot, {
      slots,
      start: startDate,
      end: endDate,
      resourceId: this.props.resource,
      action,
      bounds,
      box,
    })
  }

  _select = (...args) => {
    notify(this.props.onSelectEvent, args)
  }

  _doubleClick = (...args) => {
    notify(this.props.onDoubleClickEvent, args)
  }
}

DayColumn.propTypes = {
  events: PropTypes.array.isRequired,
  step: PropTypes.number.isRequired,
  date: PropTypes.instanceOf(Date).isRequired,
  min: PropTypes.instanceOf(Date).isRequired,
  max: PropTypes.instanceOf(Date).isRequired,
  getNow: PropTypes.func.isRequired,
  isNow: PropTypes.bool,

  rtl: PropTypes.bool,

  accessors: PropTypes.object.isRequired,
  components: PropTypes.object.isRequired,
  getters: PropTypes.object.isRequired,
  localizer: PropTypes.object.isRequired,

  showMultiDayTimes: PropTypes.bool,
  culture: PropTypes.string,
  timeslots: PropTypes.number,

  selected: PropTypes.object,
  selectable: PropTypes.oneOf([true, false, 'ignoreEvents']),
  eventOffset: PropTypes.number,
  longPressThreshold: PropTypes.number,

  onSelecting: PropTypes.func,
  onSelectSlot: PropTypes.func.isRequired,
  onSelectEvent: PropTypes.func.isRequired,
  onDoubleClickEvent: PropTypes.func.isRequired,

  className: PropTypes.string,
  dragThroughEvents: PropTypes.bool,
  resource: PropTypes.any,
}

DayColumn.defaultProps = {
  dragThroughEvents: true,
  timeslots: 2,
}

export default DayColumn
<commit_msg>fix: misplacement of current time indicator (#1239)<commit_after>import PropTypes from 'prop-types'
import React from 'react'
import { findDOMNode } from 'react-dom'
import cn from 'classnames'

import Selection, { getBoundsForNode, isEvent } from './Selection'
import dates from './utils/dates'
import * as TimeSlotUtils from './utils/TimeSlots'
import { isSelected } from './utils/selection'

import { notify } from './utils/helpers'
import * as DayEventLayout from './utils/DayEventLayout'
import TimeSlotGroup from './TimeSlotGroup'
import TimeGridEvent from './TimeGridEvent'

class DayColumn extends React.Component {
  state = { selecting: false, timeIndicatorPosition: null }

  constructor(...args) {
    super(...args)

    this.slotMetrics = TimeSlotUtils.getSlotMetrics(this.props)
  }

  componentDidMount() {
    this.props.selectable && this._selectable()

    if (this.props.isNow) {
      this.setTimeIndicatorPositionUpdateInterval()
    }
  }

  componentWillUnmount() {
    this._teardownSelectable()
    this.clearTimeIndicatorInterval()
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.selectable && !this.props.selectable) this._selectable()
    if (!nextProps.selectable && this.props.selectable)
      this._teardownSelectable()

    this.slotMetrics = this.slotMetrics.update(nextProps)
  }

  componentDidUpdate(prevProps, prevState) {
    const getNowChanged = !dates.eq(
      prevProps.getNow(),
      this.props.getNow(),
      'minutes'
    )

    if (prevProps.isNow !== this.props.isNow || getNowChanged) {
      this.clearTimeIndicatorInterval()

      if (this.props.isNow) {
        const tail =
          !getNowChanged &&
          dates.eq(prevProps.date, this.props.date, 'minutes') &&
          prevState.timeIndicatorPosition === this.state.timeIndicatorPosition

        this.setTimeIndicatorPositionUpdateInterval(tail)
      }
    }
  }

  intervalTriggered = false
  /**
   * @param tail {Boolean} - whether `positionTimeIndicator` call should be
   *   deferred or called upon setting interval (`true` - if deferred);
   */
  setTimeIndicatorPositionUpdateInterval(tail = false) {
    if (!this.intervalTriggered && !tail) {
      this.positionTimeIndicator()
    }

    this._timeIndicatorTimeout = window.setTimeout(() => {
      this.intervalTriggered = true
      this.positionTimeIndicator()
      this.setTimeIndicatorPositionUpdateInterval()
    }, 60000)
  }

  clearTimeIndicatorInterval() {
    this.intervalTriggered = false
    window.clearTimeout(this._timeIndicatorTimeout)
  }

  positionTimeIndicator() {
    const { min, max, getNow } = this.props
    const current = getNow()

    if (current >= min && current <= max) {
      const { top } = this.slotMetrics.getRange(current, current)
      this.setState({ timeIndicatorPosition: top })
    } else {
      this.clearTimeIndicatorInterval()
    }
  }

  render() {
    const {
      max,
      rtl,
      isNow,
      resource,
      accessors,
      localizer,
      getters: { dayProp, ...getters },
      components: { eventContainerWrapper: EventContainer, ...components },
    } = this.props

    let { slotMetrics } = this
    let { selecting, top, height, startDate, endDate } = this.state

    let selectDates = { start: startDate, end: endDate }

    const { className, style } = dayProp(max)

    return (

        {slotMetrics.groups.map((grp, idx) => (
          <TimeSlotGroup
            key={idx}
            group={grp}
            resource={resource}
            getters={getters}
            components={components}
          />
        ))}
        <EventContainer
          localizer={localizer}
          resource={resource}
          accessors={accessors}
          getters={getters}
          components={components}
          slotMetrics={slotMetrics}
        >

            {this.renderEvents()}

        </EventContainer>

        {selecting && (

            {localizer.format(selectDates, 'selectRangeFormat')}

        )}
        {isNow && (
          <div
            className="rbc-current-time-indicator"
            style={{ top: `${this.state.timeIndicatorPosition}%` }}
          />
        )}

    )
  }

  renderEvents = () => {
    let {
      events,
      rtl: isRtl,
      selected,
      accessors,
      localizer,
      getters,
      components,
      step,
      timeslots,
    } = this.props

    const { slotMetrics } = this
    const { messages } = localizer

    let styledEvents = DayEventLayout.getStyledEvents({
      events,
      accessors,
      slotMetrics,
      minimumStartDifference: Math.ceil((step * timeslots) / 2),
    })

    return styledEvents.map(({ event, style }, idx) => {
      let end = accessors.end(event)
      let start = accessors.start(event)
      let format = 'eventTimeRangeFormat'
      let label

      const startsBeforeDay = slotMetrics.startsBeforeDay(start)
      const startsAfterDay = slotMetrics.startsAfterDay(end)

      if (startsBeforeDay) format = 'eventTimeRangeEndFormat'
      else if (startsAfterDay) format = 'eventTimeRangeStartFormat'

      if (startsBeforeDay && startsAfterDay) label = messages.allDay
      else label = localizer.format({ start, end }, format)

      let continuesEarlier = startsBeforeDay || slotMetrics.startsBefore(start)
      let continuesLater = startsAfterDay || slotMetrics.startsAfter(end)

      return (
        <TimeGridEvent
          style={style}
          event={event}
          label={label}
          key={'evt_' + idx}
          getters={getters}
          isRtl={isRtl}
          components={components}
          continuesEarlier={continuesEarlier}
          continuesLater={continuesLater}
          accessors={accessors}
          selected={isSelected(event, selected)}
          onClick={e => this._select(event, e)}
          onDoubleClick={e => this._doubleClick(event, e)}
        />
      )
    })
  }

  _selectable = () => {
    let node = findDOMNode(this)
    let selector = (this._selector = new Selection(() => findDOMNode(this), {
      longPressThreshold: this.props.longPressThreshold,
    }))

    let maybeSelect = box => {
      let onSelecting = this.props.onSelecting
      let current = this.state || {}
      let state = selectionState(box)
      let { startDate: start, endDate: end } = state

      if (onSelecting) {
        if (
          (dates.eq(current.startDate, start, 'minutes') &&
            dates.eq(current.endDate, end, 'minutes')) ||
          onSelecting({ start, end }) === false
        )
          return
      }

      if (
        this.state.start !== state.start ||
        this.state.end !== state.end ||
        this.state.selecting !== state.selecting
      ) {
        this.setState(state)
      }
    }

    let selectionState = point => {
      let currentSlot = this.slotMetrics.closestSlotFromPoint(
        point,
        getBoundsForNode(node)
      )

      if (!this.state.selecting) this._initialSlot = currentSlot

      let initialSlot = this._initialSlot
      if (initialSlot === currentSlot)
        currentSlot = this.slotMetrics.nextSlot(initialSlot)

      const selectRange = this.slotMetrics.getRange(
        dates.min(initialSlot, currentSlot),
        dates.max(initialSlot, currentSlot)
      )

      return {
        ...selectRange,
        selecting: true,

        top: `${selectRange.top}%`,
        height: `${selectRange.height}%`,
      }
    }

    let selectorClicksHandler = (box, actionType) => {
      if (!isEvent(findDOMNode(this), box)) {
        const { startDate, endDate } = selectionState(box)
        this._selectSlot({
          startDate,
          endDate,
          action: actionType,
          box,
        })
      }
      this.setState({ selecting: false })
    }

    selector.on('selecting', maybeSelect)
    selector.on('selectStart', maybeSelect)

    selector.on('beforeSelect', box => {
      if (this.props.selectable !== 'ignoreEvents') return

      return !isEvent(findDOMNode(this), box)
    })

    selector.on('click', box => selectorClicksHandler(box, 'click'))

    selector.on('doubleClick', box => selectorClicksHandler(box, 'doubleClick'))

    selector.on('select', bounds => {
      if (this.state.selecting) {
        this._selectSlot({ ...this.state, action: 'select', bounds })
        this.setState({ selecting: false })
      }
    })

    selector.on('reset', () => {
      if (this.state.selecting) {
        this.setState({ selecting: false })
      }
    })
  }

  _teardownSelectable = () => {
    if (!this._selector) return
    this._selector.teardown()
    this._selector = null
  }

  _selectSlot = ({ startDate, endDate, action, bounds, box }) => {
    let current = startDate,
      slots = []

    while (dates.lte(current, endDate)) {
      slots.push(current)
      current = dates.add(current, this.props.step, 'minutes')
    }

    notify(this.props.onSelectSlot, {
      slots,
      start: startDate,
      end: endDate,
      resourceId: this.props.resource,
      action,
      bounds,
      box,
    })
  }

  _select = (...args) => {
    notify(this.props.onSelectEvent, args)
  }

  _doubleClick = (...args) => {
    notify(this.props.onDoubleClickEvent, args)
  }
}

DayColumn.propTypes = {
  events: PropTypes.array.isRequired,
  step: PropTypes.number.isRequired,
  date: PropTypes.instanceOf(Date).isRequired,
  min: PropTypes.instanceOf(Date).isRequired,
  max: PropTypes.instanceOf(Date).isRequired,
  getNow: PropTypes.func.isRequired,
  isNow: PropTypes.bool,

  rtl: PropTypes.bool,

  accessors: PropTypes.object.isRequired,
  components: PropTypes.object.isRequired,
  getters: PropTypes.object.isRequired,
  localizer: PropTypes.object.isRequired,

  showMultiDayTimes: PropTypes.bool,
  culture: PropTypes.string,
  timeslots: PropTypes.number,

  selected: PropTypes.object,
  selectable: PropTypes.oneOf([true, false, 'ignoreEvents']),
  eventOffset: PropTypes.number,
  longPressThreshold: PropTypes.number,

  onSelecting: PropTypes.func,
  onSelectSlot: PropTypes.func.isRequired,
  onSelectEvent: PropTypes.func.isRequired,
  onDoubleClickEvent: PropTypes.func.isRequired,

  className: PropTypes.string,
  dragThroughEvents: PropTypes.bool,
  resource: PropTypes.any,
}

DayColumn.defaultProps = {
  dragThroughEvents: true,
  timeslots: 2,
}

export default DayColumn
<|endoftext|>


<commit_before>module.exports = (slackapp) =>
  function(err, req, res) {
    if (err) {
      res.status(500).send(`ERROR: ${err}`);
    } else {
      slackapp.log(`Use /incoming-webhooks/${req.identity.team_id} to receive new reviews.`);
      res.redirect(req.identity.url);
    }
  };
<commit_msg>Fix incoming webhook endpoint to include buid<commit_after>const config = require('../config.js');

module.exports = (slackapp) =>
  function(err, req, res) {
    if (err) {
      res.status(500).send(`ERROR: ${err}`);
    } else {
      slackapp.log(
        `Use /incoming-webhooks/${req.identity.team_id}?businessUnitId=${
          config.BUSINESS_UNIT_ID
        } to receive new reviews.`
      );
      res.redirect(req.identity.url);
    }
  };
<|endoftext|>