<commit_before>// OS Monitoring for Node.js

// Copyright (c) 2012 Laurent Fortin
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

var util     = require('util'),
    os       = require('os'),
    events   = require('events'),
    _        = require('underscore'),
    interval = undefined,
    critical = os.cpus().length,
    defaults = {
      delay     : 3000,
      critical1 : critical,
      critical5 : critical,
      critical15: critical,
      freemem   : 0
    },
    running  = false,
    config   = {};

// constructor
var Osm = function() {
  events.EventEmitter.call(this);
  return this;
};

// get EventEmitter class properties
util.inherits(Osm, events.EventEmitter);

Osm.prototype.version = '0.0.6';

Osm.prototype.start = function(options) {

  var self = this;

  self.stop()
      .config(options);

  interval  = setInterval(function() {
    var info = {
      loadavg  : os.loadavg(),
      uptime   : os.uptime(),
      freemem  : os.freemem(),
      totalmem : os.totalmem()
    },
    freemem  = (config.freemem < 1) ? config.freemem * info.totalmem : config.freemem;

    self.emit('monitor', _.extend({type: 'monitor'}, info));

    if(info.loadavg[0] > config.critical1) {
      self.emit('loadavg1', _.extend({type: 'loadavg1'}, info));
    }
    if(info.loadavg[1] > config.critical5) {
      self.emit('loadavg5', _.extend({type: 'loadavg5'}, info));
    }
    if(info.loadavg[2] > config.critical15) {
      self.emit('loadavg15', _.extend({type: 'loadavg15'}, info));
    }
    if(info.freemem < freemem) {
      self.emit('freemem', _.extend({type: 'freemem'}, info));
    }
  }, config.delay);

  if(!self.isRunning()) {
    running = true;
    self.emit('start', {type: 'start'});
  }

  return self;
};

Osm.prototype.stop = function() {

  clearInterval(interval);

  if(this.isRunning()) {
    running = false;
    this.emit('stop', {type: 'stop'});
  }

  return this;
};

Osm.prototype.config = function(options) {
  _.defaults(config, defaults);

  if(_.isObject(options)) {
    _.extend(config, options);
    this.emit('config', {type: 'config', options: _.clone(options)});
  }

  return config;
};

Osm.prototype.isRunning = function() {
  return !!running;
};

// deprecated stuff
Osm.prototype.setConfig = Osm.prototype.config;

// expose OS module
Osm.prototype.os = os;

module.exports = new Osm();

<commit_msg>Expose Underscore.js reference<commit_after>// OS Monitoring for Node.js

// Copyright (c) 2012 Laurent Fortin
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

var util     = require('util'),
    os       = require('os'),
    events   = require('events'),
    _        = require('underscore'),
    interval = undefined,
    critical = os.cpus().length,
    defaults = {
      delay     : 3000,
      critical1 : critical,
      critical5 : critical,
      critical15: critical,
      freemem   : 0
    },
    running  = false,
    config   = {};

// constructor
var Osm = function() {
  events.EventEmitter.call(this);
  return this;
};

// get EventEmitter class properties
util.inherits(Osm, events.EventEmitter);

Osm.prototype.version = '0.0.7';

Osm.prototype.start = function(options) {

  var self = this;

  self.stop()
      .config(options);

  interval  = setInterval(function() {
    var info = {
      loadavg  : os.loadavg(),
      uptime   : os.uptime(),
      freemem  : os.freemem(),
      totalmem : os.totalmem()
    },
    freemem  = (config.freemem < 1) ? config.freemem * info.totalmem : config.freemem;

    self.emit('monitor', _.extend({type: 'monitor'}, info));

    if(info.loadavg[0] > config.critical1) {
      self.emit('loadavg1', _.extend({type: 'loadavg1'}, info));
    }
    if(info.loadavg[1] > config.critical5) {
      self.emit('loadavg5', _.extend({type: 'loadavg5'}, info));
    }
    if(info.loadavg[2] > config.critical15) {
      self.emit('loadavg15', _.extend({type: 'loadavg15'}, info));
    }
    if(info.freemem < freemem) {
      self.emit('freemem', _.extend({type: 'freemem'}, info));
    }
  }, config.delay);

  if(!self.isRunning()) {
    running = true;
    self.emit('start', {type: 'start'});
  }

  return self;
};

Osm.prototype.stop = function() {

  clearInterval(interval);

  if(this.isRunning()) {
    running = false;
    this.emit('stop', {type: 'stop'});
  }

  return this;
};

Osm.prototype.config = function(options) {
  _.defaults(config, defaults);

  if(_.isObject(options)) {
    _.extend(config, options);
    this.emit('config', {type: 'config', options: _.clone(options)});
  }

  return config;
};

Osm.prototype.isRunning = function() {
  return !!running;
};

// deprecated stuff
Osm.prototype.setConfig = Osm.prototype.config;

// expose OS module
Osm.prototype.os = os;

// expose Underscore
Osm.prototype._ = _;

module.exports = new Osm();

<|endoftext|>


<commit_before>/*global define: true */
define(['jquery', 'pathtree'], function ($, PathTree) {
  'use strict';

  function chart(options) {
    var svg, partition, arc, me
      , tmpl = $('#template').html()
      ;

    options = $.extend({
      width: 960
    , height: 700
    , color: d3.scale.category20c()
    , isCount: false
    }, options);

    options.radius = Math.min(options.width, options.height) / 2;

    svg = d3.select("body").append("svg")
          .attr("width", options.width)
          .attr("height", options.height)
          .append("g")
          .attr("transform", "translate(" +
                             options.width / 2 + "," +
                             options.height * 0.52 + ")");

    partition = d3.layout.partition()
                  .sort(null)
                  .size([2 * Math.PI, options.radius * options.radius]);

    arc = d3.svg.arc()
            .startAngle(function (d) { return d.x; })
            .endAngle(function (d) { return d.x + d.dx; })
            .innerRadius(function (d) { return Math.sqrt(d.y); })
            .outerRadius(function (d) { return Math.sqrt(d.y + d.dy); });

    // Stash the old values for transition.
    function stash(d) {
      d.x0 = d.x;
      d.dx0 = d.dx;
    }

    // Interpolate the arcs in data space.
    function arcTween(a) {
      var i = d3.interpolate({x: a.x0, dx: a.dx0}, a);
      return function tweener(t) {
        var b = i(t);
        a.x0 = b.x;
        a.dx0 = b.dx;
        return arc(b);
      };
    }

    function showDetails(data) {
      var mappedData = $.extend({
        name: ''
      , line_number: ''
      , status: ''
      , duration: ''
      , time_or_count: options.isCount ? 'Examples' : 'Seconds'
      }, data)
      ;

      !options.isCount && (mappedData.value = mappedData.value.toFixed(3));

      $('.example-wrapper').html(Plates.bind(tmpl, mappedData));
    }

    function getValue() {
      return options.isCount ?
                  function () { return 1; } :
                  function (d) { return d.size; };
    }

    function render() {
      var path = svg.datum(me.tree.nodes).selectAll("path")
          .data(partition.value(getValue()).nodes);

      path
          .attr("d", arc)
          .each(stash);

      path.enter().append("path")
          .attr("display", function (d) {
            return (d.depth && d.depth > 1) ? null : "none";
          })
          .attr("d", arc)
          .style("stroke", function (d) { return '#fff'; })
          .style("fill", function (d) {
            if (d.status && d.status === 'failed') {
              return '#f00';
            } else {
              return options.color(((d.children ? d : d.parent) || {}).name);
            }
          })
          .style("fill-rule", "evenodd")
          .each(stash)
          .on('mouseover', showDetails);

      path.exit().remove();

      d3.selectAll("input").on("change", function change() {
        options.isCount = this.value === 'count';

        path
            .data(partition.value(getValue()).nodes)
          .transition()
            .duration(1500)
            .attrTween("d", arcTween);
      });
    }

    return me = {
      tree: new PathTree()

    , render: render

    , reset: function () {
        me.tree = new PathTree();
        me.render();
      }

    , push: function (data) {
        me.tree.add(data);
        me.render();
      }
    };
  }

  return chart;
});
<commit_msg>Hide innermost only<commit_after>/*global define: true */
define(['jquery', 'pathtree'], function ($, PathTree) {
  'use strict';

  function chart(options) {
    var svg, partition, arc, me
      , tmpl = $('#template').html()
      ;

    options = $.extend({
      width: 960
    , height: 700
    , color: d3.scale.category20c()
    , isCount: false
    }, options);

    options.radius = Math.min(options.width, options.height) / 2;

    svg = d3.select("body").append("svg")
          .attr("width", options.width)
          .attr("height", options.height)
          .append("g")
          .attr("transform", "translate(" +
                             options.width / 2 + "," +
                             options.height * 0.52 + ")");

    partition = d3.layout.partition()
                  .sort(null)
                  .size([2 * Math.PI, options.radius * options.radius]);

    arc = d3.svg.arc()
            .startAngle(function (d) { return d.x; })
            .endAngle(function (d) { return d.x + d.dx; })
            .innerRadius(function (d) { return Math.sqrt(d.y); })
            .outerRadius(function (d) { return Math.sqrt(d.y + d.dy); });

    // Stash the old values for transition.
    function stash(d) {
      d.x0 = d.x;
      d.dx0 = d.dx;
    }

    // Interpolate the arcs in data space.
    function arcTween(a) {
      var i = d3.interpolate({x: a.x0, dx: a.dx0}, a);
      return function tweener(t) {
        var b = i(t);
        a.x0 = b.x;
        a.dx0 = b.dx;
        return arc(b);
      };
    }

    function showDetails(data) {
      var mappedData = $.extend({
        name: ''
      , line_number: ''
      , status: ''
      , duration: ''
      , time_or_count: options.isCount ? 'Examples' : 'Seconds'
      }, data)
      ;

      !options.isCount && (mappedData.value = mappedData.value.toFixed(3));

      $('.example-wrapper').html(Plates.bind(tmpl, mappedData));
    }

    function getValue() {
      return options.isCount ?
                  function () { return 1; } :
                  function (d) { return d.size; };
    }

    function render() {
      var path = svg.datum(me.tree.nodes).selectAll("path")
          .data(partition.value(getValue()).nodes);

      path
          .attr("d", arc)
          .each(stash);

      path.enter().append("path")
          .attr("display", function (d) { return d.depth ? null : "none"; })
          .attr("d", arc)
          .style("stroke", function (d) { return '#fff'; })
          .style("fill", function (d) {
            if (d.status && d.status === 'failed') {
              return '#f00';
            } else {
              return options.color(((d.children ? d : d.parent) || {}).name);
            }
          })
          .style("fill-rule", "evenodd")
          .each(stash)
          .on('mouseover', showDetails);

      path.exit().remove();

      d3.selectAll("input").on("change", function change() {
        options.isCount = this.value === 'count';

        path
            .data(partition.value(getValue()).nodes)
          .transition()
            .duration(1500)
            .attrTween("d", arcTween);
      });
    }

    return me = {
      tree: new PathTree()

    , render: render

    , reset: function () {
        me.tree = new PathTree();
        me.render();
      }

    , push: function (data) {
        me.tree.add(data);
        me.render();
      }
    };
  }

  return chart;
});
<|endoftext|>


<commit_before>import { extend } from 'core/util';
import { on, off, createEl } from 'core/util/dom';
import Polygon from 'geometry/Polygon';
import Layer from 'layer/Layer';
import VectorLayer from 'layer/VectorLayer';
import Map from 'map/Map';
import Control from './Control';

/**
 * @property {Object} options - options
 * @property {Object} [options.position='bottom-right'] - position of the control
 * @property {Number} [options.level=4]  - the zoom level of the overview
 * @property {Object} [options.size={"width":300, "height":200}  - size of the Control
 * @property {Object} [options.symbol={}] - symbol of the overview rectangle
 * @memberOf control.Overview
 * @instance
 */
const options = {
    'level': 4,
    'position': {
        'right' : 1,
        'bottom' : 1
    },
    'size': [300, 200],
    'maximize' : true,
    'symbol': {
        'lineWidth': 3,
        'lineColor': '#1bbc9b',
        'polygonFill': '#1bbc9b',
        'polygonOpacity': 0.4
    }
};

/**
 * @classdesc
 * An overview control for the map.
 * @category control
 * @extends control.Control
 * @memberOf control
 * @example
 * var overview = new Overview({
 *     position : {'bottom': '0', 'right': '0'},
 *     size : {'width' : 300,'height' : 200}
 * }).addTo(map);
 */
class Overview extends Control {

    /**
     * method to build DOM of the control
     * @param  {Map} map map to build on
     * @return {HTMLDOMElement}
     */
    buildOn() {
        let size = this.options['size'];
        if (!this.options['maximize']) {
            size = [0, 0];
        }
        const container = createEl('div');

        const mapContainer = this.mapContainer = createEl('div');
        mapContainer.style.width = size[0] + 'px';
        mapContainer.style.height = size[1] + 'px';
        mapContainer.className = 'maptalks-overview';
        const button = this.button = createEl('div');
        button.className = 'maptalks-overview-button';
        container.appendChild(mapContainer);
        container.appendChild(button);
        return container;
    }

    onAdd() {
        if (this.options['maximize']) {
            this._createOverview();
        }
        this.getMap().on('resize moving moveend zoomend pitch rotate', this._update, this)
            .on('setbaselayer', this._updateBaseLayer, this);
        on(this.button, 'click', this._onButtonClick, this);
        this._updateButtonText();
    }

    onRemove() {
        this.getMap()
            .off('resize moving moveend zoomend pitch rotate', this._update, this)
            .off('setbaselayer', this._updateBaseLayer, this);
        if (this._overview) {
            this._overview.remove();
            delete this._overview;
            delete this._perspective;
        }
        off(this.button, 'click', this._onButtonClick, this);
    }

    maxmize() {
        const size = this.options['size'];
        const dom = this.mapContainer;
        dom.style.width = size[0] + 'px';
        dom.style.height = size[1] + 'px';
        this._createOverview();
    }

    minimize() {
        if (this._overview) {
            this._overview.remove();
        }
        delete this._overview;
        delete this._perspective;
        const dom = this.mapContainer;
        dom.style.width = 0 + 'px';
        dom.style.height = 0 + 'px';
    }

    _onButtonClick() {
        if (!this._overview) {
            this.maxmize();
        } else {
            this.minimize();
        }
        this._updateButtonText();
    }

    _updateButtonText() {
        if (this._overview) {
            this.button.innerHTML = '-';
        } else {
            this.button.innerHTML = '+';
        }
    }

    _createOverview() {
        const map = this.getMap(),
            dom = this.mapContainer,
            extent = map.getExtent();
        const options = map.config();
        extend(options, {
            'center': map.getCenter(),
            'zoom': this._getOverviewZoom(),
            'zoomAnimationDuration'  : 150,
            'scrollWheelZoom': false,
            'checkSize': false,
            'doubleClickZoom': false,
            'touchZoom': false,
            'control': false,
            'draggable' : false
        });
        this._overview = new Map(dom, options);
        this._updateBaseLayer();
        this._perspective = new Polygon(extent.toArray(), {
            'draggable': true,
            'cursor': 'move',
            'symbol': this.options['symbol']
        })
            .on('dragstart', this._onDragStart, this)
            .on('dragend', this._onDragEnd, this);
        new VectorLayer('v', [this._perspective]).addTo(this._overview);
        this.fire('load');
    }

    _getOverviewZoom() {
        const map = this.getMap(),
            zoom = map.getZoom(),
            minZoom = map.getMinZoom(),
            level = this.options['level'];
        if (level > 0) {
            for (let i = level; i > 0; i--) {
                if (zoom - i >= minZoom) {
                    return zoom - i;
                }
            }
        } else {
            for (let i = level; i < 0; i++) {
                if (zoom - i >= minZoom) {
                    return zoom - i;
                }
            }
        }

        return zoom;
    }

    _onDragStart() {
        this._origDraggable = this.getMap().options['draggable'];
        this.getMap().config('draggable', false);
    }

    _onDragEnd() {
        const center = this._perspective.getCenter();
        this._overview.setCenter(center);
        this.getMap().panTo(center);
        this.getMap().config('draggable', this._origDraggable);
    }

    _update() {
        if (!this._overview) {
            return;
        }
        this._perspective.setCoordinates(this.getMap().getExtent().toArray());
        this._overview.setCenterAndZoom(this.getMap().getCenter(), this._getOverviewZoom());
    }

    _updateBaseLayer() {
        if (!this._overview) {
            return;
        }
        const map = this.getMap();
        if (map.getBaseLayer()) {
            this._overview.setBaseLayer(Layer.fromJSON(map.getBaseLayer().toJSON()));
        } else {
            this._overview.setBaseLayer(null);
        }
    }

}

Overview.mergeOptions(options);

Map.mergeOptions({
    'overviewControl': false
});

Map.addOnLoadHook(function () {
    if (this.options['overviewControl']) {
        this.overviewControl = new Overview(this.options['overviewControl']);
        this.addControl(this.overviewControl);
    }
});

export default Overview;
<commit_msg>fix perspective's drawing with anti-meridian in overview control<commit_after>import { extend } from 'core/util';
import { on, off, createEl } from 'core/util/dom';
import Polygon from 'geometry/Polygon';
import Layer from 'layer/Layer';
import VectorLayer from 'layer/VectorLayer';
import Map from 'map/Map';
import Control from './Control';

/**
 * @property {Object} options - options
 * @property {Object} [options.position='bottom-right'] - position of the control
 * @property {Number} [options.level=4]  - the zoom level of the overview
 * @property {Object} [options.size={"width":300, "height":200}  - size of the Control
 * @property {Object} [options.symbol={}] - symbol of the overview rectangle
 * @memberOf control.Overview
 * @instance
 */
const options = {
    'level': 4,
    'position': {
        'right' : 1,
        'bottom' : 1
    },
    'size': [300, 200],
    'maximize' : true,
    'symbol': {
        'lineWidth': 3,
        'lineColor': '#1bbc9b',
        'polygonFill': '#1bbc9b',
        'polygonOpacity': 0.4
    }
};

/**
 * @classdesc
 * An overview control for the map.
 * @category control
 * @extends control.Control
 * @memberOf control
 * @example
 * var overview = new Overview({
 *     position : {'bottom': '0', 'right': '0'},
 *     size : {'width' : 300,'height' : 200}
 * }).addTo(map);
 */
class Overview extends Control {

    /**
     * method to build DOM of the control
     * @param  {Map} map map to build on
     * @return {HTMLDOMElement}
     */
    buildOn() {
        let size = this.options['size'];
        if (!this.options['maximize']) {
            size = [0, 0];
        }
        const container = createEl('div');

        const mapContainer = this.mapContainer = createEl('div');
        mapContainer.style.width = size[0] + 'px';
        mapContainer.style.height = size[1] + 'px';
        mapContainer.className = 'maptalks-overview';
        const button = this.button = createEl('div');
        button.className = 'maptalks-overview-button';
        container.appendChild(mapContainer);
        container.appendChild(button);
        return container;
    }

    onAdd() {
        if (this.options['maximize']) {
            this._createOverview();
        }
        this.getMap().on('resize moving moveend zoomend pitch rotate', this._update, this)
            .on('setbaselayer', this._updateBaseLayer, this);
        on(this.button, 'click', this._onButtonClick, this);
        this._updateButtonText();
    }

    onRemove() {
        this.getMap()
            .off('resize moving moveend zoomend pitch rotate', this._update, this)
            .off('setbaselayer', this._updateBaseLayer, this);
        if (this._overview) {
            this._overview.remove();
            delete this._overview;
            delete this._perspective;
        }
        off(this.button, 'click', this._onButtonClick, this);
    }

    maxmize() {
        const size = this.options['size'];
        const dom = this.mapContainer;
        dom.style.width = size[0] + 'px';
        dom.style.height = size[1] + 'px';
        this._createOverview();
    }

    minimize() {
        if (this._overview) {
            this._overview.remove();
        }
        delete this._overview;
        delete this._perspective;
        const dom = this.mapContainer;
        dom.style.width = 0 + 'px';
        dom.style.height = 0 + 'px';
    }

    _onButtonClick() {
        if (!this._overview) {
            this.maxmize();
        } else {
            this.minimize();
        }
        this._updateButtonText();
    }

    _updateButtonText() {
        if (this._overview) {
            this.button.innerHTML = '-';
        } else {
            this.button.innerHTML = '+';
        }
    }

    _createOverview() {
        const map = this.getMap(),
            dom = this.mapContainer,
            extent = map.getExtent();
        const options = map.config();
        extend(options, {
            'center': map.getCenter(),
            'zoom': this._getOverviewZoom(),
            'zoomAnimationDuration'  : 150,
            'scrollWheelZoom': false,
            'checkSize': false,
            'doubleClickZoom': false,
            'touchZoom': false,
            'control': false,
            'draggable' : false
        });
        this._overview = new Map(dom, options);
        this._updateBaseLayer();
        this._perspective = new Polygon(extent.toArray(), {
            'draggable': true,
            'cursor': 'move',
            'symbol': this.options['symbol'],
            'antiMeridian' : false
        })
            .on('dragstart', this._onDragStart, this)
            .on('dragend', this._onDragEnd, this);
        new VectorLayer('v', [this._perspective]).addTo(this._overview);
        this.fire('load');
    }

    _getOverviewZoom() {
        const map = this.getMap(),
            zoom = map.getZoom(),
            minZoom = map.getMinZoom(),
            level = this.options['level'];
        if (level > 0) {
            for (let i = level; i > 0; i--) {
                if (zoom - i >= minZoom) {
                    return zoom - i;
                }
            }
        } else {
            for (let i = level; i < 0; i++) {
                if (zoom - i >= minZoom) {
                    return zoom - i;
                }
            }
        }

        return zoom;
    }

    _onDragStart() {
        this._origDraggable = this.getMap().options['draggable'];
        this.getMap().config('draggable', false);
    }

    _onDragEnd() {
        const center = this._perspective.getCenter();
        this._overview.setCenter(center);
        this.getMap().panTo(center);
        this.getMap().config('draggable', this._origDraggable);
    }

    _update() {
        if (!this._overview) {
            return;
        }
        this._perspective.setCoordinates(this.getMap().getExtent().toArray());
        this._overview.setCenterAndZoom(this.getMap().getCenter(), this._getOverviewZoom());
    }

    _updateBaseLayer() {
        if (!this._overview) {
            return;
        }
        const map = this.getMap();
        if (map.getBaseLayer()) {
            this._overview.setBaseLayer(Layer.fromJSON(map.getBaseLayer().toJSON()));
        } else {
            this._overview.setBaseLayer(null);
        }
    }

}

Overview.mergeOptions(options);

Map.mergeOptions({
    'overviewControl': false
});

Map.addOnLoadHook(function () {
    if (this.options['overviewControl']) {
        this.overviewControl = new Overview(this.options['overviewControl']);
        this.addControl(this.overviewControl);
    }
});

export default Overview;
<|endoftext|>


<commit_before>var events    = require('events'),
    util      = require('util'),
    redis     = require('redis'),
    redisScan = require('./redis-scan');

var SessionManager = exports.SessionManager = function(addr, callback) {

  if (addr) {
    this.redisClient = redis.createClient(addr.split(':')[1], addr.split(':')[0]);
  } else {
    this.redisClient = redis.createClient();
    addr = 'localhost:6379';
  }

  events.EventEmitter.call(this);

  this.redisClient.on("error", function(err) {
    console.log("Redis error encountered", err);
  });

  this.redisClient.on("end", function() {
    console.log("Redis connection closed");
    if (callback) callback('ERR-REDIS', 'redis - failed to connect to ['+addr+']');
  });

  this.redisClient.once("connect", function() {
    if (callback) callback(null);
  });
};

util.inherits(SessionManager, events.EventEmitter);

/**
 * Get the server number according to channel name from redis hash table.

 * @name retrieve
 * @function
 * @param {string} app - application key
 * @param {string} channel - channel name
 * @param {callback} callback - callback function
 */
SessionManager.prototype.retrieve = function(app, channel, callback) {
  this.redisClient.hgetall(app+":"+channel, function (err, res) {
    callback(res);
  });
};

/**
 * Remove server datas from redis hash table

 * @name remove
 * @function
 * @param {string} app - application key
 * @param {string} channel - channel name
 */
SessionManager.prototype.remove = function(app, channel) {
  this.redisClient.hdel(app, channel);
};

/**
 * Update connection informations into redis server.
 * If the number of connections in this channel is ZERO, delete data from redis hash table.
 *
 * @name update
 * @function
 * @param {string} app - application key
 * @param {string} channel - channel name
 * @param {string} server - server number (auth-generated into zookeeper)
 * @param {number} count - the number of connections
 *
 */
SessionManager.prototype.update = function(app, channel, server, count, callback) {

  if(callback){
    if (count > 0) {
      this.redisClient.hset(app+":"+channel, server, count, callback);
    } else {
      this.redisClient.hdel(app+":"+channel, server, callback);
    }
  }else{
    if (count > 0) {
      this.redisClient.hset(app+":"+channel, server, count);
    } else {
      this.redisClient.hdel(app+":"+channel, server);
    }
  }
};

/**
 * Publish data to another server.
 * @name publish
 * @function
 * @param {string} server - server number
 * @param {object} dataObj -  Data to send
 */
SessionManager.prototype.publish = function(server, dataObj) {

  console.log('#### REDIS Publish : ' + 'C-' + server);
  console.log('####       app(A)  : ' + dataObj.A);
  console.log('####   channel(C) : ' + dataObj.C);
  console.log('####  socketId(SS) : ' + dataObj.SS);
  console.log('####      name(NM) : ' + dataObj.NM);

  this.redisClient.publish('C-' + server, JSON.stringify(dataObj));

};

SessionManager.prototype.updateClient = function(app, channel, key, value) {
  if(!value) value = "";
  this.redisClient.hset(app+":DATA:"+channel, key, value);
};

SessionManager.prototype.deleteClient = function(app, channel, key) {
  this.redisClient.hdel(app+":DATA:"+channel, key);
};

SessionManager.prototype.retrieveClients = function(app, channel, callback) {
  this.redisClient.hgetall(app+":DATA:"+channel, function (err, res) {
    callback(err, res);
  });
};

/**
* Retrieve channel list with hscan @ TODO 확인해봐야 함.
*
* @name retrieveChannelList
* @function
* @param {string} key - application key
* @param {string} pattern - channel name
* @param {callback} callback - callback function
*/
SessionManager.prototype.retrieveChannelList = function(key, pattern, callback) {
  var reVa = [];
  redisScan({
    redis: this.redisClient,
    cmd : 'HSCAN',
    key : key,
    pattern : pattern,
    each_callback: function (type, key, subkey, cursor, value, cb) {
      //console.log(key,subkey,value);
      if(subkey){
        reVa.push({key: subkey, value: value });
      }
      cb();
    },
    done_callback: function (err) {
      callback(err,reVa);
    }
  });
};
<commit_msg>add validation to store user datas<commit_after>var events    = require('events'),
    util      = require('util'),
    redis     = require('redis'),
    redisScan = require('./redis-scan');

var SessionManager = exports.SessionManager = function(addr, callback) {

  if (addr) {
    this.redisClient = redis.createClient(addr.split(':')[1], addr.split(':')[0]);
  } else {
    this.redisClient = redis.createClient();
    addr = 'localhost:6379';
  }

  events.EventEmitter.call(this);

  this.redisClient.on("error", function(err) {
    console.log("Redis error encountered", err);
  });

  this.redisClient.on("end", function() {
    console.log("Redis connection closed");
    if (callback) callback('ERR-REDIS', 'redis - failed to connect to ['+addr+']');
  });

  this.redisClient.once("connect", function() {
    if (callback) callback(null);
  });
};

util.inherits(SessionManager, events.EventEmitter);

/**
 * Get the server number according to channel name from redis hash table.

 * @name retrieve
 * @function
 * @param {string} app - application key
 * @param {string} channel - channel name
 * @param {callback} callback - callback function
 */
SessionManager.prototype.retrieve = function(app, channel, callback) {
  this.redisClient.hgetall(app+":"+channel, function (err, res) {
    callback(res);
  });
};

/**
 * Remove server datas from redis hash table

 * @name remove
 * @function
 * @param {string} app - application key
 * @param {string} channel - channel name
 */
SessionManager.prototype.remove = function(app, channel) {
  this.redisClient.hdel(app, channel);
};

/**
 * Update connection informations into redis server.
 * If the number of connections in this channel is ZERO, delete data from redis hash table.
 *
 * @name update
 * @function
 * @param {string} app - application key
 * @param {string} channel - channel name
 * @param {string} server - server number (auth-generated into zookeeper)
 * @param {number} count - the number of connections
 *
 */
SessionManager.prototype.update = function(app, channel, server, count, callback) {

  if(callback){
    if (count > 0) {
      this.redisClient.hset(app+":"+channel, server, count, callback);
    } else {
      this.redisClient.hdel(app+":"+channel, server, callback);
    }
  }else{
    if (count > 0) {
      this.redisClient.hset(app+":"+channel, server, count);
    } else {
      this.redisClient.hdel(app+":"+channel, server);
    }
  }
};

/**
 * Publish data to another server.
 * @name publish
 * @function
 * @param {string} server - server number
 * @param {object} dataObj -  Data to send
 */
SessionManager.prototype.publish = function(server, dataObj) {

  console.log('#### REDIS Publish : ' + 'C-' + server);
  console.log('####       app(A)  : ' + dataObj.A);
  console.log('####   channel(C) : ' + dataObj.C);
  console.log('####  socketId(SS) : ' + dataObj.SS);
  console.log('####      name(NM) : ' + dataObj.NM);

  this.redisClient.publish('C-' + server, JSON.stringify(dataObj));

};

SessionManager.prototype.updateClient = function(app, channel, key, value) {
  if(key){
    if(!value) value = "";
    this.redisClient.hset(app+":DATA:"+channel, key, value);
  }
};

SessionManager.prototype.deleteClient = function(app, channel, key) {
  if(key){
    this.redisClient.hdel(app+":DATA:"+channel, key);
  }
};

SessionManager.prototype.retrieveClients = function(app, channel, callback) {
  this.redisClient.hgetall(app+":DATA:"+channel, function (err, res) {
    callback(err, res);
  });
};

/**
* Retrieve channel list with hscan @ TODO 확인해봐야 함.
*
* @name retrieveChannelList
* @function
* @param {string} key - application key
* @param {string} pattern - channel name
* @param {callback} callback - callback function
*/
SessionManager.prototype.retrieveChannelList = function(key, pattern, callback) {
  var reVa = [];
  redisScan({
    redis: this.redisClient,
    cmd : 'HSCAN',
    key : key,
    pattern : pattern,
    each_callback: function (type, key, subkey, cursor, value, cb) {
      //console.log(key,subkey,value);
      if(subkey){
        reVa.push({key: subkey, value: value });
      }
      cb();
    },
    done_callback: function (err) {
      callback(err,reVa);
    }
  });
};
<|endoftext|>


<commit_before>'use strict';

var RequestPromise = require("request-promise");
var Promise = require("bluebird");
var _ = require('lodash');

var regionModel = require('./../models/universe/regionModel');
var constellationModel = require('./../models/universe/constellationModel');
var systemModel = require('./../models/universe/systemModel');

var eveRegionCrestEndpoint = 'https://crest-tq.eveonline.com/regions/';
var eveConstellationCrestEndpoint = 'https://crest-tq.eveonline.com/constellations/';

exports.updateUniverseData = getAllRegions;

function getAllRegions(req, res) {
    getAllRegionsHrefs().then(function (hrefs) {
        return Promise.mapSeries(hrefs, function (href) {
            getRegion(href).then(function (regions) {
                return Promise.mapSeries(regions.constellations, function (constellation) {
                    getConstellationInfo(constellation).then(function (constellationInfo) {
                        return Promise.map(constellationInfo, getSystem).delay(15000);
                    });
                }).delay(15000);
            });
        }).delay(15000);
    });
}

function getSystem(systems) {
    console.log('Systems', systems);
    //for(var updateSystem in systems){
    var options = {
        uri: systems.href,
        json: true
    };
    return RequestPromise(options).then(function (responseItem) {
        //Grab the system in the db and update it with its info
        var securityType;
        if (responseItem.securityStatus <= (-0.990000009536743)) {
            //J-Space
            securityType = 2
        } else {
            //K-Space
            securityType = 1;
        }
        systemModel.findOne({_id: systems._id}, function (err, doc) {
            doc.name = responseItem.name;
            doc.securityStatus = responseItem.securityStatus;
            doc.systemType = securityType;
            doc.save();
        });

    })
}

function getConstellationInfo(constellation) {
    var options = {
        uri: constellation.href,
        json: true
    };
    return RequestPromise(options).then(function (responseItem) {
        var arrayOfSystems = [];
        for (var system in responseItem.systems) {
            if (responseItem.systems.hasOwnProperty(system)) {
                var newSystem = new systemModel({
                    _id: responseItem.systems[system].id,
                    href: responseItem.systems[system].href
                });
                newSystem.save();
                arrayOfSystems.push(newSystem);
            }
        }
        //find the constellation and update it with its info
        constellationModel.findOne({_id: constellation._id}, function (err, doc) {
            doc.name = responseItem.name;
            doc.solarSystems = arrayOfSystems;
            doc.save();
        });
        return arrayOfSystems;
    }).delay(15000);
}

function getRegion(href) {
    var options = {
        uri: href,
        json: true
    };
    return RequestPromise(options).then(function (responseItem) {
        var constellationObjects = [];
        for (var item in responseItem.constellations) {
            var newConstellation = constellationModel({
                _id: responseItem.constellations[item].id,
                href: eveConstellationCrestEndpoint + responseItem.constellations[item].id + '/'
            });
            newConstellation.save();
            constellationObjects.push(newConstellation);
        }
        var newRegion = regionModel({
            _id: responseItem.id,
            name: responseItem.name,
            description: responseItem.description,
            href: eveRegionCrestEndpoint + responseItem.id + '/',
            constellations: constellationObjects
        });
        newRegion.save();
        return newRegion;
    });
}

function getAllRegionsHrefs() {
    var options = {
        uri: eveRegionCrestEndpoint,
        json: true
    };
    return RequestPromise(options).then(function (responseItems) {
        var regionHrefs = [];
        for (var item in responseItems.items) {
            if (responseItems.items.hasOwnProperty(item)) {
                regionHrefs.push(responseItems.items[item].href);
            }
        }
        return regionHrefs;
    });
}<commit_msg>FINALLY GET IT TO WAIT! FUCK YEAH! WOOHOOO THIS IS FANTASTIC! IM SO HAPPY! YAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAH<commit_after>var RequestPromise = require("request-promise");
var Promise = require("bluebird");

var regionModel = require('./../models/universe/regionModel');
var constellationModel = require('./../models/universe/constellationModel');
var systemModel = require('./../models/universe/systemModel');

var eveRegionCrestEndpoint = 'https://crest-tq.eveonline.com/regions/';
var eveConstellationCrestEndpoint = 'https://crest-tq.eveonline.com/constellations/';

exports.updateUniverseData = getAllRegions;

function getAllRegions(req, res) {
    getAllRegionsHrefs().then(function (hrefs) {
        return Promise.mapSeries(hrefs, function (href) {
            return getRegion(href).then(function (regions) {
                return Promise.mapSeries(regions.constellations, function (constellation) {
                    return getConstellationInfo(constellation).then(function (constellationInfo) {
                        return Promise.map(constellationInfo, getSystem).delay(20);
                    });
                });
            });
        });
    });
}

function getSystem(system) {
    console.log('System Again', system);
    var options = {
        uri: system.href,
        json: true
    };
    return RequestPromise(options).then(function (responseItem) {
        //Grab the system in the db and update it with its info
        var securityType;
        if (responseItem.securityStatus <= (-0.990000009536743)) {
            //J-Space
            securityType = 2
        } else {
            //K-Space
            securityType = 1;
        }
        systemModel.findOne({_id: system._id}, function (err, doc) {
            doc.name = responseItem.name;
            doc.securityStatus = responseItem.securityStatus;
            doc.systemType = securityType;
            doc.save();
        });
    })
}

function getConstellationInfo(constellation) {
    var options = {
        uri: constellation.href,
        json: true
    };
    return RequestPromise(options).then(function (responseItem) {
        var arrayOfSystems = [];
        for (var system in responseItem.systems) {
            if (responseItem.systems.hasOwnProperty(system)) {
                var newSystem = new systemModel({
                    _id: responseItem.systems[system].id,
                    href: responseItem.systems[system].href
                });
                newSystem.save();
                arrayOfSystems.push(newSystem);
            }
        }
        //find the constellation and update it with its info
        constellationModel.findOne({_id: constellation._id}, function (err, doc) {
            doc.name = responseItem.name;
            doc.solarSystems = arrayOfSystems;
            doc.save();
        });
        return arrayOfSystems;
    });
}

function getRegion(href) {
    var options = {
        uri: href,
        json: true
    };
    return RequestPromise(options).then(function (responseItem) {
        var constellationObjects = [];
        for (var item in responseItem.constellations) {
            var newConstellation = constellationModel({
                _id: responseItem.constellations[item].id,
                href: eveConstellationCrestEndpoint + responseItem.constellations[item].id + '/'
            });
            newConstellation.save();
            constellationObjects.push(newConstellation);
        }
        var newRegion = regionModel({
            _id: responseItem.id,
            name: responseItem.name,
            description: responseItem.description,
            href: eveRegionCrestEndpoint + responseItem.id + '/',
            constellations: constellationObjects
        });
        newRegion.save();
        return newRegion;
    });
}

function getAllRegionsHrefs() {
    var options = {
        uri: eveRegionCrestEndpoint,
        json: true
    };
    return RequestPromise(options).then(function (responseItems) {
        var regionHrefs = [];
        for (var item in responseItems.items) {
            if (responseItems.items.hasOwnProperty(item)) {
                regionHrefs.push(responseItems.items[item].href);
            }
        }
        return regionHrefs;
    });
}<|endoftext|>


<commit_before>'use strict';
var stripe = require('stripe');
var Promise = require('promise');
var validateVAT = require('validate-vat');
var models = require('../../models');

module.exports = function (stripe) {

  return function (req, event, done) {

    done(null)

  };

};
<commit_msg>Add helpers for VAT calculations<commit_after>'use strict';
var stripe = require('stripe');
var Promise = require('promise');
var validateVAT = require('validate-vat');
var models = require('../../models');

function getVATByCountry(countrycode) {
  return Promise.resolve(0.2);
};

function countryIsInEU(countrycode) {
    var EU = ['AT', 'BE', 'BG', 'CY', 'CZ', 'DE', 'DK', 'EE', 'EL', 'ES', 'FI', 'FR', 'GB', 'HR', 'HU', 'IE', 'IT', 'LT', 'LU', 'LV', 'MT', 'NL', 'PL', 'PT', 'RO', 'SE', 'SI', 'SK'];
    return EU.indexOf(countrycode.toUpperCase()) !== -1;
}

function getCountry(customer) {
  var card = customer.default_card; // jshint ignore:line

  var country = customer.cards.data.reduce(function (last, current) {
    if (current.id === card) {
      return current.country;
    } else {
      return last;
    }
  }, null);

  if (country === null) {
    if (customer.cards.data.length === 1) {
      return customer.cards.data[0].country;
    } else {
      // TODO multipile cards and no default ??
      return customer.cards.data[0].country;
    }
  } else {
    return country;
  }

}

module.exports = function (stripe) {

  return function (req, event, done) {

    done(null)

  };

};
<|endoftext|>


<commit_before>// 工程配置
BI.prepares.push(function () {
    // 注册布局
    // adapt类布局优先级规则
    // 1、在非IE且支持flex的浏览器下使用flex布局
    // 2、IE或者不支持flex的浏览器下使用inline布局
    // 3、在2的情况下如果布局的items大于1的话使用display:table的布局
    // 4、在3的情况下如果IE版本低于8使用table标签布局
    var _isSupportFlex;
    var isSupportFlex = function () {
        if (_isSupportFlex == null) {
            _isSupportFlex = !!(BI.isSupportCss3 && BI.isSupportCss3("flex"));
        }
        return _isSupportFlex;
    };
    BI.Plugin.configWidget("bi.horizontal", function (ob) {
        var isIE = BI.isIE(), supportFlex = isSupportFlex(), isLessIE8 = isIE && BI.getIEVersion() < 8;
        if (isLessIE8) {
            return ob;
        }
        if (ob.items && ob.items.length > 1) {
            return BI.extend(ob, {type: "bi.table_adapt"});
        }
        if (!IE && supportFlex) {
            return BI.extend(ob, {type: "bi.flex_horizontal"});
        }
        return BI.extend(ob, {type: "bi.table_adapt"});
    });
    BI.Plugin.configWidget("bi.center_adapt", function (ob) {
        var isIE = BI.isIE(), supportFlex = isSupportFlex(), justOneItem = (ob.items && ob.items.length <= 1);
        if (!isIE && supportFlex && justOneItem) {
            return BI.extend(ob, {type: "bi.flex_center_adapt"});
        }
        // 一个item的情况下inline布局睥睨天下
        if (justOneItem) {
            return BI.extend(ob, {type: "bi.inline_center_adapt"});
        }
        return ob;
    });
    BI.Plugin.configWidget("bi.vertical_adapt", function (ob) {
        var isIE = BI.isIE(), supportFlex = isSupportFlex();
        if (!isIE && supportFlex) {
            return BI.extend(ob, {type: "bi.flex_vertical_center_adapt"});
        }
        return BI.extend(ob, {type: "bi.inline_vertical_adapt"});
    });
    BI.Plugin.configWidget("bi.horizontal_adapt", function (ob) {
        if (ob.verticalAlign === BI.VerticalAlign.TOP && ob.items && ob.items.length <= 1) {
            return BI.extend(ob, {type: "bi.horizontal_auto"});
        }
        return ob;
    });
    BI.Plugin.configWidget("bi.float_center_adapt", function (ob) {
        if (!BI.isIE() && isSupportFlex()) {
            return BI.extend(ob, {type: "bi.flex_center_adapt"});
        }
        return BI.extend(ob, {type: "bi.inline_center_adapt"});
    });

    BI.Plugin.configWidget("bi.flex_horizontal", function (ob) {
        if (ob.scrollable === true || ob.scrollx === true || ob.scrolly === true) {
            return BI.extend({}, ob, {type: "bi.flex_scrollable_horizontal"});
        }
    });
    BI.Plugin.configWidget("bi.flex_vertical", function (ob) {
        if (ob.scrollable === true || ob.scrollx === true || ob.scrolly === true) {
            return BI.extend({}, ob, {type: "bi.flex_scrollable_vertical"});
        }
    });
    BI.Plugin.configWidget("bi.flex_horizontal_adapt", function (ob) {
        if (ob.scrollable === true || ob.scrollx === true || ob.scrolly === true) {
            return BI.extend({}, ob, {type: "bi.flex_scrollable_horizontal_adapt"});
        }
    });
    BI.Plugin.configWidget("bi.flex_vertical_adapt", function (ob) {
        if (ob.scrollable === true || ob.scrollx === true || ob.scrolly === true) {
            return BI.extend({}, ob, {type: "bi.flex_scrollable_vertical_adapt"});
        }
    });
    BI.Plugin.configWidget("bi.flex_horizontal_center_adapt", function (ob) {
        if (ob.scrollable === true || ob.scrollx === true || ob.scrolly === true) {
            return BI.extend({}, ob, {type: "bi.flex_scrollable_horizontal_adapt"});
        }
    });
    BI.Plugin.configWidget("bi.flex_vertical_center_adapt", function (ob) {
        if (ob.scrollable === true || ob.scrollx === true || ob.scrolly === true) {
            return BI.extend({}, ob, {type: "bi.flex_scrollable_vertical_adapt"});
        }
    });
    BI.Plugin.configWidget("bi.flex_center_adapt", function (ob) {
        if (ob.scrollable === true || ob.scrolly === true || ob.scrollx === true) {
            return BI.extend({}, ob, {type: "bi.flex_scrollable_center_adapt"});
        }
    });

    BI.Plugin.configWidget("bi.radio", function (ob) {
        if (BI.isIE() && BI.getIEVersion() < 9) {
            return BI.extend(ob, {type: "bi.image_radio"});
        }
        return ob;
    });

    BI.Plugin.configWidget("bi.checkbox", function (ob) {
        if (BI.isIE() && BI.getIEVersion() < 9) {
            return BI.extend(ob, {type: "bi.image_checkbox"});
        }
        return ob;
    });

    BI.Plugin.configWidget("bi.half_icon_button", function (ob) {
        if (BI.isIE() && BI.getIEVersion() < 9) {
            return ob;
        }
        return BI.extend(ob, {type: "bi.half_button"});
    });
});
<commit_msg>Pull request #1467: 无JIRA任务 bugfix<commit_after>// 工程配置
BI.prepares.push(function () {
    // 注册布局
    // adapt类布局优先级规则
    // 1、在非IE且支持flex的浏览器下使用flex布局
    // 2、IE或者不支持flex的浏览器下使用inline布局
    // 3、在2的情况下如果布局的items大于1的话使用display:table的布局
    // 4、在3的情况下如果IE版本低于8使用table标签布局
    var _isSupportFlex;
    var isSupportFlex = function () {
        if (_isSupportFlex == null) {
            _isSupportFlex = !!(BI.isSupportCss3 && BI.isSupportCss3("flex"));
        }
        return _isSupportFlex;
    };
    BI.Plugin.configWidget("bi.horizontal", function (ob) {
        var isIE = BI.isIE(), supportFlex = isSupportFlex(), isLessIE8 = isIE && BI.getIEVersion() < 8;
        if (isLessIE8) {
            return ob;
        }
        if (ob.items && ob.items.length > 1) {
            return BI.extend(ob, {type: "bi.table_adapt"});
        }
        if (!IE && supportFlex) {
            return BI.extend(ob, {type: "bi.flex_horizontal"});
        }
        return BI.extend(ob, {type: "bi.table_adapt"});
    });
    BI.Plugin.configWidget("bi.center_adapt", function (ob) {
        var isIE = BI.isIE(), supportFlex = isSupportFlex(), justOneItem = (ob.items && ob.items.length <= 1);
        if (!isIE && supportFlex && justOneItem) {
            return BI.extend(ob, {type: "bi.flex_center_adapt"});
        }
        // 一个item的情况下inline布局睥睨天下
        if (justOneItem) {
            return BI.extend(ob, {type: "bi.inline_center_adapt"});
        }
        return ob;
    });
    BI.Plugin.configWidget("bi.vertical_adapt", function (ob) {
        var isIE = BI.isIE(), supportFlex = isSupportFlex();
        if (!isIE && supportFlex) {
            return BI.extend(ob, {type: "bi.flex_vertical_center_adapt"});
        }
        return BI.extend(ob, {type: "bi.inline_vertical_adapt"});
    });
    BI.Plugin.configWidget("bi.horizontal_adapt", function (ob) {
        if (ob.verticalAlign === BI.VerticalAlign.TOP && ob.items && ob.items.length <= 1) {
            return BI.extend(ob, {type: "bi.horizontal_auto"});
        }
        return ob;
    });
    BI.Plugin.configWidget("bi.float_center_adapt", function (ob) {
        if (!BI.isIE() && isSupportFlex()) {
            return BI.extend(ob, {type: "bi.flex_center_adapt"});
        }
        return BI.extend(ob, {type: "bi.inline_center_adapt"});
    });

    BI.Plugin.configWidget("bi.flex_horizontal", function (ob) {
        if (ob.scrollable === true || ob.scrollx === true || ob.scrolly === true) {
            return BI.extend(ob, {type: "bi.flex_scrollable_horizontal"});
        }
    });
    BI.Plugin.configWidget("bi.flex_vertical", function (ob) {
        if (ob.scrollable === true || ob.scrollx === true || ob.scrolly === true) {
            return BI.extend(ob, {type: "bi.flex_scrollable_vertical"});
        }
    });
    BI.Plugin.configWidget("bi.flex_horizontal_adapt", function (ob) {
        if (ob.scrollable === true || ob.scrollx === true || ob.scrolly === true) {
            return BI.extend(ob, {type: "bi.flex_scrollable_horizontal_adapt"});
        }
    });
    BI.Plugin.configWidget("bi.flex_vertical_adapt", function (ob) {
        if (ob.scrollable === true || ob.scrollx === true || ob.scrolly === true) {
            return BI.extend(ob, {type: "bi.flex_scrollable_vertical_adapt"});
        }
    });
    BI.Plugin.configWidget("bi.flex_horizontal_center_adapt", function (ob) {
        if (ob.scrollable === true || ob.scrollx === true || ob.scrolly === true) {
            return BI.extend(ob, {type: "bi.flex_scrollable_horizontal_adapt"});
        }
    });
    BI.Plugin.configWidget("bi.flex_vertical_center_adapt", function (ob) {
        if (ob.scrollable === true || ob.scrollx === true || ob.scrolly === true) {
            return BI.extend(ob, {type: "bi.flex_scrollable_vertical_adapt"});
        }
    });
    BI.Plugin.configWidget("bi.flex_center_adapt", function (ob) {
        if (ob.scrollable === true || ob.scrolly === true || ob.scrollx === true) {
            return BI.extend(ob, {type: "bi.flex_scrollable_center_adapt"});
        }
    });

    BI.Plugin.configWidget("bi.radio", function (ob) {
        if (BI.isIE() && BI.getIEVersion() < 9) {
            return BI.extend(ob, {type: "bi.image_radio"});
        }
        return ob;
    });

    BI.Plugin.configWidget("bi.checkbox", function (ob) {
        if (BI.isIE() && BI.getIEVersion() < 9) {
            return BI.extend(ob, {type: "bi.image_checkbox"});
        }
        return ob;
    });

    BI.Plugin.configWidget("bi.half_icon_button", function (ob) {
        if (BI.isIE() && BI.getIEVersion() < 9) {
            return ob;
        }
        return BI.extend(ob, {type: "bi.half_button"});
    });
});
<|endoftext|>


<commit_before>// 工程配置
BI.prepares.push(function () {
    // 注册布局
    // adapt类布局优先级规则
    // 1、在非IE且支持flex的浏览器下使用flex布局
    // 2、IE或者不支持flex的浏览器下使用inline布局
    // 3、在2的情况下如果布局的items大于1的话使用display:table的布局
    // 4、在3的情况下如果IE版本低于8使用table标签布局
    var _isSupportFlex;
    var isSupportFlex = function () {
        if (_isSupportFlex == null) {
            _isSupportFlex = !!(BI.isSupportCss3 && BI.isSupportCss3("flex"));
        }
        return _isSupportFlex;
    };
    BI.Plugin.configWidget("bi.horizontal", function (ob) {
        var supportFlex = isSupportFlex();
        // // 在横向自适应场景下我们需要使用table的自适应撑出滚动条的特性（flex处理不了这种情况）
        // // 主要出现在center_adapt或者horizontal_adapt的场景，或者主动设置horizontalAlign的场景
        // if (ob.horizontalAlign === BI.HorizontalAlign.Center || ob.horizontalAlign === BI.HorizontalAlign.Stretch) {
        //     return BI.extend({}, ob, {type: "bi.table_adapt"});
        // }
        if (supportFlex) {
            return BI.extend({}, ob, {type: "bi.flex_horizontal"});
        }
        return BI.extend({
            scrollx: true
        }, ob, {type: "bi.inline"});
    });
    BI.Plugin.configWidget("bi.inline", function (ob) {
        // 当列宽既需要自动列宽又需要自适应列宽时，inline布局也处理不了了，降级table处理吧
        var hasAutoAndFillColumnSize = false;
        if (ob.columnSize && ob.columnSize.length > 0) {
            if (ob.columnSize.indexOf("") >= 0 && ob.columnSize.indexOf("fill") >= 0) {
                hasAutoAndFillColumnSize = true;
            }
        } else {
            var hasAuto = false, hasFill = false;
            BI.each(ob.items, function (i, item) {
                if (item.width === "fill") {
                    hasFill = true;
                } else if (BI.isNull(item.width) || item.width === "") {
                    hasAuto = true;
                }
            });
            hasAutoAndFillColumnSize = hasAuto && hasFill;
        }

        if (hasAutoAndFillColumnSize) {
            // 宽度是不是受限
            if ((ob.scrollable !== true && ob.scrollx !== true) || ob.horizontalAlign === BI.HorizontalAlign.Stretch) {
                return BI.extend({
                    verticalAlign: BI.VerticalAlign.Top
                }, ob, {type: "bi.horizontal_float_fill"});
            }
            return BI.extend({
                horizontalAlign: BI.HorizontalAlign.Stretch
            }, ob, {type: "bi.table_adapt"});
        }
        return ob;
    });
    BI.Plugin.configWidget("bi.center_adapt", function (ob) {
        var supportFlex = isSupportFlex();
        // var isAdapt = !ob.horizontalAlign || ob.horizontalAlign === BI.HorizontalAlign.Center || ob.horizontalAlign === BI.HorizontalAlign.Stretch;
        // if (!isAdapt || justOneItem) {
        if (supportFlex) {
            return BI.extend({}, ob, {type: "bi.flex_center_adapt"});
        }
        return BI.extend({}, ob, {type: "bi.inline_center_adapt"});
        // }
        // return ob;
    });
    BI.Plugin.configWidget("bi.vertical_adapt", function (ob) {
        var supportFlex = isSupportFlex();
        // var isAdapt = ob.horizontalAlign === BI.HorizontalAlign.Center || ob.horizontalAlign === BI.HorizontalAlign.Stretch;
        // if (!isAdapt || justOneItem) {
        if (supportFlex) {
            return BI.extend({}, ob, {type: "bi.flex_vertical_center_adapt"});
        }
        return BI.extend({}, ob, {type: "bi.inline_vertical_adapt"});
        // }
        // return ob;
    });
    BI.Plugin.configWidget("bi.horizontal_adapt", function (ob) {
        var justOneItem = (ob.items && ob.items.length <= 1);
        var isAdapt = !ob.horizontalAlign || ob.horizontalAlign === BI.HorizontalAlign.Center || ob.horizontalAlign === BI.HorizontalAlign.Stretch;
        var verticalAlignTop = !ob.verticalAlign || ob.verticalAlign === BI.VerticalAlign.TOP;
        if (verticalAlignTop && justOneItem) {
            return BI.extend({}, ob, {type: "bi.horizontal_auto"});
        }
        var supportFlex = isSupportFlex();
        // 在横向自适应场景下我们需要使用table的自适应撑出滚动条的特性（flex处理不了这种情况）
        // 主要出现在center_adapt或者horizontal_adapt的场景，或者主动设置horizontalAlign的场景
        if (isAdapt) {
            return BI.extend({
                horizontalAlign: BI.HorizontalAlign.Center
            }, ob, {type: "bi.table_adapt"});
        }
        if (supportFlex) {
            return BI.extend({
                horizontalAlign: BI.HorizontalAlign.Center,
                scrollx: false
            }, ob, {type: "bi.flex_horizontal"});
        }
        return BI.extend({
            horizontalAlign: BI.HorizontalAlign.Center
        }, ob, {type: "bi.table_adapt"});
    });
    BI.Plugin.configWidget("bi.horizontal_float", function (ob) {
        if (isSupportFlex()) {
            return BI.extend({}, ob, {type: "bi.flex_horizontal_adapt"});
        }
        if (ob.items && ob.items.length <= 1) {
            return BI.extend({}, ob, {type: "bi.inline_horizontal_adapt"});
        }
        return ob;
    });

    BI.Plugin.configWidget("bi.horizontal_fill", function (ob) {
        if (isSupportFlex()) {
            return BI.extend({
                horizontalAlign: BI.HorizontalAlign.Stretch,
                verticalAlign: BI.VerticalAlign.Stretch,
                scrollx: false
            }, ob, {type: "bi.flex_horizontal"});
        }
        if ((ob.horizontalAlign && ob.horizontalAlign !== BI.HorizontalAlign.Stretch) || (ob.scrollable === true || ob.scrollx === true)) {
            // 宽度不受限，要用table布局
            return BI.extend({
                horizontalAlign: BI.HorizontalAlign.Stretch,
                verticalAlign: BI.VerticalAlign.Stretch
            }, ob, {type: "bi.table_adapt"});
        }
        return BI.extend({}, ob, {type: "bi.horizontal_float_fill"});
    });
    BI.Plugin.configWidget("bi.vertical_fill", function (ob) {
        if (isSupportFlex()) {
            return BI.extend({
                horizontalAlign: BI.HorizontalAlign.Stretch,
                verticalAlign: BI.VerticalAlign.Stretch,
                scrolly: false
            }, ob, {type: "bi.flex_vertical"});
        }
        return BI.extend({}, ob, {type: "bi.vtape"});
    });

    BI.Plugin.configWidget("bi.left_right_vertical_adapt", function (ob) {
        if (isSupportFlex()) {
            // IE下其实也是可以使用flex布局的，只要排除掉出现滚动条的情况
            // if (!BI.isIE() || (ob.scrollable !== true && ob.scrolly !== true)) {
            return BI.extend({}, ob, {type: "bi.flex_left_right_vertical_adapt"});
            // }
        }
        return ob;
    });
    BI.Plugin.configWidget("bi.flex_horizontal", function (ob) {
        if (ob.scrollable === true || ob.scrollx !== false) {
            if (ob.hgap > 0 || ob.rgap > 0) {// flex中最后一个margin-right不生效
                return BI.extend({}, ob, {type: "bi.flex_scrollable_horizontal"});
            }
        }
    });
    BI.Plugin.configWidget("bi.flex_vertical", function (ob) {
        if (ob.scrollable === true || ob.scrollx === true) {
            if (ob.hgap > 0 || ob.rgap > 0) {// flex中最后一个margin-right不生效
                return BI.extend({}, ob, {type: "bi.flex_scrollable_vertical"});
            }
        }
    });

    BI.Plugin.configWidget("bi.radio", function (ob) {
        if (BI.isIE() && BI.getIEVersion() <= 9) {
            return BI.extend({}, ob, {type: "bi.image_radio"});
        }
        return ob;
    });

    BI.Plugin.configWidget("bi.checkbox", function (ob) {
        if (BI.isIE() && BI.getIEVersion() <= 9) {
            return BI.extend({}, ob, {type: "bi.image_checkbox"});
        }
        return ob;
    });

    BI.Plugin.configWidget("bi.half_icon_button", function (ob) {
        if (BI.isIE() && BI.getIEVersion() < 9) {
            return ob;
        }
        return BI.extend({}, ob, {type: "bi.half_button"});
    });
});
<commit_msg>Pull request #2296: 无JIRA任务 优化代码<commit_after>// 工程配置
BI.prepares.push(function () {
    // 注册布局
    // adapt类布局优先级规则
    // 1、在非IE且支持flex的浏览器下使用flex布局
    // 2、IE或者不支持flex的浏览器下使用inline布局
    // 3、在2的情况下如果布局的items大于1的话使用display:table的布局
    // 4、在3的情况下如果IE版本低于8使用table标签布局
    var _isSupportFlex;
    var isSupportFlex = function () {
        if (_isSupportFlex == null) {
            _isSupportFlex = !!(BI.isSupportCss3 && BI.isSupportCss3("flex"));
        }
        return _isSupportFlex;
    };
    BI.Plugin.configWidget("bi.horizontal", function (ob) {
        var supportFlex = isSupportFlex();
        // // 在横向自适应场景下我们需要使用table的自适应撑出滚动条的特性（flex处理不了这种情况）
        // // 主要出现在center_adapt或者horizontal_adapt的场景，或者主动设置horizontalAlign的场景
        // if (ob.horizontalAlign === BI.HorizontalAlign.Center || ob.horizontalAlign === BI.HorizontalAlign.Stretch) {
        //     return BI.extend({}, ob, {type: "bi.table_adapt"});
        // }
        if (supportFlex) {
            return BI.extend({}, ob, {type: "bi.flex_horizontal"});
        }
        return BI.extend({
            scrollx: true
        }, ob, {type: "bi.inline"});
    });
    BI.Plugin.configWidget("bi.inline", function (ob) {
        // 当列宽既需要自动列宽又需要自适应列宽时，inline布局也处理不了了，降级table处理吧
        var hasAutoAndFillColumnSize = false;
        if (ob.columnSize && ob.columnSize.length > 0) {
            if (ob.columnSize.indexOf("") >= 0 && ob.columnSize.indexOf("fill") >= 0) {
                hasAutoAndFillColumnSize = true;
            }
        } else {
            var hasAuto = false, hasFill = false;
            BI.each(ob.items, function (i, item) {
                if (item.width === "fill") {
                    hasFill = true;
                } else if (BI.isNull(item.width) || item.width === "") {
                    hasAuto = true;
                }
            });
            hasAutoAndFillColumnSize = hasAuto && hasFill;
        }

        if (hasAutoAndFillColumnSize) {
            // 宽度是不是受限
            if ((ob.scrollable !== true && ob.scrollx !== true) || ob.horizontalAlign === BI.HorizontalAlign.Stretch) {
                return BI.extend({
                    verticalAlign: BI.VerticalAlign.Top
                }, ob, {type: "bi.horizontal_float_fill"});
            }
            return BI.extend({
                horizontalAlign: BI.HorizontalAlign.Stretch
            }, ob, {type: "bi.table_adapt"});
        }
        return ob;
    });
    BI.Plugin.configWidget("bi.center_adapt", function (ob) {
        var supportFlex = isSupportFlex();
        // var isAdapt = !ob.horizontalAlign || ob.horizontalAlign === BI.HorizontalAlign.Center || ob.horizontalAlign === BI.HorizontalAlign.Stretch;
        // if (!isAdapt || justOneItem) {
        if (supportFlex) {
            return BI.extend({}, ob, {type: "bi.flex_center_adapt"});
        }
        return BI.extend({}, ob, {type: "bi.inline_center_adapt"});
        // }
        // return ob;
    });
    BI.Plugin.configWidget("bi.vertical_adapt", function (ob) {
        var supportFlex = isSupportFlex();
        // var isAdapt = ob.horizontalAlign === BI.HorizontalAlign.Center || ob.horizontalAlign === BI.HorizontalAlign.Stretch;
        // if (!isAdapt || justOneItem) {
        if (supportFlex) {
            return BI.extend({}, ob, {type: "bi.flex_vertical_center_adapt"});
        }
        return BI.extend({}, ob, {type: "bi.inline_vertical_adapt"});
        // }
        // return ob;
    });
    BI.Plugin.configWidget("bi.horizontal_adapt", function (ob) {
        var justOneItem = (ob.items && ob.items.length <= 1);
        var isAdapt = !ob.horizontalAlign || ob.horizontalAlign === BI.HorizontalAlign.Center || ob.horizontalAlign === BI.HorizontalAlign.Stretch;
        var verticalAlignTop = !ob.verticalAlign || ob.verticalAlign === BI.VerticalAlign.TOP;
        if (verticalAlignTop && justOneItem) {
            return BI.extend({}, ob, {type: "bi.horizontal_auto"});
        }
        var supportFlex = isSupportFlex();
        // 在横向自适应场景下我们需要使用table的自适应撑出滚动条的特性（flex处理不了这种情况）
        // 主要出现在center_adapt或者horizontal_adapt的场景，或者主动设置horizontalAlign的场景
        if (isAdapt) {
            return BI.extend({
                horizontalAlign: BI.HorizontalAlign.Center
            }, ob, {type: "bi.table_adapt"});
        }
        if (supportFlex) {
            return BI.extend({
                horizontalAlign: BI.HorizontalAlign.Center,
                scrollx: false
            }, ob, {type: "bi.flex_horizontal"});
        }
        return BI.extend({
            horizontalAlign: BI.HorizontalAlign.Center
        }, ob, {type: "bi.table_adapt"});
    });
    BI.Plugin.configWidget("bi.horizontal_float", function (ob) {
        if (isSupportFlex()) {
            return BI.extend({}, ob, {type: "bi.flex_horizontal_adapt"});
        }
        if (ob.items && ob.items.length <= 1) {
            return BI.extend({}, ob, {type: "bi.inline_horizontal_adapt"});
        }
        return ob;
    });

    BI.Plugin.configWidget("bi.horizontal_fill", function (ob) {
        if (isSupportFlex()) {
            return BI.extend({
                horizontalAlign: BI.HorizontalAlign.Stretch,
                verticalAlign: BI.VerticalAlign.Stretch,
                scrollx: false
            }, ob, {type: "bi.flex_horizontal"});
        }
        if ((ob.horizontalAlign && ob.horizontalAlign !== BI.HorizontalAlign.Stretch) || (ob.scrollable === true || ob.scrollx === true)) {
            // 宽度不受限，要用table布局
            return BI.extend({
                horizontalAlign: BI.HorizontalAlign.Stretch,
                verticalAlign: BI.VerticalAlign.Stretch
            }, ob, {type: "bi.table_adapt"});
        }
        return BI.extend({}, ob, {type: "bi.horizontal_float_fill"});
    });
    BI.Plugin.configWidget("bi.vertical_fill", function (ob) {
        if (isSupportFlex()) {
            return BI.extend({
                horizontalAlign: BI.HorizontalAlign.Stretch,
                verticalAlign: BI.VerticalAlign.Stretch,
                scrolly: false
            }, ob, {type: "bi.flex_vertical"});
        }
        return BI.extend({}, ob, {
            type: "bi.td",
            items: BI.map(ob.items, function (i, item) {
                return [item];
            })});
    });

    BI.Plugin.configWidget("bi.left_right_vertical_adapt", function (ob) {
        if (isSupportFlex()) {
            // IE下其实也是可以使用flex布局的，只要排除掉出现滚动条的情况
            // if (!BI.isIE() || (ob.scrollable !== true && ob.scrolly !== true)) {
            return BI.extend({}, ob, {type: "bi.flex_left_right_vertical_adapt"});
            // }
        }
        return ob;
    });
    BI.Plugin.configWidget("bi.flex_horizontal", function (ob) {
        if (ob.scrollable === true || ob.scrollx !== false) {
            if (ob.hgap > 0 || ob.rgap > 0) {// flex中最后一个margin-right不生效
                return BI.extend({}, ob, {type: "bi.flex_scrollable_horizontal"});
            }
        }
    });
    BI.Plugin.configWidget("bi.flex_vertical", function (ob) {
        if (ob.scrollable === true || ob.scrollx === true) {
            if (ob.hgap > 0 || ob.rgap > 0) {// flex中最后一个margin-right不生效
                return BI.extend({}, ob, {type: "bi.flex_scrollable_vertical"});
            }
        }
    });

    BI.Plugin.configWidget("bi.radio", function (ob) {
        if (BI.isIE() && BI.getIEVersion() <= 9) {
            return BI.extend({}, ob, {type: "bi.image_radio"});
        }
        return ob;
    });

    BI.Plugin.configWidget("bi.checkbox", function (ob) {
        if (BI.isIE() && BI.getIEVersion() <= 9) {
            return BI.extend({}, ob, {type: "bi.image_checkbox"});
        }
        return ob;
    });

    BI.Plugin.configWidget("bi.half_icon_button", function (ob) {
        if (BI.isIE() && BI.getIEVersion() < 9) {
            return ob;
        }
        return BI.extend({}, ob, {type: "bi.half_button"});
    });
});
<|endoftext|>


<commit_before>import React from 'react';
import {render} from 'react-dom';
import {Provider} from 'react-redux';
import Store from 'core/Store';
import Routes from 'core/Routes';

import { DevTools, DebugPanel, LogMonitor } from 'redux-devtools/lib/react';

function runApplication() {
  render(
    <Provider store={Store}>

        {Routes}
        <DebugPanel
          top
          right
          bottom
        >
          <DevTools
            store={Store}
            monitor={LogMonitor}
          />
        </DebugPanel>

    </Provider>, document.getElementById('application'));
}

runApplication();
<commit_msg>Remove Redux DevTools in production<commit_after>import React from 'react';
import {render} from 'react-dom';
import {Provider} from 'react-redux';
import Store from 'core/Store';
import Routes from 'core/Routes';

import { DevTools, DebugPanel, LogMonitor } from 'redux-devtools/lib/react';

function runApplication() {
  render(
    <Provider store={Store}>
    {(() => {
      if (__DEV__) {
        return (

            {Routes}
            <DebugPanel
              top
              right
              bottom
            >
              <DevTools
                store={Store}
                monitor={LogMonitor}
              />
            </DebugPanel>

        );
      } else {
        return Routes;
      }
    })()}
    </Provider>, document.getElementById('application'));
}

runApplication();
<|endoftext|>


<commit_before>define(["require", "exports", "module", "./VerletParticle2D","./VerletSpring2D"], function(require, exports, module) {

var VerletParticle2D = require('./VerletParticle2D'),
	VerletSpring2D = require('./VerletSpring2D');

/**
* Utility builder/grouping/management class to connect a set of particles into
* a physical string/thread. Custom spring types can be used by subclassing this
* class and overwriting the
* {@link #createSpring(VerletParticle2D, VerletParticle2D, float, float)}
method.
*/

 /**
  Construct a ParticleString2D,
  parameter options:
  1 - options object
  3 - VerletPhysics2D physics, Array<VerletParticle2D> plist, Number strength
  6 - VerletPhysics2D physic, Vec2D pos, Vec2D step, Number num, Number mass, Number strength
  */

var	ParticleString2D = function(){
	var opts = {
		physics: undefined,
		plist: undefined,
		pos: undefined,
		step: undefined,
		num: undefined,
		mass: undefined,
		strength: undefined
	},
	is6ParamConstructor = false;
	if(arguments.length === 0){
		throw new Error("Incorrect Parameters");
	} else if(arguments.length == 1){ //options object
		var arg = arguments[0];
		for(var prop in arg){
			opts[prop] = arg[prop];
		}
	} else {
		opts.physics = arguments[0];
		if(arguments.length == 6){
			opts.pos = arguments[1];
			opts.step = arguments[2];
			opts.num = arguments[3];
			opts.mass = arguments[4];
			opts.strength = arguments[5];
		} else {
			opts.plist = arguments[1];
			opts.strength = arguments[2];
		}
	}
	if(opts.num !== undefined && opts.pos !== undefined && opts.step !== undefined && opts.mass !== undefined){
		is6ParamConstructor = true;
	}
	if(!is6ParamConstructor && opts.plist === undefined){
		throw new Error("Incorrect Parameters, please supply plist or num, pos, step & mass");
	}

	this.physics = opts.physics;
	this.links = [];

	var prev,
		p,
		s,
		strength,
		i = 0;

	if(is6ParamConstructor){
		var pos = opts.pos.copy(),
			step = opts.step,
			mass = opts.mass,
			len = step.magnitude();
		this.particles = [];
		strength = opts.strength;

		for(i = 0; i < opts.num; i++){
			p = new VerletParticle2D(pos.copy(),mass);
			this.particles.push(p);
			this.physics.particles.push(p);
			if(prev !== undefined){
				s = this.createSpring(prev,p,len,strength);
				this.links.push(s);
				this.physics.addSpring(s);
			}
			prev = p;
			pos.addSelf(step);
		}
	} else {
		strength = opts.strength;
		this.particles = opts.plist || [];

		for(i = 0; i < this.particles.length; i++){
			p = this.particles[i];
			this.physics.addParticle(p);
			if(prev !== undefined){
				s = this.createSpring(prev,p,prev.distanceTo(p),strength);
				this.links.push(s);
				this.physics.addSpring(s);
			}
			prev = p;
		}
	}
 };
ParticleString2D.prototype = {
	clear: function(){
		for(var i = 0, len = this.links.length; i < len; i++){
			this.physics.removeSpringElements(s);
		}
		this.particles.clear();
		this.links.clear();
	},
	createSpring: function(a,b,len,strength){
		return new VerletSpring2D(a,b,len,strength);
	},

	getHead: function(){
		return this.particles[0];
	},

	getNumParticles: function(){
		return this.particles.length;
	},

	getTail: function(){
		return this.particles[this.particles.length-1];
	}
};

module.exports = ParticleString2D;
});
<commit_msg>fix for ParticleString2D.clear<commit_after>define(["require", "exports", "module", "./VerletParticle2D","./VerletSpring2D"], function(require, exports, module) {

var VerletParticle2D = require('./VerletParticle2D'),
	VerletSpring2D = require('./VerletSpring2D');

/**
* Utility builder/grouping/management class to connect a set of particles into
* a physical string/thread. Custom spring types can be used by subclassing this
* class and overwriting the
* {@link #createSpring(VerletParticle2D, VerletParticle2D, float, float)}
method.
*/

 /**
  Construct a ParticleString2D,
  parameter options:
  1 - options object
  3 - VerletPhysics2D physics, Array<VerletParticle2D> plist, Number strength
  6 - VerletPhysics2D physic, Vec2D pos, Vec2D step, Number num, Number mass, Number strength
  */

var	ParticleString2D = function(){
	var opts = {
		physics: undefined,
		plist: undefined,
		pos: undefined,
		step: undefined,
		num: undefined,
		mass: undefined,
		strength: undefined
	},
	is6ParamConstructor = false;
	if(arguments.length === 0){
		throw new Error("Incorrect Parameters");
	} else if(arguments.length == 1){ //options object
		var arg = arguments[0];
		for(var prop in arg){
			opts[prop] = arg[prop];
		}
	} else {
		opts.physics = arguments[0];
		if(arguments.length == 6){
			opts.pos = arguments[1];
			opts.step = arguments[2];
			opts.num = arguments[3];
			opts.mass = arguments[4];
			opts.strength = arguments[5];
		} else {
			opts.plist = arguments[1];
			opts.strength = arguments[2];
		}
	}
	if(opts.num !== undefined && opts.pos !== undefined && opts.step !== undefined && opts.mass !== undefined){
		is6ParamConstructor = true;
	}
	if(!is6ParamConstructor && opts.plist === undefined){
		throw new Error("Incorrect Parameters, please supply plist or num, pos, step & mass");
	}

	this.physics = opts.physics;
	this.links = [];

	var prev,
		p,
		s,
		strength,
		i = 0;

	if(is6ParamConstructor){
		var pos = opts.pos.copy(),
			step = opts.step,
			mass = opts.mass,
			len = step.magnitude();
		this.particles = [];
		strength = opts.strength;

		for(i = 0; i < opts.num; i++){
			p = new VerletParticle2D(pos.copy(),mass);
			this.particles.push(p);
			this.physics.particles.push(p);
			if(prev !== undefined){
				s = this.createSpring(prev,p,len,strength);
				this.links.push(s);
				this.physics.addSpring(s);
			}
			prev = p;
			pos.addSelf(step);
		}
	} else {
		strength = opts.strength;
		this.particles = opts.plist || [];

		for(i = 0; i < this.particles.length; i++){
			p = this.particles[i];
			this.physics.addParticle(p);
			if(prev !== undefined){
				s = this.createSpring(prev,p,prev.distanceTo(p),strength);
				this.links.push(s);
				this.physics.addSpring(s);
			}
			prev = p;
		}
	}
 };
ParticleString2D.prototype = {
	clear: function(){
		for(var i = 0, len = this.links.length; i < len; i++){
			this.physics.removeSpringElements(this.links[i]);
		}
		this.particles = [];
		this.links = [];
	},
	createSpring: function(a,b,len,strength){
		return new VerletSpring2D(a,b,len,strength);
	},

	getHead: function(){
		return this.particles[0];
	},

	getNumParticles: function(){
		return this.particles.length;
	},

	getTail: function(){
		return this.particles[this.particles.length-1];
	}
};

module.exports = ParticleString2D;
});
<|endoftext|>


<commit_before>require("source-map-support/register");
var pkg = require("./package.json");

module.exports = {
  build: require("./lib/build"),
  create: require("./lib/commands/create/helpers"),
  console: require("./lib/repl"),
  contracts: require("@truffle/workflow-compile"),
  package: require("./lib/package"),
  test: require("./lib/test"),
  version: pkg.version,
  ganache: require("ganache-core/public-exports")
};
<commit_msg>Expose the legacy version of workflow-compile in core to avoid a breaking change to Truffle<commit_after>require("source-map-support/register");
const pkg = require("./package.json");

module.exports = {
  build: require("./lib/build"),
  create: require("./lib/commands/create/helpers"),
  console: require("./lib/repl"),
  // TODO: update this to non-legacy the next breaking change
  contracts: require("@truffle/workflow-compile/legacy"),
  package: require("./lib/package"),
  test: require("./lib/test"),
  version: pkg.version,
  ganache: require("ganache-core/public-exports")
};
<|endoftext|>


<commit_before>import {
  supportsPassive
} from 'uni-shared'

import {
  normalizeDataset
} from 'uni-helpers/index'

import {
  wrapperMPEvent
} from 'uni-helpers/patch'

import getWindowOffset from 'uni-platform/helpers/get-window-offset'

function processTarget (target, detail) {
  const res = {
    id: target.id,
    offsetLeft: target.offsetLeft,
    offsetTop: target.offsetTop,
    dataset: normalizeDataset(target.dataset)
  }
  if (detail) {
    Object.assign(res, detail)
  }
  return res
}

function processTouches (touches) {
  if (touches) {
    const res = []

    const {
      top
    } = getWindowOffset()

    for (let i = 0; i < touches.length; i++) {
      const touch = touches[i]
      res.push({
        identifier: touch.identifier,
        pageX: touch.pageX,
        pageY: touch.pageY - top,
        clientX: touch.clientX,
        clientY: touch.clientY - top,
        force: touch.force || 0
      })
    }
    return res
  }
  return []
}

export function processEvent (name, $event = {}, detail = {}, target = {}, currentTarget = {}) {
  if ($event._processed) {
    $event.type = detail.type || name
    return $event
  }

  // fixed 针对小程序 click（tap）事件，补充事件详情
  if (name === 'click') {
    const {
      top
    } = getWindowOffset()

    detail = {
      x: $event.x,
      y: $event.y - top
    }
    $event.touches = $event.changedTouches = [{
      force: 1,
      identifier: 0,
      clientX: $event.clientX,
      clientY: $event.clientY,
      pageX: $event.pageX,
      pageY: $event.pageY
    }]
  }

  // fixed mp-vue
  return wrapperMPEvent({
    type: detail.type || name,
    timeStamp: $event.timeStamp || 0,
    detail: detail,
    target: processTarget(target, detail),
    currentTarget: processTarget(currentTarget),
    // 只处理系统事件
    touches: $event instanceof Event ? processTouches($event.touches) : $event.touches,
    changedTouches: $event instanceof Event ? processTouches($event.changedTouches) : $event.changedTouches,
    preventDefault () { },
    stopPropagation () { }
  })
}

const LONGPRESS_TIMEOUT = 350
const LONGPRESS_THRESHOLD = 10

const passiveOptions = supportsPassive ? {
  passive: true
} : false

let longPressTimer = false

function clearLongPressTimer () {
  if (longPressTimer) {
    clearTimeout(longPressTimer)
    longPressTimer = false
  }
}

let startPageX = 0
let startPageY = 0

function touchstart (evt) {
  clearLongPressTimer()
  if (evt.touches.length !== 1) {
    return
  }
  const {
    touches: [{
      pageX,
      pageY
    }]
  } = evt

  startPageX = pageX
  startPageY = pageY

  longPressTimer = setTimeout(function () {
    evt.target.dispatchEvent(new CustomEvent('longpress', {
      bubbles: true,
      cancelable: true,
      target: evt.target,
      currentTarget: evt.currentTarget,
      touches: evt.touches,
      changedTouches: evt.changedTouches
    }))
  }, LONGPRESS_TIMEOUT)
}

function touchmove (evt) {
  if (!longPressTimer) {
    return
  }

  if (evt.touches.length !== 1) {
    return clearLongPressTimer()
  }

  const {
    touches: [{
      pageX,
      pageY
    }]
  } = evt

  if (Math.abs(pageX - startPageX) > LONGPRESS_THRESHOLD || Math.abs(pageY - startPageY) > LONGPRESS_THRESHOLD) {
    return clearLongPressTimer()
  }
}

export function initEvents () {
  window.addEventListener('touchstart', touchstart, passiveOptions)
  window.addEventListener('touchmove', touchmove, passiveOptions)
  window.addEventListener('touchend', clearLongPressTimer, passiveOptions)
  window.addEventListener('touchcancel', clearLongPressTimer, passiveOptions)
}
<commit_msg>fix: H5平台 longpress 事件回调 touches/changedTouches 为 [] Bug<commit_after>import {
  supportsPassive
} from 'uni-shared'

import {
  normalizeDataset
} from 'uni-helpers/index'

import {
  wrapperMPEvent
} from 'uni-helpers/patch'

import getWindowOffset from 'uni-platform/helpers/get-window-offset'

function processTarget (target, detail) {
  const res = {
    id: target.id,
    offsetLeft: target.offsetLeft,
    offsetTop: target.offsetTop,
    dataset: normalizeDataset(target.dataset)
  }
  if (detail) {
    Object.assign(res, detail)
  }
  return res
}

function processTouches (touches) {
  if (touches) {
    const res = []

    const {
      top
    } = getWindowOffset()

    for (let i = 0; i < touches.length; i++) {
      const touch = touches[i]
      res.push({
        identifier: touch.identifier,
        pageX: touch.pageX,
        pageY: touch.pageY - top,
        clientX: touch.clientX,
        clientY: touch.clientY - top,
        force: touch.force || 0
      })
    }
    return res
  }
  return []
}

export function processEvent (name, $event = {}, detail = {}, target = {}, currentTarget = {}) {
  if ($event._processed) {
    $event.type = detail.type || name
    return $event
  }

  // fixed 针对小程序 click（tap）事件，补充事件详情
  if (name === 'click') {
    const {
      top
    } = getWindowOffset()

    detail = {
      x: $event.x,
      y: $event.y - top
    }
    $event.touches = $event.changedTouches = [{
      force: 1,
      identifier: 0,
      clientX: $event.clientX,
      clientY: $event.clientY,
      pageX: $event.pageX,
      pageY: $event.pageY
    }]
  }

  // fixed mp-vue
  return wrapperMPEvent({
    type: detail.type || name,
    timeStamp: $event.timeStamp || 0,
    detail: detail,
    target: processTarget(target, detail),
    currentTarget: processTarget(currentTarget),
    // 只处理系统事件
    touches: ($event instanceof Event || $event instanceof CustomEvent) ? processTouches($event.touches) : $event.touches,
    changedTouches: ($event instanceof Event || $event instanceof CustomEvent) ? processTouches($event.changedTouches) : $event.changedTouches,
    preventDefault () { },
    stopPropagation () { }
  })
}

const LONGPRESS_TIMEOUT = 350
const LONGPRESS_THRESHOLD = 10

const passiveOptions = supportsPassive ? {
  passive: true
} : false

let longPressTimer = false

function clearLongPressTimer () {
  if (longPressTimer) {
    clearTimeout(longPressTimer)
    longPressTimer = false
  }
}

let startPageX = 0
let startPageY = 0

function touchstart (evt) {
  clearLongPressTimer()
  if (evt.touches.length !== 1) {
    return
  }
  const {
    touches: [{
      pageX,
      pageY
    }]
  } = evt

  startPageX = pageX
  startPageY = pageY

  longPressTimer = setTimeout(function () {
    let customEvent = new CustomEvent('longpress', {
      bubbles: true,
      cancelable: true,
      target: evt.target,
      currentTarget: evt.currentTarget
    })
    customEvent.touches = evt.touches
    customEvent.changedTouches = evt.changedTouches
    evt.target.dispatchEvent(customEvent)
  }, LONGPRESS_TIMEOUT)
}

function touchmove (evt) {
  if (!longPressTimer) {
    return
  }

  if (evt.touches.length !== 1) {
    return clearLongPressTimer()
  }

  const {
    touches: [{
      pageX,
      pageY
    }]
  } = evt

  if (Math.abs(pageX - startPageX) > LONGPRESS_THRESHOLD || Math.abs(pageY - startPageY) > LONGPRESS_THRESHOLD) {
    return clearLongPressTimer()
  }
}

export function initEvents () {
  window.addEventListener('touchstart', touchstart, passiveOptions)
  window.addEventListener('touchmove', touchmove, passiveOptions)
  window.addEventListener('touchend', clearLongPressTimer, passiveOptions)
  window.addEventListener('touchcancel', clearLongPressTimer, passiveOptions)
}
<|endoftext|>


<commit_before>import { arc, pie } from  'd3-shape';
import Ember from 'ember';
import layout from './template';
import GroupElement from '../../mixins/group-element';
import { interpolateCool } from 'd3-scale';

const {
  Component,
  computed,
  get,
  getProperties,
  run,
  run: { scheduleOnce }
} = Ember;

const DonutComponent = Component.extend(GroupElement, {
  layout,

  radius: computed('width', 'height', function() {
    let { width, height } = getProperties(this, 'width', 'height');
    return Math.min(width, height) / 2;
  }),

  transform: computed('width', 'height', function() {
    let { width, height } = getProperties(this, 'width', 'height');

    return `translate(${width / 2},${height / 2})`;
  }),

  innerRadius: computed('radius', function() {
    return get(this, 'radius') - 32;
  }),

  outerRadius: computed('radius', function() {
    return get(this, 'radius');
  }),

  cornerRadius: 8,
  colorScale: interpolateCool,
  padDegrees: 5,

  onArcClick: null,
  onArcEnter: null,
  onArcLeave: null,

  drawnValues: [],

  didReceiveAttrs() {
    this._super(...arguments);

    scheduleOnce('afterRender', this, this.draw);
  },

  pie: computed('padDegrees', function() {
    return pie()
      .padAngle(get(this, 'padDegrees') / 360)
      .value((d) => d[1]);
  }),

  piedValues: computed('pie', 'values.[]', function() {
    let { values, pie } = getProperties(this, 'values', 'pie');

    return pie(values);
  }),

  arc: computed('cornerRadius', 'innerRadius', 'outerRadius', function() {
    let { cornerRadius, innerRadius, outerRadius } =
      getProperties(this, 'cornerRadius', 'innerRadius', 'outerRadius');

    return arc()
      .cornerRadius(cornerRadius)
      .innerRadius(innerRadius)
      .outerRadius(outerRadius);
  }),

  draw() {
    let { piedValues, arc, colorScale } = getProperties(this, 'piedValues', 'arc', 'colorScale');

    let arcs = this.selection.selectAll('.arc path');

    if (piedValues !== this.drawnValues || piedValues.length !== this.drawnValues.length) {
      arcs = arcs.data(piedValues).enter()
        .append('g')
          .attr('class', 'arc')
          .append('path')
          .on('click', (d) => run(this, this.sendAction, 'onArcClick', d.data[0]))
          .on('mouseenter', (d) => run(this, this.sendAction, 'onArcEnter', d.data[0]))
          .on('mouseleave', (d) => run(this, this.sendAction, 'onArcLeave', d.data[0]));
    }

    arcs
      .attr('fill', (d) => colorScale(d.data[0]))
      .attr('d', arc);
  }
});

DonutComponent.reopenClass({
  positionalParams: [ 'values' ]
});

export default DonutComponent;
<commit_msg>add data-title and stroke to arcs<commit_after>import { arc, pie } from  'd3-shape';
import Ember from 'ember';
import layout from './template';
import GroupElement from '../../mixins/group-element';
import { interpolateCool } from 'd3-scale';

const {
  Component,
  computed,
  get,
  getProperties,
  run,
  run: { scheduleOnce }
} = Ember;

const DonutComponent = Component.extend(GroupElement, {
  layout,

  radius: computed('width', 'height', function() {
    let { width, height } = getProperties(this, 'width', 'height');
    return Math.min(width, height) / 2;
  }),

  transform: computed('width', 'height', function() {
    let { width, height } = getProperties(this, 'width', 'height');

    return `translate(${width / 2},${height / 2})`;
  }),

  innerRadius: computed('radius', function() {
    return get(this, 'radius') - 32;
  }),

  outerRadius: computed('radius', function() {
    return get(this, 'radius');
  }),

  cornerRadius: 8,
  colorScale: interpolateCool,
  padDegrees: 5,

  onArcClick: null,
  onArcEnter: null,
  onArcLeave: null,

  drawnValues: [],

  didReceiveAttrs() {
    this._super(...arguments);

    scheduleOnce('afterRender', this, this.draw);
  },

  pie: computed('padDegrees', function() {
    return pie()
      .padAngle(get(this, 'padDegrees') / 360)
      .value((d) => d[1]);
  }),

  piedValues: computed('pie', 'values.[]', function() {
    let { values, pie } = getProperties(this, 'values', 'pie');

    return pie(values);
  }),

  arc: computed('cornerRadius', 'innerRadius', 'outerRadius', function() {
    let { cornerRadius, innerRadius, outerRadius } =
      getProperties(this, 'cornerRadius', 'innerRadius', 'outerRadius');

    return arc()
      .cornerRadius(cornerRadius)
      .innerRadius(innerRadius)
      .outerRadius(outerRadius);
  }),

  draw() {
    let { piedValues, arc, colorScale } = getProperties(this, 'piedValues', 'arc', 'colorScale');

    let arcs = this.selection.selectAll('.arc path');

    if (piedValues !== this.drawnValues || piedValues.length !== this.drawnValues.length) {
      arcs = arcs.data(piedValues).enter()
        .append('g')
          .attr('class', 'arc')
          .attr('data-title', (d) => d.data[0])
          .append('path')
          .on('click', (d) => run(this, this.sendAction, 'onArcClick', d.data[0]))
          .on('mouseenter', (d) => run(this, this.sendAction, 'onArcEnter', d.data[0]))
          .on('mouseleave', (d) => run(this, this.sendAction, 'onArcLeave', d.data[0]));
    }

    arcs
      .attr('fill', (d) => colorScale(d.data[0]))
      .attr('stroke', (d) => colorScale(d.data[0]))
      .attr('d', arc);
  }
});

DonutComponent.reopenClass({
  positionalParams: [ 'values' ]
});

export default DonutComponent;
<|endoftext|>


<commit_before>import Ember from 'ember';

const { run, set, Evented, Service, computed } = Ember;

export default Service.extend(Evented, {
  window,
  targetOriginMap: null,
  allowedOrigins: computed('targetOriginMap', function() {
    let map = this.get('targetOriginMap');
    return Ember.A(Object.keys(map).map((key) => {
      return map[key];
    }));
  }),
  eventListener: null,

  init() {
    this._super(...arguments);
    let listener = run.bind(this, '_onMessage');
    this._getWindow().addEventListener('message', set(this, 'eventListener', listener));
  },

  /**
   * @private
   * @return {Window}
   */
  _getWindow() {
    return this.get('window');
  },

  /**
   * Check if message origin is allowed
   *
   * @param  {String}  origin
   * @private
   * @return {Boolean}
   */

  _isOriginAllowed(origin) {
    return this.get('allowedOrigins').includes(origin);
  },

  _parseMessage(data) {
    let message = null;
    if (typeof data === 'string') {
      try {
        message = JSON.parse(data);
      } catch(e) {/* Ignored */}
    }
    return message;
  },

  _onMessage(event) {
    if (this._isOriginAllowed(event.origin)) {
      let message = this._parseMessage(event.data);
      if (message !== null) {
        this.trigger(`from:${message.type}`, message);
      }
    }
    return null;
  },

  willDestroy() {
    this._super(...arguments);
    // Remove event listener when this service is getting destroyed
    this._getWindow().removeEventListener('message', this.get('eventListener'));
  }
});
<commit_msg>passing event as argument to use in listener<commit_after>import Ember from 'ember';

const { run, set, Evented, Service, computed } = Ember;

export default Service.extend(Evented, {
  window,
  targetOriginMap: null,
  allowedOrigins: computed('targetOriginMap', function() {
    let map = this.get('targetOriginMap');
    return Ember.A(Object.keys(map).map((key) => {
      return map[key];
    }));
  }),
  eventListener: null,

  init() {
    this._super(...arguments);
    let listener = run.bind(this, '_onMessage');
    this._getWindow().addEventListener('message', set(this, 'eventListener', listener));
  },

  /**
   * @private
   * @return {Window}
   */
  _getWindow() {
    return this.get('window');
  },

  /**
   * Check if message origin is allowed
   *
   * @param  {String}  origin
   * @private
   * @return {Boolean}
   */

  _isOriginAllowed(origin) {
    return this.get('allowedOrigins').includes(origin);
  },

  _parseMessage(data) {
    let message = null;
    if (typeof data === 'string') {
      try {
        message = JSON.parse(data);
      } catch(e) {/* Ignored */}
    }
    return message;
  },

  _onMessage(event) {
    if (this._isOriginAllowed(event.origin)) {
      let message = this._parseMessage(event.data);
      if (message !== null) {
        this.trigger(`from:${message.type}`, message, event);
      }
    }
    return null;
  },

  willDestroy() {
    this._super(...arguments);
    // Remove event listener when this service is getting destroyed
    this._getWindow().removeEventListener('message', this.get('eventListener'));
  }
});
<|endoftext|>