<commit_before>/**
 * Created by Administrator on 2016/4/1.
 */
initial=function(){
    "use strict";

    var initial={
        iniLayerSwitch:iniLayerSwitch,
        iniElevationSlider:iniElevationSlider,
        iniCarousel:iniCarousel
    };

    function iniLayerSwitch(){
        jQuery('#LayerSwitcher').slider({
            min: 0.0,
            max: 15.0,
            value: 0,
            step: 0.1,
            slide: function (event, ui) {
                if (ui.value < 5) {
                    dataImageLayer[1].alpha = 1;
                    dataImageLayer[2].alpha = 0;
                    dataImageLayer[3].alpha = 0;

                    dataImageLayer[1].alpha = ui.value / 5;

                    //console.log(ui.value);
                } else if (ui.value >= 5 && ui.value < 10) {
                    dataImageLayer[1].alpha = 1;
                    dataImageLayer[2].alpha = 1;
                    dataImageLayer[3].alpha = 0;

                    dataImageLayer[1].alpha = (1 - (ui.value - 5) / 5);
                    dataImageLayer[2].alpha = (ui.value - 5) / 5;

                } else if (ui.value >= 10 && ui.value < 15) {
                    dataImageLayer[1].alpha = 0;
                    dataImageLayer[2].alpha = 1;
                    dataImageLayer[3].alpha = 1;

                    dataImageLayer[2].alpha = (1 - (ui.value - 10) / 5);
                    dataImageLayer[3].alpha = (ui.value - 10) / 5;

                }
            }
        });
    }

    function iniElevationSlider(){
        //jQuery('#ElevationSlider').slider({
        //    min: 1.0,
        //    max: 25.0,
        //    value: mapView.verticalScale,
        //    step: 0.1,
        //    slide: function (event, ui) {
        //        mapView.setVerticalScale(ui.value);
        //    }
        //});
        //
    }

    function iniCarousel() {
        //$('.web3dglobe-mainmenu > li > a').click(function () {
        //    $('.web3dglobe-mainmenu > li').each(function () {
        //        $(this).removeClass('active');
        //    });
        //
        //    $(this).parent().addClass('active');
        //});

        $("#ui-carousel-next")
            .add("#ui-carousel-prev")
            .hover(
                function () {
                    $(this).css("opacity", 0.7);
                },
                function () {
                    $(this).css("opacity", 1.0);
                }
            );
        $.each($('#carousel-items').children(), function (i, e) {
            carousel_items.push($(e).html());
            prodList.push({
                label: $($(e).children()['1']).text()
            });
        });
    }
};

var initialize= function () {
    //常见的是返回一个拥有多种功能的对象
    //如果是单一的功能,可能就附加到其他对象上了
}();

var initialized= function () {

};
var iii=initialized();
//iii.***
//这样组织的原因是把相关的函数变量或者只用一次的,中间的函数都整理到一个大的函数对象内部,便于组织管理也便于访问,
//感觉自己在将一个功能的代码搞到一块的能力还有点欠缺的.<commit_msg>initial.js<commit_after>/**
 * Created by Administrator on 2016/4/1.
 */
initial=function(){
    "use strict";

    var initial={
        iniLayerSwitch:iniLayerSwitch,
        iniElevationSlider:iniElevationSlider,
        iniCarousel:iniCarousel
    };
    //先初始化成两个函数,把功能实现再说,然后再去完善这个功能,让他更全面些,有头有尾巴

    function iniLayerSwitch(){
        jQuery('#LayerSwitcher').slider({
            min: 0.0,
            max: 15.0,
            value: 0,
            step: 0.1,
            slide: function (event, ui) {
                if (ui.value < 5) {
                    dataImageLayer[1].alpha = 1;
                    dataImageLayer[2].alpha = 0;
                    dataImageLayer[3].alpha = 0;

                    dataImageLayer[1].alpha = ui.value / 5;

                    //console.log(ui.value);
                } else if (ui.value >= 5 && ui.value < 10) {
                    dataImageLayer[1].alpha = 1;
                    dataImageLayer[2].alpha = 1;
                    dataImageLayer[3].alpha = 0;

                    dataImageLayer[1].alpha = (1 - (ui.value - 5) / 5);
                    dataImageLayer[2].alpha = (ui.value - 5) / 5;

                } else if (ui.value >= 10 && ui.value < 15) {
                    dataImageLayer[1].alpha = 0;
                    dataImageLayer[2].alpha = 1;
                    dataImageLayer[3].alpha = 1;

                    dataImageLayer[2].alpha = (1 - (ui.value - 10) / 5);
                    dataImageLayer[3].alpha = (ui.value - 10) / 5;

                }
            }
        });
    }

    function iniElevationSlider(){
        //jQuery('#ElevationSlider').slider({
        //    min: 1.0,
        //    max: 25.0,
        //    value: mapView.verticalScale,
        //    step: 0.1,
        //    slide: function (event, ui) {
        //        mapView.setVerticalScale(ui.value);
        //    }
        //});
        //
    }

    function iniCarousel() {
        //$('.web3dglobe-mainmenu > li > a').click(function () {
        //    $('.web3dglobe-mainmenu > li').each(function () {
        //        $(this).removeClass('active');
        //    });
        //
        //    $(this).parent().addClass('active');
        //});

        $("#ui-carousel-next")
            .add("#ui-carousel-prev")
            .hover(
                function () {
                    $(this).css("opacity", 0.7);
                },
                function () {
                    $(this).css("opacity", 1.0);
                }
            );
        $.each($('#carousel-items').children(), function (i, e) {
            carousel_items.push($(e).html());
            prodList.push({
                label: $($(e).children()['1']).text()
            });
        });
    }

    return initial;
};

var initialize= function () {
    //常见的是返回一个拥有多种功能的对象
    //如果是单一的功能,可能就附加到其他对象上了
}();

var initialized= function () {

};
var iii=initialized();
//iii.***
//这样组织的原因是把相关的函数变量或者只用一次的,中间的函数都整理到一个大的函数对象内部,便于组织管理也便于访问,
//感觉自己在将一个功能的代码搞到一块的能力还有点欠缺的.

//最好的是将所有的代码都整理为对象的形式,整个项目的入口其实也只有一个$(document).ready(function () {})或者onload两个,
// 这两个一般都是比较简洁的写法了(一两句代码就把功能实现了),更多的东西是在这些简洁的东西后面<|endoftext|>


<commit_before>// Copyright 2002-2012, University of Colorado

/**
 * Basic 2-dimensional vector
 *
 * @author Jonathan Olson <olsonsjc@gmail.com>
 */

define( function( require ) {
  "use strict";

  var assert = require( 'ASSERT/assert' )( 'dot' );

  var dot = require( 'DOT/dot' );

  var inherit = require( 'PHET_CORE/inherit' );
  require( 'DOT/Util' );
  // require( 'DOT/Vector3' ); // commented out since Require.js complains about the circular dependency

  dot.Vector2 = function Vector2( x, y ) {
    // allow optional parameters
    this.x = x || 0;
    this.y = y || 0;

    assert && assert( typeof this.x === 'number', 'x needs to be a number' );
    assert && assert( typeof this.y === 'number', 'y needs to be a number' );
  };
  var Vector2 = dot.Vector2;

  Vector2.createPolar = function( magnitude, angle ) {
    return new Vector2( magnitude * Math.cos( phase ), magnitude * Math.sin( phase ) );
  };

  Vector2.prototype = {
    constructor: Vector2,

    isVector2: true,

    dimension: 2,

    magnitude: function() {
      return Math.sqrt( this.magnitudeSquared() );
    },

    magnitudeSquared: function() {
      return this.dot( this );
    },

    // the distance between this vector (treated as a point) and another point
    distance: function( point ) {
      return this.minus( point ).magnitude();
    },

    // the squared distance between this vector (treated as a point) and another point
    distanceSquared: function( point ) {
      return this.minus( point ).magnitudeSquared();
    },

    dot: function( v ) {
      return this.x * v.x + this.y * v.y;
    },

    equals: function( other ) {
      return this.x === other.x && this.y === other.y;
    },

    equalsEpsilon: function( other, epsilon ) {
      if ( !epsilon ) {
        epsilon = 0;
      }
      return Math.max( Math.abs( this.x - other.x ), Math.abs( this.y - other.y ) ) <= epsilon;
    },

    isFinite: function() {
      return isFinite( this.x ) && isFinite( this.y );
    },

    /*---------------------------------------------------------------------------*
     * Immutables
     *----------------------------------------------------------------------------*/

    copy: function() {
      return new this.constructor( this.x, this.y );
    },

    // z component of the equivalent 3-dimensional cross product (this.x, this.y,0) x (v.x, v.y, 0)
    crossScalar: function( v ) {
      return this.x * v.y  - this.y * v.x;
    },

    normalized: function() {
      var mag = this.magnitude();
      if ( mag === 0 ) {
        throw new Error( "Cannot normalize a zero-magnitude vector" );
      }
      else {
        return new this.constructor( this.x / mag, this.y / mag );
      }
    },

    timesScalar: function( scalar ) {
      return new this.constructor( this.x * scalar, this.y * scalar );
    },

    times: function( scalar ) {
      // make sure it's not a vector!
      assert && assert( scalar.dimension === undefined );
      return this.timesScalar( scalar );
    },

    componentTimes: function( v ) {
      return new this.constructor( this.x * v.x, this.y * v.y );
    },

    plus: function( v ) {
      return new this.constructor( this.x + v.x, this.y + v.y );
    },

    plusScalar: function( scalar ) {
      return new this.constructor( this.x + scalar, this.y + scalar );
    },

    minus: function( v ) {
      return new this.constructor( this.x - v.x, this.y - v.y );
    },

    minusScalar: function( scalar ) {
      return new this.constructor( this.x - scalar, this.y - scalar );
    },

    dividedScalar: function( scalar ) {
      return new this.constructor( this.x / scalar, this.y / scalar );
    },

    negated: function() {
      return new this.constructor( -this.x, -this.y );
    },

    angle: function() {
      return Math.atan2( this.y, this.x );
    },

    // equivalent to a -PI/2 rotation (right hand rotation)
    perpendicular: function() {
      return new this.constructor( this.y, -this.x );
    },

    angleBetween: function( v ) {
      return Math.acos( dot.clamp( this.normalized().dot( v.normalized() ), -1, 1 ) );
    },

    rotated: function( angle ) {
      var newAngle = this.angle() + angle;
      return new this.constructor( Math.cos( newAngle ), Math.sin( newAngle ) ).timesScalar( this.getMagnitude() );
    },

    // linear interpolation from this (ratio=0) to vector (ratio=1)
    blend: function( vector, ratio ) {
      return this.plus( vector.minus( this ).times( ratio ) );
    },

    toString: function() {
      return "Vector2(" + this.x + ", " + this.y + ")";
    },

    toVector3: function() {
      return new dot.Vector3( this.x, this.y );
    },

    /*---------------------------------------------------------------------------*
     * Mutables
     *----------------------------------------------------------------------------*/

    set: function( x, y ) {
      this.x = x;
      this.y = y;
      return this;
    },

    setX: function( x ) {
      this.x = x;
      return this;
    },

    setY: function( y ) {
      this.y = y;
      return this;
    },

    add: function( v ) {
      this.x += v.x;
      this.y += v.y;
      return this;
    },

    addScalar: function( scalar ) {
      this.x += scalar;
      this.y += scalar;
      return this;
    },

    subtract: function( v ) {
      this.x -= v.x;
      this.y -= v.y;
      return this;
    },

    subtractScalar: function( scalar ) {
      this.x -= scalar;
      this.y -= scalar;
      return this;
    },

    componentMultiply: function( v ) {
      this.x *= v.x;
      this.y *= v.y;
      return this;
    },

    divideScalar: function( scalar ) {
      this.x /= scalar;
      this.y /= scalar;
      return this;
    },

    negate: function() {
      this.x = -this.x;
      this.y = -this.y;
      return this;
    }

  };

  /*---------------------------------------------------------------------------*
   * Immutable Vector form
   *----------------------------------------------------------------------------*/
  Vector2.Immutable = function ImmutableVector2( x, y ) {
    Vector2.call( this, x, y );
  };
  var Immutable = Vector2.Immutable;

  inherit( Immutable, Vector2 );

  // throw errors whenever a mutable method is called on our immutable vector
  Immutable.mutableOverrideHelper = function( mutableFunctionName ) {
    Immutable.prototype[mutableFunctionName] = function() {
      throw new Error( "Cannot call mutable method '" + mutableFunctionName + "' on immutable Vector2" );
    };
  };

  // TODO: better way to handle this list?
  Immutable.mutableOverrideHelper( 'set' );
  Immutable.mutableOverrideHelper( 'setX' );
  Immutable.mutableOverrideHelper( 'setY' );
  Immutable.mutableOverrideHelper( 'copy' );
  Immutable.mutableOverrideHelper( 'add' );
  Immutable.mutableOverrideHelper( 'addScalar' );
  Immutable.mutableOverrideHelper( 'subtract' );
  Immutable.mutableOverrideHelper( 'subtractScalar' );
  Immutable.mutableOverrideHelper( 'componentMultiply' );
  Immutable.mutableOverrideHelper( 'divideScalar' );
  Immutable.mutableOverrideHelper( 'negate' );

  // helpful immutable constants
  Vector2.ZERO = new Immutable( 0, 0 );
  Vector2.X_UNIT = new Immutable( 1, 0 );
  Vector2.Y_UNIT = new Immutable( 0, 1 );

  return Vector2;
} );
<commit_msg>Bugfix<commit_after>// Copyright 2002-2012, University of Colorado

/**
 * Basic 2-dimensional vector
 *
 * @author Jonathan Olson <olsonsjc@gmail.com>
 */

define( function( require ) {
  "use strict";

  var assert = require( 'ASSERT/assert' )( 'dot' );

  var dot = require( 'DOT/dot' );

  var inherit = require( 'PHET_CORE/inherit' );
  require( 'DOT/Util' );
  // require( 'DOT/Vector3' ); // commented out since Require.js complains about the circular dependency

  dot.Vector2 = function Vector2( x, y ) {
    // allow optional parameters
    this.x = x || 0;
    this.y = y || 0;

    assert && assert( typeof this.x === 'number', 'x needs to be a number' );
    assert && assert( typeof this.y === 'number', 'y needs to be a number' );
  };
  var Vector2 = dot.Vector2;

  Vector2.createPolar = function( magnitude, angle ) {
    return new Vector2( magnitude * Math.cos( angle ), magnitude * Math.sin( angle ) );
  };

  Vector2.prototype = {
    constructor: Vector2,

    isVector2: true,

    dimension: 2,

    magnitude: function() {
      return Math.sqrt( this.magnitudeSquared() );
    },

    magnitudeSquared: function() {
      return this.dot( this );
    },

    // the distance between this vector (treated as a point) and another point
    distance: function( point ) {
      return this.minus( point ).magnitude();
    },

    // the squared distance between this vector (treated as a point) and another point
    distanceSquared: function( point ) {
      return this.minus( point ).magnitudeSquared();
    },

    dot: function( v ) {
      return this.x * v.x + this.y * v.y;
    },

    equals: function( other ) {
      return this.x === other.x && this.y === other.y;
    },

    equalsEpsilon: function( other, epsilon ) {
      if ( !epsilon ) {
        epsilon = 0;
      }
      return Math.max( Math.abs( this.x - other.x ), Math.abs( this.y - other.y ) ) <= epsilon;
    },

    isFinite: function() {
      return isFinite( this.x ) && isFinite( this.y );
    },

    /*---------------------------------------------------------------------------*
     * Immutables
     *----------------------------------------------------------------------------*/

    copy: function() {
      return new this.constructor( this.x, this.y );
    },

    // z component of the equivalent 3-dimensional cross product (this.x, this.y,0) x (v.x, v.y, 0)
    crossScalar: function( v ) {
      return this.x * v.y  - this.y * v.x;
    },

    normalized: function() {
      var mag = this.magnitude();
      if ( mag === 0 ) {
        throw new Error( "Cannot normalize a zero-magnitude vector" );
      }
      else {
        return new this.constructor( this.x / mag, this.y / mag );
      }
    },

    timesScalar: function( scalar ) {
      return new this.constructor( this.x * scalar, this.y * scalar );
    },

    times: function( scalar ) {
      // make sure it's not a vector!
      assert && assert( scalar.dimension === undefined );
      return this.timesScalar( scalar );
    },

    componentTimes: function( v ) {
      return new this.constructor( this.x * v.x, this.y * v.y );
    },

    plus: function( v ) {
      return new this.constructor( this.x + v.x, this.y + v.y );
    },

    plusScalar: function( scalar ) {
      return new this.constructor( this.x + scalar, this.y + scalar );
    },

    minus: function( v ) {
      return new this.constructor( this.x - v.x, this.y - v.y );
    },

    minusScalar: function( scalar ) {
      return new this.constructor( this.x - scalar, this.y - scalar );
    },

    dividedScalar: function( scalar ) {
      return new this.constructor( this.x / scalar, this.y / scalar );
    },

    negated: function() {
      return new this.constructor( -this.x, -this.y );
    },

    angle: function() {
      return Math.atan2( this.y, this.x );
    },

    // equivalent to a -PI/2 rotation (right hand rotation)
    perpendicular: function() {
      return new this.constructor( this.y, -this.x );
    },

    angleBetween: function( v ) {
      return Math.acos( dot.clamp( this.normalized().dot( v.normalized() ), -1, 1 ) );
    },

    rotated: function( angle ) {
      var newAngle = this.angle() + angle;
      return new this.constructor( Math.cos( newAngle ), Math.sin( newAngle ) ).timesScalar( this.getMagnitude() );
    },

    // linear interpolation from this (ratio=0) to vector (ratio=1)
    blend: function( vector, ratio ) {
      return this.plus( vector.minus( this ).times( ratio ) );
    },

    toString: function() {
      return "Vector2(" + this.x + ", " + this.y + ")";
    },

    toVector3: function() {
      return new dot.Vector3( this.x, this.y );
    },

    /*---------------------------------------------------------------------------*
     * Mutables
     *----------------------------------------------------------------------------*/

    set: function( x, y ) {
      this.x = x;
      this.y = y;
      return this;
    },

    setX: function( x ) {
      this.x = x;
      return this;
    },

    setY: function( y ) {
      this.y = y;
      return this;
    },

    add: function( v ) {
      this.x += v.x;
      this.y += v.y;
      return this;
    },

    addScalar: function( scalar ) {
      this.x += scalar;
      this.y += scalar;
      return this;
    },

    subtract: function( v ) {
      this.x -= v.x;
      this.y -= v.y;
      return this;
    },

    subtractScalar: function( scalar ) {
      this.x -= scalar;
      this.y -= scalar;
      return this;
    },

    componentMultiply: function( v ) {
      this.x *= v.x;
      this.y *= v.y;
      return this;
    },

    divideScalar: function( scalar ) {
      this.x /= scalar;
      this.y /= scalar;
      return this;
    },

    negate: function() {
      this.x = -this.x;
      this.y = -this.y;
      return this;
    }

  };

  /*---------------------------------------------------------------------------*
   * Immutable Vector form
   *----------------------------------------------------------------------------*/
  Vector2.Immutable = function ImmutableVector2( x, y ) {
    Vector2.call( this, x, y );
  };
  var Immutable = Vector2.Immutable;

  inherit( Immutable, Vector2 );

  // throw errors whenever a mutable method is called on our immutable vector
  Immutable.mutableOverrideHelper = function( mutableFunctionName ) {
    Immutable.prototype[mutableFunctionName] = function() {
      throw new Error( "Cannot call mutable method '" + mutableFunctionName + "' on immutable Vector2" );
    };
  };

  // TODO: better way to handle this list?
  Immutable.mutableOverrideHelper( 'set' );
  Immutable.mutableOverrideHelper( 'setX' );
  Immutable.mutableOverrideHelper( 'setY' );
  Immutable.mutableOverrideHelper( 'copy' );
  Immutable.mutableOverrideHelper( 'add' );
  Immutable.mutableOverrideHelper( 'addScalar' );
  Immutable.mutableOverrideHelper( 'subtract' );
  Immutable.mutableOverrideHelper( 'subtractScalar' );
  Immutable.mutableOverrideHelper( 'componentMultiply' );
  Immutable.mutableOverrideHelper( 'divideScalar' );
  Immutable.mutableOverrideHelper( 'negate' );

  // helpful immutable constants
  Vector2.ZERO = new Immutable( 0, 0 );
  Vector2.X_UNIT = new Immutable( 1, 0 );
  Vector2.Y_UNIT = new Immutable( 0, 1 );

  return Vector2;
} );
<|endoftext|>


<commit_before>'use strict';
var Rect = require('./helpers/rect').Rect;
var Utils = require('./helpers/utils');
var renderer = require('./renderer.base');
var Tayberry = require('./base.js').Tayberry;

class BarRenderer extends renderer.Renderer {
    drawPlot() {
        this.ctx.save();
        let barEnumerator = new BarEnumerator(this);
        let bar;
        while ((bar = barEnumerator.next())) {
            this.ctx.fillStyle = bar.selected ? bar.renderedSeries.highlightColour : bar.renderedSeries.colour;
            this.ctx.fillRect(bar.rect.left, bar.rect.top, bar.rect.width, bar.rect.height);
        }
        this.ctx.restore();
    }

    drawLabels() {
        if (this.tb.options.labels.enabled) {
            this.ctx.save();
            let barEnumerator = new BarEnumerator(this);
            let bar;
            while ((bar = barEnumerator.next())) {
                this.ctx.font = this.tb.labelFont;
                this.ctx.fillStyle = this.tb.options.labels.font.colour;
                this.drawLabel(bar.value, this.tb.options.yAxis.labelFormatter(bar.value), bar.rect);
            }
            this.ctx.restore();
        }
    }

    hitTest(x, y) {
        // TODO: Optimise
        let ret = {
            found: false,
            plotType: 'bar',
            isXRange: true
        };

        const categoryCount = this.renderedSeries[0].data.length;
        const isHorizontal = this.tb.options.swapAxes;
        let plotArea = this.tb.plotArea.clone();
        if (isHorizontal)
            plotArea.swapXY();
        const categoryIndex = Math.floor(categoryCount * ((isHorizontal ? y : x) - plotArea.left) / plotArea.width);

        let matches = [];

        let barEnumerator = new BarEnumerator(this, categoryIndex);
        let bar;
        while ((bar = barEnumerator.next())) {
            if (bar.categoryIndex > categoryIndex)
                break;
            let distance, priority;
            if (bar.rect.containsPoint(x, y)) {
                distance = 0;
                priority = 0;
            }
            else if (bar.rect.containsX(x)) {
                distance = y < bar.rect.top ? bar.rect.top - y : y - bar.rect.bottom;
                priority = isHorizontal ? 2 : 1;
            }
            else if (bar.rect.containsY(y)) {
                distance = x < bar.rect.left ? bar.rect.left - x : x - bar.rect.right;
                priority = isHorizontal ? 1 : 2;
            }
            else {
                const xDist = Math.min(Math.abs(x - bar.rect.left), Math.abs(x - bar.rect.right));
                const yDist = Math.min(Math.abs(y - bar.rect.top), Math.abs(y - bar.rect.bottom));
                // distance = Math.sqrt(Math.pow(xDist, 2) + Math.pow(yDist, 2));
                distance = isHorizontal ? yDist : xDist;
                priority = 3;
            }

            matches.push({
                distance: distance,
                priority: priority,
                data: {
                    categoryIndex: bar.categoryIndex,
                    seriesIndex: bar.seriesIndex,
                    rect: bar.rect,
                    series: this.series[bar.seriesIndex],
                    value: Tayberry.getDataValue(this.series[bar.seriesIndex].data[bar.categoryIndex])
                }
            });
        }

        if (matches.length) {
            matches.sort((a, b) => {
                let ret = a.priority - b.priority;
                if (!ret) ret = a.distance - b.distance;
                if (!ret) ret = a.data.rect.height - b.data.rect.height;
                return ret;
            });
            ret.found = true;
            ret.normalisedDistance = matches[0].distance * matches[0].data.rect.area;
            ret = Utils.assign(ret, matches[0].data);
        }
        return ret;
    }
}

class BarEnumerator extends renderer.ByCategoryEnumerator {
    constructor(renderer, startCategoryIndex = 0) {
        super(renderer, startCategoryIndex);
        if (this.categoryCount) {
            this.isStacked = this.tb.options.barPlot.mode === 'stacked';
            this.isOverlaid = this.tb.options.barPlot.mode === 'overlaid';
            this.isNormal = !this.isStacked && !this.isOverlaid;
            this.barCount = (this.isStacked || this.isOverlaid) ? 1 : this.tb.seriesCount;
            this.categoryWidth = (this.plotArea.width / this.categoryCount);

            this.onNewCategory();
        }
    }

    onNewCategory() {
        this.yBottomPositive = this.yOrigin;
        this.yBottomNegative = this.yOrigin;
        this.yRunningTotalPositive = 0;
        this.yRunningTotalNegative = 0;
        this.barIndex = 0;
    }

    next() {
        let ret;

        if (this.categoryIndex < this.categoryCount) {
            const value = Tayberry.getDataValue(this.renderer.renderedSeries[this.seriesIndex].data[this.categoryIndex]);
            let categoryXStart = this.plotArea.left + Math.floor(this.categoryIndex * this.categoryWidth);
            let categoryXEnd = this.plotArea.left + Math.floor((this.categoryIndex + 1) * this.categoryWidth);
            let barXStart = categoryXStart + Math.ceil(this.categoryWidth * this.tb.options.barPlot.categorySpacing / 2);
            let barXEnd = categoryXEnd - Math.floor(this.categoryWidth * this.tb.options.barPlot.categorySpacing / 2);

            const barWidth = Math.floor((barXEnd - barXStart) / this.barCount);
            const xStart = Math.floor(barXStart + this.barIndex * barWidth);
            const xEnd = Math.ceil(barXStart + (this.barIndex + 1) * barWidth);

            const yTop = this.tb.yAxis.getValueDisplacement(value + (value > 0 ? this.yRunningTotalPositive : this.yRunningTotalNegative));
            let rect = new Rect(xStart, yTop, xEnd, value > 0 ? this.yBottomPositive : this.yBottomNegative);
            rect.left += Math.ceil(this.tb.xAxis.mapLogicalXOrYUnit(this.tb.options.barPlot.barPadding) / 2);
            rect.right -= Math.floor(this.tb.xAxis.mapLogicalXOrYUnit(this.tb.options.barPlot.barPadding) / 2);
            if (rect.right < rect.left)
                rect.right = rect.left;
            if (this.isHorizontal)
                rect.swapXY();
            rect.clip(this.tb.plotArea);

            ret = {
                seriesIndex: this.seriesIndex,
                categoryIndex: this.categoryIndex,
                series: this.renderer.series[this.seriesIndex],
                renderedSeries: this.renderer.renderedSeries[this.seriesIndex],
                value: Tayberry.getDataValue(this.renderer.series[this.seriesIndex].data[this.categoryIndex]),
                renderedValue: Tayberry.getDataValue(this.renderer.renderedSeries[this.seriesIndex].data[this.categoryIndex]),
                rect: rect,
                selected: this.tb.selectedItem.categoryIndex === this.categoryIndex && (this.tb.options.tooltips.shared || this.tb.selectedItem.series === this.renderer.series[this.seriesIndex])
            };

            if (this.isStacked) {
                if (value > 0) {
                    this.yRunningTotalPositive += value;
                    this.yBottomPositive = yTop;
                }
                else {
                    this.yRunningTotalNegative += value;
                    this.yBottomNegative = yTop;
                }
            } else if (this.isNormal) {
                this.barIndex++;
            }

            this.nextValue();

        }
        return ret;
    }
}

exports.BarRenderer = BarRenderer;<commit_msg>bar hit test fix<commit_after>'use strict';
var Rect = require('./helpers/rect').Rect;
var Utils = require('./helpers/utils');
var renderer = require('./renderer.base');
var Tayberry = require('./base.js').Tayberry;

class BarRenderer extends renderer.Renderer {
    drawPlot() {
        this.ctx.save();
        let barEnumerator = new BarEnumerator(this);
        let bar;
        while ((bar = barEnumerator.next())) {
            this.ctx.fillStyle = bar.selected ? bar.renderedSeries.highlightColour : bar.renderedSeries.colour;
            this.ctx.fillRect(bar.rect.left, bar.rect.top, bar.rect.width, bar.rect.height);
        }
        this.ctx.restore();
    }

    drawLabels() {
        if (this.tb.options.labels.enabled) {
            this.ctx.save();
            let barEnumerator = new BarEnumerator(this);
            let bar;
            while ((bar = barEnumerator.next())) {
                this.ctx.font = this.tb.labelFont;
                this.ctx.fillStyle = this.tb.options.labels.font.colour;
                this.drawLabel(bar.value, this.tb.options.yAxis.labelFormatter(bar.value), bar.rect);
            }
            this.ctx.restore();
        }
    }

    hitTest(x, y) {
        // TODO: Optimise
        let ret = {
            found: false,
            plotType: 'bar',
            isXRange: true
        };

        const categoryCount = this.renderedSeries[0].data.length;
        const isHorizontal = this.tb.options.swapAxes;
        let plotArea = this.tb.plotArea.clone();
        if (isHorizontal)
            plotArea.swapXY();
        const categoryIndex = Math.floor(categoryCount * ((isHorizontal ? y : x) - plotArea.left) / plotArea.width);

        let matches = [];

        let barEnumerator = new BarEnumerator(this, categoryIndex);
        let bar;
        while ((bar = barEnumerator.next())) {
            if (bar.categoryIndex > categoryIndex)
                break;
            let sortDistance, priority, realDistance;
            if (bar.rect.containsPoint(x, y)) {
                sortDistance = 0;
                priority = 0;
            }
            else if (bar.rect.containsX(x)) {
                sortDistance = y < bar.rect.top ? bar.rect.top - y : y - bar.rect.bottom;
                priority = isHorizontal ? 2 : 1;
            }
            else if (bar.rect.containsY(y)) {
                sortDistance = x < bar.rect.left ? bar.rect.left - x : x - bar.rect.right;
                priority = isHorizontal ? 1 : 2;
            }
            else {
                const xDist = Math.min(Math.abs(x - bar.rect.left), Math.abs(x - bar.rect.right));
                const yDist = Math.min(Math.abs(y - bar.rect.top), Math.abs(y - bar.rect.bottom));
                realDistance = Math.sqrt(Math.pow(xDist, 2) + Math.pow(yDist, 2));
                sortDistance = isHorizontal ? yDist : xDist;
                priority = 3;
            }

            if (typeof realDistance === 'undefined')
                realDistance = sortDistance;

            matches.push({
                sortDistance: sortDistance,
                distance: realDistance,
                priority: priority,
                data: {
                    categoryIndex: bar.categoryIndex,
                    seriesIndex: bar.seriesIndex,
                    rect: bar.rect,
                    series: this.series[bar.seriesIndex],
                    value: Tayberry.getDataValue(this.series[bar.seriesIndex].data[bar.categoryIndex])
                }
            });
        }

        if (matches.length) {
            matches.sort((a, b) => {
                let ret = a.priority - b.priority;
                if (!ret) ret = a.sortDistance - b.sortDistance;
                if (!ret) ret = a.data.rect.height - b.data.rect.height;
                return ret;
            });
            ret.found = true;
            ret.normalisedDistance = matches[0].distance * matches[0].data.rect.area;
            ret = Utils.assign(ret, matches[0].data);
        }
        return ret;
    }
}

class BarEnumerator extends renderer.ByCategoryEnumerator {
    constructor(renderer, startCategoryIndex = 0) {
        super(renderer, startCategoryIndex);
        if (this.categoryCount) {
            this.isStacked = this.tb.options.barPlot.mode === 'stacked';
            this.isOverlaid = this.tb.options.barPlot.mode === 'overlaid';
            this.isNormal = !this.isStacked && !this.isOverlaid;
            this.barCount = (this.isStacked || this.isOverlaid) ? 1 : this.tb.seriesCount;
            this.categoryWidth = (this.plotArea.width / this.categoryCount);

            this.onNewCategory();
        }
    }

    onNewCategory() {
        this.yBottomPositive = this.yOrigin;
        this.yBottomNegative = this.yOrigin;
        this.yRunningTotalPositive = 0;
        this.yRunningTotalNegative = 0;
        this.barIndex = 0;
    }

    next() {
        let ret;

        if (this.categoryIndex < this.categoryCount) {
            const value = Tayberry.getDataValue(this.renderer.renderedSeries[this.seriesIndex].data[this.categoryIndex]);
            let categoryXStart = this.plotArea.left + Math.floor(this.categoryIndex * this.categoryWidth);
            let categoryXEnd = this.plotArea.left + Math.floor((this.categoryIndex + 1) * this.categoryWidth);
            let barXStart = categoryXStart + Math.ceil(this.categoryWidth * this.tb.options.barPlot.categorySpacing / 2);
            let barXEnd = categoryXEnd - Math.floor(this.categoryWidth * this.tb.options.barPlot.categorySpacing / 2);

            const barWidth = Math.floor((barXEnd - barXStart) / this.barCount);
            const xStart = Math.floor(barXStart + this.barIndex * barWidth);
            const xEnd = Math.ceil(barXStart + (this.barIndex + 1) * barWidth);

            const yTop = this.tb.yAxis.getValueDisplacement(value + (value > 0 ? this.yRunningTotalPositive : this.yRunningTotalNegative));
            let rect = new Rect(xStart, yTop, xEnd, value > 0 ? this.yBottomPositive : this.yBottomNegative);
            rect.left += Math.ceil(this.tb.xAxis.mapLogicalXOrYUnit(this.tb.options.barPlot.barPadding) / 2);
            rect.right -= Math.floor(this.tb.xAxis.mapLogicalXOrYUnit(this.tb.options.barPlot.barPadding) / 2);
            if (rect.right < rect.left)
                rect.right = rect.left;
            if (this.isHorizontal)
                rect.swapXY();
            rect.clip(this.tb.plotArea);

            ret = {
                seriesIndex: this.seriesIndex,
                categoryIndex: this.categoryIndex,
                series: this.renderer.series[this.seriesIndex],
                renderedSeries: this.renderer.renderedSeries[this.seriesIndex],
                value: Tayberry.getDataValue(this.renderer.series[this.seriesIndex].data[this.categoryIndex]),
                renderedValue: Tayberry.getDataValue(this.renderer.renderedSeries[this.seriesIndex].data[this.categoryIndex]),
                rect: rect,
                selected: this.tb.selectedItem.categoryIndex === this.categoryIndex && (this.tb.options.tooltips.shared || this.tb.selectedItem.series === this.renderer.series[this.seriesIndex])
            };

            if (this.isStacked) {
                if (value > 0) {
                    this.yRunningTotalPositive += value;
                    this.yBottomPositive = yTop;
                }
                else {
                    this.yRunningTotalNegative += value;
                    this.yBottomNegative = yTop;
                }
            } else if (this.isNormal) {
                this.barIndex++;
            }

            this.nextValue();

        }
        return ret;
    }
}

exports.BarRenderer = BarRenderer;<|endoftext|>


<commit_before><commit_msg>Update VideoPlayer bar<commit_after><|endoftext|>


<commit_before>import { Observable } from 'rxjs/Observable'

const passThrough = v => v

// type signature as per https://fetch.spec.whatwg.org/#fetch-method
export function fetchObservable(input, init, modifier = passThrough) {
  const result = fetch(input, init)
  const modifiedResult = result.then(modifier)
  return Observable.from(modifiedResult)
}

export function fetchJsonObservable(input, init) {
  const parseJson = response => response.json()
  return fetchObservable(input, init, parseJson)
}

export default {
  fetchObservable,
  fetchJsonObservable
}
<commit_msg>Remove unused Rx helper module<commit_after><|endoftext|>


<commit_before>
import _ from 'lodash';
import express from 'express';
import WebSocket from 'ws';
import bodyParser from 'body-parser';
import superagent from 'superagent';
import mongodb from 'mongodb';
import core from './forest-core';
import auth from './auth';

let serverHost=null;
let serverPort=0;

// --------------------------------

const logRequest = (req, res, next) => {
  console.log('---------------------------->');
  if(req.method==='POST') console.log(req.method, req.originalUrl, req.body && req.body.UID, req.headers.authorization||'');
  else                    console.log(req.method, req.originalUrl,                           req.headers.authorization||'');
  next();
};

const logResponse = (req, res, next) => {
  console.log(res.statusCode)
  console.log('<----------------------------');
  next();
};

const CORS = (req, res, next) => {
  res.header('Access-Control-Allow-Origin','*');
  res.header('Access-Control-Allow-Methods', 'GET,POST,OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Content-Type, X-Requested-With, Authorization'); // Accept, X-Requested-By, Origin, Cache-Control
  next();
};

const app = express();

app.use(bodyParser.json());

app.options("/*",
  logRequest,
  CORS,
  (req, res, next) => {
    res.sendStatus(200);
  },
  logResponse,
);

function prefixUIDs(o){
  const s = JSON.stringify(_.omit(o, core.localProps), null, 2);
  return s.replace(/"(uid-[^"]*"[^:])/g, `"http://${serverHost}:${serverPort}/$1`)
}

app.get('/*',
  logRequest,
  CORS,
  (req, res, next) => {
    const { Peer, User } = auth.getPeerUser(req);
    const uid = req.originalUrl.substring(1);
    if(!User){
      console.log('implement temporary no-User user');
      res.status(404).send('Not found');
      next();
      return;
    }
    core.runEvaluator(User, { method: 'GET', URL: uid, Peer })
      .then(user => {
        const ok = user && user.PK!==false && (!user.PK || auth.checkSig(user.PK));
        if(user) delete user.PK;
        if(!ok){
          return res.status(404).send('Not found');
        }
        return core.getObject(uid).then(o => {
          res.json(JSON.parse(prefixUIDs(o)));
          if(Peer) core.setNotify(o,Peer);
        });
      })
      .then(()=>next())
      .catch(e => {
        console.error(e);
        res.status(404).send('Not found');
        next();
      });
  },
  logResponse,
);

const peer2ws = {};

app.post('/*',
  logRequest,
  CORS,
  (req, res, next) => {
    const json=req.body;
    if(!json || !json.UID) next();
    const { Peer, User } = auth.getPeerUser(req);
    const path = req.originalUrl.substring(1);
    core.incomingObject(Object.assign(json, Peer && { Peer }), path!=='notify' && path)
    res.json({ });
    next();
  },
  logResponse,
);

function doGet(url){
  return superagent.get(url)
    .timeout({ response: 9000, deadline: 10000 })
    .set(auth.makeHTTPAuth())
    .then(x => x.body);
}

const pendingWSpackets = {};

function doPost(o, u){
  if(core.isURL(u)) return Promise.resolve(false);
  const Peer = core.isNotify(u)? u: o.Peer;
  if(!pendingWSpackets[Peer]) pendingWSpackets[Peer] = [];
  pendingWSpackets[Peer].push(prefixUIDs(o));
  wsFlush(Peer);
  return Promise.resolve(true);
}

function wsInit(config){
  const wss = new WebSocket.Server(config);
  wss.on('connection', (ws) => {
    ws.on('message', (data) => {
      const json = JSON.parse(data);
      if(json.Peer){
        console.log('ws init:', json);
        peer2ws[json.Peer]=ws;
        ws.send(auth.makeWSAuth());
        wsFlush(json.Peer);
      }
      else{
        console.log('ws incoming json:', json);
      }
    });
  });
}

function wsFlush(Peer){
  const ws = peer2ws[Peer];
  if(!ws){
    console.log('websocket not found', Peer);
    return;
  }
  let packet;
  while((packet=(pendingWSpackets[Peer]||[]).shift())){
    try{
      console.log('<<----------ws---------------', Peer);
      if(ws.readyState === ws.OPEN) ws.send(packet);
      else console.log('WebSocket closed sending\n', packet, '\nto', Peer)
    }
    catch(e){
      console.error('error sending\n', packet, '\nto', Peer, '\n', e)
    }
  }
}

core.setNetwork({ doGet, doPost });

// --------------------------------

let forestdb;

function persistenceInit(mongoHostPort){
  return mongodb.MongoClient.connect(mongoHostPort)
    .then((client) => {
      forestdb = client.db('forest');
    });
}

function persist(o){
  if(!o.is) return Promise.resolve();
  const collectionName = (o.is.constructor===String)? o.is:
                        ((o.is.constructor===Array)? o.is.join('-'): null);
  if(!collectionName) return Promise.resolve();
  return forestdb.collection(collectionName)
    .update({ UID: o.UID }, o, { upsert: true })
    .then(result => result.result)
    .catch(err => { console.log(err, `Failed to insert ${o.UID} in ${collectionName}`); return err });
}

function fetch(uid){
  return forestdb.collections().then(colls=>findOneFirst(colls, uid))
}

function findOneFirst(colls, uid){
  if(!(colls && colls.length)) return Promise.resolve(null);
  return colls[0].findOne({ UID: uid }, { projection: { _id: 0 }}).then(o => o || findOneFirst(colls.slice(1), uid));
}

function recache(){
  return forestdb.collections()
    .then(colls=>Promise.all(colls.map(coll=>coll.find({ Cache: 'keep-active' }, { projection: { _id: 0 }}).toArray()))
                  .then(actives => [].concat(...actives)))
}

function query(is, scope, query){
  return forestdb.collection(is.join('-'))
    .find(toMongo(scope, query.match), { projection: { _id: 0 }})
    .toArray()
    .then(r => r.map(o => query.inline? getInlineVals(o, query.inline): o.UID))
    .catch(e => console.error(e));
}

function toMongo(scope, match){
  return Object.assign({}, ...Object.keys(match).map(k => ({[k]: toMongoProp(k,match[k])})));
}

function toMongoProp(key, val){
  if(val.length===3 && val[1]==='..'){
    return { $gt: val[0], $lt: val[2] };
  }
  return val;
}

function getInlineVals(o, inline){
  return Object.assign({}, ...inline.map(k => o[k] && { [k]: o[k] }), { More: o.UID })
}

core.setPersistence({ persist, fetch, recache, query });

// --------------------------------

function init({httpHost, httpPort, wsPort, mongoHostPort}){
  serverHost=httpHost; serverPort=httpPort;
  return new Promise((resolve, reject) => {
    persistenceInit(mongoHostPort)
      .then(() => {
        app.listen(httpPort, ()=>{
          console.log(`Server started on port ${httpPort}`);
          wsInit({ port: wsPort });
          resolve();
        }).on('error', (err) => reject(err));
      })
      .catch((err) => reject(err));
  });
}

export default {
  init,
  cacheObjects:        core.cacheObjects,
  reCacheObjects:      core.reCacheObjects,
  setEvaluator:        core.setEvaluator,
  getObject:           core.getObject,
  spawnObject:         core.spawnObject,
  makeUID:             core.makeUID,
  setLogging:          core.setLogging,
  setPeerIdentityUser: auth.setPeerIdentityUser,
}

<commit_msg>do User check on POST too<commit_after>
import _ from 'lodash';
import express from 'express';
import WebSocket from 'ws';
import bodyParser from 'body-parser';
import superagent from 'superagent';
import mongodb from 'mongodb';
import core from './forest-core';
import auth from './auth';

let serverHost=null;
let serverPort=0;

// --------------------------------

const logRequest = (req, res, next) => {
  console.log('---------------------------->');
  if(req.method==='POST') console.log(req.method, req.originalUrl, req.body && req.body.UID, req.headers.authorization||'');
  else                    console.log(req.method, req.originalUrl,                           req.headers.authorization||'');
  next();
};

const logResponse = (req, res, next) => {
  console.log(res.statusCode)
  console.log('<----------------------------');
  next();
};

const CORS = (req, res, next) => {
  res.header('Access-Control-Allow-Origin','*');
  res.header('Access-Control-Allow-Methods', 'GET,POST,OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Content-Type, X-Requested-With, Authorization'); // Accept, X-Requested-By, Origin, Cache-Control
  next();
};

const app = express();

app.use(bodyParser.json());

app.options("/*",
  logRequest,
  CORS,
  (req, res, next) => {
    res.sendStatus(200);
  },
  logResponse,
);

function prefixUIDs(o){
  const s = JSON.stringify(_.omit(o, core.localProps), null, 2);
  return s.replace(/"(uid-[^"]*"[^:])/g, `"http://${serverHost}:${serverPort}/$1`)
}

app.get('/*',
  logRequest,
  CORS,
  (req, res, next) => {
    const { Peer, User } = auth.getPeerUser(req);
    const uid = req.originalUrl.substring(1);
    if(!User){
      console.log('implement temporary no-User user');
      res.status(404).send('Not found');
      next();
      return;
    }
    core.runEvaluator(User, { method: 'GET', URL: uid, Peer })
      .then(user => {
        const ok = user && user.PK!==false && (!user.PK || auth.checkSig(user.PK));
        if(user) delete user.PK;
        if(!ok){
          return res.status(404).send('Not found');
        }
        return core.getObject(uid).then(o => {
          res.json(JSON.parse(prefixUIDs(o)));
          if(Peer) core.setNotify(o,Peer);
        });
      })
      .then(()=>next())
      .catch(e => {
        console.error(e);
        res.status(404).send('Not found');
        next();
      });
  },
  logResponse,
);

const peer2ws = {};

app.post('/*',
  logRequest,
  CORS,
  (req, res, next) => {
    const json=req.body;
    if(!json || !json.UID) next();
    const { Peer, User } = auth.getPeerUser(req);
    const path = req.originalUrl.substring(1);
    if(!User){
      console.log('implement temporary no-User user');
      res.status(403).send('Forbidden');
      next();
      return;
    }
    core.runEvaluator(User, { method: 'POST', URL: json.UID, Peer })
      .then(user => {
        const ok = user && user.PK!==false && (!user.PK || auth.checkSig(user.PK));
        if(user) delete user.PK;
        if(!ok){
          return res.status(403).send('Forbidden');
        }
        core.incomingObject(Object.assign({ User }, Peer && { Peer }, json), path!=='notify' && path)
        res.json({ });
      })
      .then(()=>next())
      .catch(e => {
        console.error(e);
        res.status(403).send('Forbidden');
        next();
      });
  },
  logResponse,
);

function doGet(url){
  return superagent.get(url)
    .timeout({ response: 9000, deadline: 10000 })
    .set(auth.makeHTTPAuth())
    .then(x => x.body);
}

const pendingWSpackets = {};

function doPost(o, u){
  if(core.isURL(u)) return Promise.resolve(false);
  const Peer = core.isNotify(u)? u: o.Peer;
  if(!pendingWSpackets[Peer]) pendingWSpackets[Peer] = [];
  pendingWSpackets[Peer].push(prefixUIDs(o));
  wsFlush(Peer);
  return Promise.resolve(true);
}

function wsInit(config){
  const wss = new WebSocket.Server(config);
  wss.on('connection', (ws) => {
    ws.on('message', (data) => {
      const json = JSON.parse(data);
      if(json.Peer){
        console.log('ws init:', json);
        peer2ws[json.Peer]=ws;
        ws.send(auth.makeWSAuth());
        wsFlush(json.Peer);
      }
      else{
        console.log('ws incoming json:', json);
      }
    });
  });
}

function wsFlush(Peer){
  const ws = peer2ws[Peer];
  if(!ws){
    console.log('websocket not found', Peer);
    return;
  }
  let packet;
  while((packet=(pendingWSpackets[Peer]||[]).shift())){
    try{
      console.log('<<----------ws---------------', Peer);
      if(ws.readyState === ws.OPEN) ws.send(packet);
      else console.log('WebSocket closed sending\n', packet, '\nto', Peer)
    }
    catch(e){
      console.error('error sending\n', packet, '\nto', Peer, '\n', e)
    }
  }
}

core.setNetwork({ doGet, doPost });

// --------------------------------

let forestdb;

function persistenceInit(mongoHostPort){
  return mongodb.MongoClient.connect(mongoHostPort)
    .then((client) => {
      forestdb = client.db('forest');
    });
}

function persist(o){
  if(!o.is) return Promise.resolve();
  const collectionName = (o.is.constructor===String)? o.is:
                        ((o.is.constructor===Array)? o.is.join('-'): null);
  if(!collectionName) return Promise.resolve();
  return forestdb.collection(collectionName)
    .update({ UID: o.UID }, o, { upsert: true })
    .then(result => result.result)
    .catch(err => { console.log(err, `Failed to insert ${o.UID} in ${collectionName}`); return err });
}

function fetch(uid){
  return forestdb.collections().then(colls=>findOneFirst(colls, uid))
}

function findOneFirst(colls, uid){
  if(!(colls && colls.length)) return Promise.resolve(null);
  return colls[0].findOne({ UID: uid }, { projection: { _id: 0 }}).then(o => o || findOneFirst(colls.slice(1), uid));
}

function recache(){
  return forestdb.collections()
    .then(colls=>Promise.all(colls.map(coll=>coll.find({ Cache: 'keep-active' }, { projection: { _id: 0 }}).toArray()))
                  .then(actives => [].concat(...actives)))
}

function query(is, scope, query){
  return forestdb.collection(is.join('-'))
    .find(toMongo(scope, query.match), { projection: { _id: 0 }})
    .toArray()
    .then(r => r.map(o => query.inline? getInlineVals(o, query.inline): o.UID))
    .catch(e => console.error(e));
}

function toMongo(scope, match){
  return Object.assign({}, ...Object.keys(match).map(k => ({[k]: toMongoProp(k,match[k])})));
}

function toMongoProp(key, val){
  if(val.length===3 && val[1]==='..'){
    return { $gt: val[0], $lt: val[2] };
  }
  return val;
}

function getInlineVals(o, inline){
  return Object.assign({}, ...inline.map(k => o[k] && { [k]: o[k] }), { More: o.UID })
}

core.setPersistence({ persist, fetch, recache, query });

// --------------------------------

function init({httpHost, httpPort, wsPort, mongoHostPort}){
  serverHost=httpHost; serverPort=httpPort;
  return new Promise((resolve, reject) => {
    persistenceInit(mongoHostPort)
      .then(() => {
        app.listen(httpPort, ()=>{
          console.log(`Server started on port ${httpPort}`);
          wsInit({ port: wsPort });
          resolve();
        }).on('error', (err) => reject(err));
      })
      .catch((err) => reject(err));
  });
}

export default {
  init,
  cacheObjects:        core.cacheObjects,
  reCacheObjects:      core.reCacheObjects,
  setEvaluator:        core.setEvaluator,
  getObject:           core.getObject,
  spawnObject:         core.spawnObject,
  makeUID:             core.makeUID,
  setLogging:          core.setLogging,
  setPeerIdentityUser: auth.setPeerIdentityUser,
}

<|endoftext|>


<commit_before>var app = angular.module("app", []);

app.controller("AppCtrl", function($scope,$http) {
  // this.things = ["Title",
  // 				 "BRA Project Type",
  // 				 "BRA Article80 Type",
  // 				 "BRA Project Neighborhood",
  // 				 "BRA Project Status",
  // 				 "BRA Project Status Css Class",
  // 				 "BRA Project Status Number",
  // 				 "BRA Project Description",
  // 				 "BRA Project Street Num",
  // 				 "BRA Project Street Name",
  // 				 "BRA Project Zip Code",
  // 				 "BRA Land Sq Ft",
  // 				 "BRA Bldg Sq Ft",
  // 				 "BRA Res Units",
  // 				 "BRA Parcel ID",
  // 				 "BRA Is Publish",
  // 				 "BRA Last Updated Date",
  // 				 "BRA Board Approval Date",
  // 				 "BRA Contact Name",
  // 				 "BRA Contact Email",
  // 				 "BRA Contact Phone",
  // 				 "BRA Neighborhood ID",
  // 				 "BRA Latitude",
  // 				 "BRA Longitude"];

  	$scope.projects =
  			{attribute: [
              "BRA ProjectID",
              "Document name",
              'Title',
              'BRA Latitude',
              'BRA Longitude',
        			'BRA Project Type',
        			'BRA Article80 Type',
        			'BRA Project Neighborhood',
        			'BRA Project Status',
        			'BRA Project Status Css Class',
        			'BRA Project Status Number',
              'BRA Project Description',
           		'BRA Project Street Num',
        			'BRA Project Street Name',
        			'BRA Project Zip Code',
       				'BRA Land Sq Ft',
      				'BRA Bldg Sq Ft',
        			'BRA Res Units',
        			'BRA Parcel ID',
        			'BRA Is Publish',
        			'BRA Last Updated Date',
        			'BRA Board Approval Date',
        			'BRA Contact Name',
        			'BRA Contact Email',
        			'BRA Contact Phone',
        			'BRA Neighborhood ID'],
        	value: ['',
        			'',
        			'',
        			'',
        			'',
        			'',
        			'',
              '',
           		'',
        			'',
        			'',
       				'',
      				'',
        			'',
        			'',
        			'',
        			'',
        			'',
        			'',
        			'',
        			'',
        			'',
        			'',
        			'']
        	};

  	$scope.clickSumbit = function(){
  		console.log($scope.projects.value);

      // var URL = "http://staging.bostonredevelopmentauthority.org/rest/content/currentsite/en-us/document/projects/Development-Projects/10-St-James-Avenue?format=json";

      // // $http.defaults.headers.common.Authorization = 'Basic Basic UmVzdEFQSTpCUkFCb3N0b242MTchIQ==';
      // $http.get(URL,{"DocumentContent":"123"},{
      //   headers: {'Authorization': 'Basic UmVzdEFQSTpCUkFCb3N0b242MTchIQ=='}
      // }).
      //     success(function(data, status, headers, config) {
      //       // this callback will be called asynchronously
      //       console.log(data);
      //       // when the response is available
      //     }).
      //     error(function(data, status, headers, config) {
      //       // called asynchronously if an error occurs
      //       // or server returns response with an error status.
      //     });

  var URL = "http://staging.bostonredevelopmentauthority.org/rest/content/currentsite/en-us/document/projects/Development-Projects/10-St-James-Avenue?format=json";

      var res = {
        url: URL,
        method: "PUT",
        headers: {
          'Authorization': 'Basic UmVzdEFQSTpCUkFCb3N0b242MTchIQ==',
          'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
        },
        data: {
      }
      };

      // $http.defaults.headers.common.Authorization = 'Basic Basic UmVzdEFQSTpCUkFCb3N0b242MTchIQ==';
      $http(res).
          success(function(data, status, headers, config) {
            // this callback will be called asynchronously
            console.log(data);
            // when the response is available
          }).
          error(function(data, status, headers, config) {
            // called asynchronously if an error occurs
            // or server returns response with an error status.
          });
  	};

});

app.controller("MapCtrl", function($scope) {
  require(["application/bootstrapmap",
        "esri/tasks/GeometryService",
        "esri/toolbars/edit",

        "esri/tasks/IdentifyTask",
        "esri/tasks/IdentifyParameters",

        "esri/layers/ArcGISTiledMapServiceLayer",
        "esri/layers/FeatureLayer",

        "esri/Color",
        "esri/symbols/SimpleMarkerSymbol",
        "esri/symbols/SimpleLineSymbol",

        "esri/dijit/editing/Editor",
        "esri/dijit/editing/TemplatePicker",

        "esri/config",
        "dojo/i18n!esri/nls/jsapi",

        "dojo/_base/array", "dojo/parser", "dojo/keys",

        "dijit/layout/BorderContainer", "dijit/layout/ContentPane",
        "dojo/domReady!"],
        function(BootstrapMap, GeometryService, Edit,
        IdentifyTask, IdentifyParameters,
        ArcGISTiledMapServiceLayer, FeatureLayer,
        Color, SimpleMarkerSymbol, SimpleLineSymbol,
        Editor, TemplatePicker,
        esriConfig, jsapiBundle,
        arrayUtils, parser, keys) {
          // Get a reference to the ArcGIS Map class
          $scope.map = BootstrapMap.create("mapDiv",{
            basemap:"gray",
            center:[-71.059, 42.36],
            zoom:14,
            scrollWheelZoom: false
          });

          $scope.map.on("layers-add-result", initEditor);

          esriConfig.defaults.geometryService = new GeometryService("http://tasks.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer");

            var parcel = new FeatureLayer("http://mapservices.bostonredevelopmentauthority.org/arcgis/rest/services/Test/Article80_test/FeatureServer/0",{
              mode: FeatureLayer.MODE_ONDEMAND,
              outFields: ['*'],
              opacity: 0.8
            });

            $scope.map.addLayers([parcel]);

            function initEditor(evt) {
          var templateLayers = arrayUtils.map(evt.layers, function(result){
            return result.layer;
          });
          var templatePicker = new TemplatePicker({
            featureLayers: templateLayers,
            grouping: true,
            rows: "auto",
            columns: 3
          }, "templateDiv");
          templatePicker.startup();

          var layers = arrayUtils.map(evt.layers, function(result) {
            return { featureLayer: result.layer };
          });
          var settings = {
            map: $scope.map,
            templatePicker: templatePicker,
            layerInfos: layers,
            toolbarVisible: true,
            createOptions: {
              polylineDrawTools:[ Editor.CREATE_TOOL_FREEHAND_POLYLINE ],
              polygonDrawTools: [ Editor.CREATE_TOOL_FREEHAND_POLYGON,
                Editor.CREATE_TOOL_CIRCLE,
                Editor.CREATE_TOOL_TRIANGLE,
                Editor.CREATE_TOOL_RECTANGLE
              ]
            },
            toolbarOptions: {
              reshapeVisible: true,
              mergeVisible: true,
              cutVisible: true
            }
          };

          var params = {settings: settings};
          var myEditor = new Editor(params,'editorDiv');
          //define snapping options
          var symbol = new SimpleMarkerSymbol(
            SimpleMarkerSymbol.STYLE_CROSS,
            15,
            new SimpleLineSymbol(
              SimpleLineSymbol.STYLE_SOLID,
              new Color([255, 0, 0, 0.5]),
              5
            ),
            null
          );
          $scope.map.enableSnapping({
            snapPointSymbol: symbol,
            tolerance: 20,
            snapKey: keys.ALT
          });

          myEditor.startup();

          $scope.map.on("click",function(e){
            // console.log(e);

            var identifyTask = new IdentifyTask("http://mapservices.bostonredevelopmentauthority.org/arcgis/rest/services/Test/Article80_test/MapServer");
            identifyParams = new IdentifyParameters();
            identifyParams.tolerance = 6;
            identifyParams.returnGeometry = true;
            identifyParams.layerIds = [0];
            identifyParams.layerOption = IdentifyParameters.LAYER_OPTION_ALL;
            identifyParams.width = $scope.map.width;
            identifyParams.height = $scope.map.height;
            identifyParams.geometry = e.mapPoint;
            identifyParams.mapExtent = $scope.map.extent;
            identifyTask.execute(identifyParams, function (idResults) {
                // handleIdResultAddress(idResults, e);
                console.log(idResults);
                $scope.projects.value[3] = idResults[0].feature.attributes.X;
                $scope.projects.value[4] = idResults[0].feature.attributes.Y;
                $scope.$apply();
            });

            // console.log($scope.projects);
          });
        }

      });

});<commit_msg>figured out 403 error<commit_after>var app = angular.module("app", []);

app.controller("AppCtrl", function($scope,$http) {
  // this.things = ["Title",
  // 				 "BRA Project Type",
  // 				 "BRA Article80 Type",
  // 				 "BRA Project Neighborhood",
  // 				 "BRA Project Status",
  // 				 "BRA Project Status Css Class",
  // 				 "BRA Project Status Number",
  // 				 "BRA Project Description",
  // 				 "BRA Project Street Num",
  // 				 "BRA Project Street Name",
  // 				 "BRA Project Zip Code",
  // 				 "BRA Land Sq Ft",
  // 				 "BRA Bldg Sq Ft",
  // 				 "BRA Res Units",
  // 				 "BRA Parcel ID",
  // 				 "BRA Is Publish",
  // 				 "BRA Last Updated Date",
  // 				 "BRA Board Approval Date",
  // 				 "BRA Contact Name",
  // 				 "BRA Contact Email",
  // 				 "BRA Contact Phone",
  // 				 "BRA Neighborhood ID",
  // 				 "BRA Latitude",
  // 				 "BRA Longitude"];

  	$scope.projects =
  			{attribute: [
              "BRA ProjectID",
              "Document name",
              'Title',
              'BRA Latitude',
              'BRA Longitude',
        			'BRA Project Type',
        			'BRA Article80 Type',
        			'BRA Project Neighborhood',
        			'BRA Project Status',
        			'BRA Project Status Css Class',
        			'BRA Project Status Number',
              'BRA Project Description',
           		'BRA Project Street Num',
        			'BRA Project Street Name',
        			'BRA Project Zip Code',
       				'BRA Land Sq Ft',
      				'BRA Bldg Sq Ft',
        			'BRA Res Units',
        			'BRA Parcel ID',
        			'BRA Is Publish',
        			'BRA Last Updated Date',
        			'BRA Board Approval Date',
        			'BRA Contact Name',
        			'BRA Contact Email',
        			'BRA Contact Phone',
        			'BRA Neighborhood ID'],
        	value: ['',
        			'',
        			'',
        			'',
        			'',
        			'',
        			'',
              '',
           		'',
        			'',
        			'',
       				'',
      				'',
        			'',
        			'',
        			'',
        			'',
        			'',
        			'',
        			'',
        			'',
        			'',
        			'',
        			'']
        	};

  	$scope.clickSumbit = function(){
  		console.log($scope.projects.value);

      // var URL = "http://staging.bostonredevelopmentauthority.org/rest/content/currentsite/en-us/document/projects/Development-Projects/10-St-James-Avenue?format=json";

      // // $http.defaults.headers.common.Authorization = 'Basic Basic UmVzdEFQSTpCUkFCb3N0b242MTchIQ==';
      // $http.get(URL,{"DocumentContent":"123"},{
      //   headers: {'Authorization': 'Basic UmVzdEFQSTpCUkFCb3N0b242MTchIQ=='}
      // }).
      //     success(function(data, status, headers, config) {
      //       // this callback will be called asynchronously
      //       console.log(data);
      //       // when the response is available
      //     }).
      //     error(function(data, status, headers, config) {
      //       // called asynchronously if an error occurs
      //       // or server returns response with an error status.
      //     });

  var URL = "http://staging.bostonredevelopmentauthority.org/rest/content/currentsite/en-us/document/projects/Development-Projects/10-St-James-Avenue?format=json";

      var res = {
        url: URL,
        method: "PUT",
        headers: {
          'Authorization': 'Basic amlhbi5mYW46eHVubHUxMTIxMTA=',
          'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
        },
        data: {
      }
      };

      // $http.defaults.headers.common.Authorization = 'Basic Basic UmVzdEFQSTpCUkFCb3N0b242MTchIQ==';
      $http(res).
          success(function(data, status, headers, config) {
            // this callback will be called asynchronously
            console.log(data);
            // when the response is available
          }).
          error(function(data, status, headers, config) {
            // called asynchronously if an error occurs
            // or server returns response with an error status.
          });
  	};

});

app.controller("MapCtrl", function($scope) {
  require(["application/bootstrapmap",
        "esri/tasks/GeometryService",
        "esri/toolbars/edit",

        "esri/tasks/IdentifyTask",
        "esri/tasks/IdentifyParameters",

        "esri/layers/ArcGISTiledMapServiceLayer",
        "esri/layers/FeatureLayer",

        "esri/Color",
        "esri/symbols/SimpleMarkerSymbol",
        "esri/symbols/SimpleLineSymbol",

        "esri/dijit/editing/Editor",
        "esri/dijit/editing/TemplatePicker",

        "esri/config",
        "dojo/i18n!esri/nls/jsapi",

        "dojo/_base/array", "dojo/parser", "dojo/keys",

        "dijit/layout/BorderContainer", "dijit/layout/ContentPane",
        "dojo/domReady!"],
        function(BootstrapMap, GeometryService, Edit,
        IdentifyTask, IdentifyParameters,
        ArcGISTiledMapServiceLayer, FeatureLayer,
        Color, SimpleMarkerSymbol, SimpleLineSymbol,
        Editor, TemplatePicker,
        esriConfig, jsapiBundle,
        arrayUtils, parser, keys) {
          // Get a reference to the ArcGIS Map class
          $scope.map = BootstrapMap.create("mapDiv",{
            basemap:"gray",
            center:[-71.059, 42.36],
            zoom:14,
            scrollWheelZoom: false
          });

          $scope.map.on("layers-add-result", initEditor);

          esriConfig.defaults.geometryService = new GeometryService("http://tasks.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer");

            var parcel = new FeatureLayer("http://mapservices.bostonredevelopmentauthority.org/arcgis/rest/services/Test/Article80_test/FeatureServer/0",{
              mode: FeatureLayer.MODE_ONDEMAND,
              outFields: ['*'],
              opacity: 0.8
            });

            $scope.map.addLayers([parcel]);

            function initEditor(evt) {
          var templateLayers = arrayUtils.map(evt.layers, function(result){
            return result.layer;
          });
          var templatePicker = new TemplatePicker({
            featureLayers: templateLayers,
            grouping: true,
            rows: "auto",
            columns: 3
          }, "templateDiv");
          templatePicker.startup();

          var layers = arrayUtils.map(evt.layers, function(result) {
            return { featureLayer: result.layer };
          });
          var settings = {
            map: $scope.map,
            templatePicker: templatePicker,
            layerInfos: layers,
            toolbarVisible: true,
            createOptions: {
              polylineDrawTools:[ Editor.CREATE_TOOL_FREEHAND_POLYLINE ],
              polygonDrawTools: [ Editor.CREATE_TOOL_FREEHAND_POLYGON,
                Editor.CREATE_TOOL_CIRCLE,
                Editor.CREATE_TOOL_TRIANGLE,
                Editor.CREATE_TOOL_RECTANGLE
              ]
            },
            toolbarOptions: {
              reshapeVisible: true,
              mergeVisible: true,
              cutVisible: true
            }
          };

          var params = {settings: settings};
          var myEditor = new Editor(params,'editorDiv');
          //define snapping options
          var symbol = new SimpleMarkerSymbol(
            SimpleMarkerSymbol.STYLE_CROSS,
            15,
            new SimpleLineSymbol(
              SimpleLineSymbol.STYLE_SOLID,
              new Color([255, 0, 0, 0.5]),
              5
            ),
            null
          );
          $scope.map.enableSnapping({
            snapPointSymbol: symbol,
            tolerance: 20,
            snapKey: keys.ALT
          });

          myEditor.startup();

          $scope.map.on("click",function(e){
            // console.log(e);

            var identifyTask = new IdentifyTask("http://mapservices.bostonredevelopmentauthority.org/arcgis/rest/services/Test/Article80_test/MapServer");
            identifyParams = new IdentifyParameters();
            identifyParams.tolerance = 6;
            identifyParams.returnGeometry = true;
            identifyParams.layerIds = [0];
            identifyParams.layerOption = IdentifyParameters.LAYER_OPTION_ALL;
            identifyParams.width = $scope.map.width;
            identifyParams.height = $scope.map.height;
            identifyParams.geometry = e.mapPoint;
            identifyParams.mapExtent = $scope.map.extent;
            identifyTask.execute(identifyParams, function (idResults) {
                // handleIdResultAddress(idResults, e);
                console.log(idResults);
                $scope.projects.value[3] = idResults[0].feature.attributes.X;
                $scope.projects.value[4] = idResults[0].feature.attributes.Y;
                $scope.$apply();
            });

            // console.log($scope.projects);
          });
        }

      });

});<|endoftext|>


<commit_before><commit_msg>lint fix, related to https://github.com/phetsims/tambo/issues/73<commit_after><|endoftext|>


<commit_before>import Snap from "snapsvg/dist/snap.svg-min";
import {Calc} from "./calc";
import {zodiac} from "./zodiac";
import {planets} from "./planets";

export class Drawer {
  draw(properties) {
    if (properties.hasOwnProperty('selector')) {
      this.selector = properties.selector;
    } else {
      throw new Error('Irregular selector');
    }

    this.planets = (properties.hasOwnProperty('planets')) ? properties.planets : null;
    this.houses = (properties.hasOwnProperty('houses')) ? properties.houses : null;

    this.s = Snap(this.selector);
    this.s.attr({viewBox: "-50 -50 100 100"});

    let drawn = {
      circles: this.drawZodiacCircles(),
      degrees: this.drawZodiacDegrees(),
      signs: this.drawZodiacSigns(),
      houses: {
        axes: this.drawHousesAxes(),
        meta: this.houses
      },
      planets: [
        this.drawSun(),
        this.drawMercury(),
        this.drawVenus(),
        this.drawMars(),
        this.drawMoon(),
        this.drawJupiter(),
        this.drawSaturn(),
        this.drawUranus(),
        this.drawNeptune(),
        this.drawPluto()
      ]
    };

    // drawn.planets = this.correctCollidingPlanets(drawn.planets);

    return drawn;
  }

  describeArc(radius, startDegree, endDegree) {

    let start = Calc.getPointOnCircle(radius, endDegree);
    let end = Calc.getPointOnCircle(radius, startDegree);
    let largeArcFlag = endDegree - startDegree <= 180 ? "0" : "1";

    let d = [
      "A", radius, radius, 0, largeArcFlag, 0, end.x, end.y
    ].join(" ");

    return d;
  }

  drawZodiacCircles() {
    let circles = {
      outer: this.s.circle(0, 0, zodiac.radius.outer),
      inner: this.s.circle(0, 0, zodiac.radius.inner),
      innerAuxiliary: this.s.circle(0, 0, zodiac.radius.innerAuxiliary)
    }

    circles.outer.attr({
      fill: "rgba(250, 250, 250, 0.15)",
      stroke: zodiac.stroke,
      strokeWidth: 0.2
    });
    circles.inner.attr({
      fill: "rgba(255, 255, 255, 0)",
      stroke: zodiac.stroke,
      strokeWidth: 0.2
    });
    circles.innerAuxiliary.attr({
      fill: "rgba(255, 255, 255, 0)",
      stroke: zodiac.stroke,
      strokeWidth: 0.1
    });

    return circles;
  }

  drawZodiacDegrees() {
    let degrees = [];

    for (let degree = 0; degree <= 360; degree++) {
      const radius = zodiac.radius.innerAuxiliary;
      const offsetFromRadius = 1;

      const point1 = Calc.getPointOnCircle(radius, degree);
      const point2 = Calc.getPointOnCircle(radius, degree, offsetFromRadius);

      const zodiacDegree = this.s.line(point1.x, point1.y, point2.x, point2.y);
      zodiacDegree.attr({
        index: degree,
        stroke: zodiac.stroke,
        strokeWidth: 0.1
      });

      degrees.push({
        meta: {
          degree,
          point1,
          point2
        },
        zodiacDegree
      });
    }

    return degrees;
  }

  drawZodiacSigns() {
    const zodiacSignImageWidth = 3;
    const zodiacSignImageHeight = 3;

    let signs = [];

    for (let sign = 0; sign <= 11; sign++) {
      let degree = sign * 30;
      let degreeBetweenSigns = degree + 15;
      let degreeNextSign = degree + 30;

      const topLeftPoint = Calc.getPointOnCircle(zodiac.radius.outer, degree);
      const topRightPoint = Calc.getPointOnCircle(zodiac.radius.innerAuxiliary, degree);
      const rightArcDescription = this.describeArc(zodiac.radius.innerAuxiliary, degreeNextSign, degree);
      const bottomLeftPoint = Calc.getPointOnCircle(zodiac.radius.outer, degreeNextSign);
      const leftArcDescription = this.describeArc(zodiac.radius.outer, degreeNextSign, degree);

      const zodiacSignBackground = this.s.path([
        "M", topLeftPoint.x, topLeftPoint.y,
        "L", topRightPoint.x, topRightPoint.y,
        rightArcDescription,
        "L", bottomLeftPoint.x, bottomLeftPoint.y,
        "M", topLeftPoint.x, topLeftPoint.y,
        leftArcDescription,
        "M", topLeftPoint.x, topLeftPoint.y,
        "Z"
      ].join(" "));

      zodiacSignBackground.attr({
        fill: zodiac.signs[sign].fillColor(),
        stroke: zodiac.stroke,
        strokeWidth: 0.1
      });

      const zodiacSignPosition = Calc.getPointOnCircle(zodiac.radius.betweenOuterInner, degreeBetweenSigns)
      const zodiacSignImagePositionX = zodiacSignPosition.x - zodiacSignImageWidth / 2;
      const zodiacSignImagePositionY = zodiacSignPosition.y - zodiacSignImageHeight / 2;
      const zodiacSignSymbol = this.s.image(zodiac.signs[sign].imageUrl, zodiacSignImagePositionX, zodiacSignImagePositionY, zodiacSignImageWidth, zodiacSignImageHeight);

      signs.push({
        meta: zodiac.signs[sign],
        symbol: zodiacSignSymbol,
        background: zodiacSignBackground
      });
    }

    return signs;
  }

  drawHousesAxes() {
    let axis = [];

    // 1 + 7
    const ascendantDegree = (this.houses.hasOwnProperty('house1') && this.houses.house1.hasOwnProperty('degree')) ? this.houses.house1.degree : null;
    const ascendantPoint = Calc.getPointOnCircle(zodiac.radius.outer, ascendantDegree, -2);
    const descendantPoint = Calc.getPointOnCircle(zodiac.radius.outer, Calc.getOppositeDegree(ascendantDegree), -2);
    const ascendantDescendantAxis = this.s.line(ascendantPoint.x, ascendantPoint.y, descendantPoint.x, descendantPoint.y);
    ascendantDescendantAxis.attr({
      stroke: zodiac.stroke,
      strokeWidth: 0.5
    });
    axis.push(ascendantDescendantAxis);

    // 2 + 8
    const house2Degree = (this.houses.hasOwnProperty('house2') && this.houses.house2.hasOwnProperty('degree')) ? this.houses.house2.degree : null;
    const house2Point = Calc.getPointOnCircle(zodiac.radius.outer, house2Degree, -2);
    const house8Point = Calc.getPointOnCircle(zodiac.radius.outer, Calc.getOppositeDegree(house2Degree), -2);
    const house2house8Axis = this.s.line(house2Point.x, house2Point.y, house8Point.x, house8Point.y);
    house2house8Axis.attr({
      stroke: zodiac.stroke,
      strokeWidth: 0.2
    });
    axis.push(house2house8Axis);

    // 3 + 9
    const house3Degree = (this.houses.hasOwnProperty('house3') && this.houses.house3.hasOwnProperty('degree')) ? this.houses.house3.degree : null;
    const house3Point = Calc.getPointOnCircle(zodiac.radius.outer, house3Degree, -2);
    const house9Point = Calc.getPointOnCircle(zodiac.radius.outer, Calc.getOppositeDegree(house3Degree), -2);
    const house3house9Axis = this.s.line(house3Point.x, house3Point.y, house9Point.x, house9Point.y);
    house3house9Axis.attr({
      stroke: zodiac.stroke,
      strokeWidth: 0.2
    });
    axis.push(house3house9Axis);

    // 4 + 10
    const immumCoelliDegree = (this.houses.hasOwnProperty('house4') && this.houses.house4.hasOwnProperty('degree')) ? this.houses.house4.degree : null;
    const immumCoelliPoint = Calc.getPointOnCircle(zodiac.radius.outer, immumCoelliDegree, -2);
    const mediumCoelliPoint = Calc.getPointOnCircle(zodiac.radius.outer, Calc.getOppositeDegree(immumCoelliDegree), -2);
    const immumMediumCoelliAxis = this.s.line(immumCoelliPoint.x, immumCoelliPoint.y, mediumCoelliPoint.x, mediumCoelliPoint.y);
    immumMediumCoelliAxis.attr({
      stroke: zodiac.stroke,
      strokeWidth: 0.5
    });
    axis.push(immumMediumCoelliAxis);

    // 5 + 11
    const house5Degree = (this.houses.hasOwnProperty('house5') && this.houses.house5.hasOwnProperty('degree')) ? this.houses.house5.degree : null;
    const house5Point = Calc.getPointOnCircle(zodiac.radius.outer, house5Degree, -2);
    const house11Point = Calc.getPointOnCircle(zodiac.radius.outer, Calc.getOppositeDegree(house5Degree), -2);
    const house5house11Axis = this.s.line(house5Point.x, house5Point.y, house11Point.x, house11Point.y);
    house5house11Axis.attr({
      stroke: zodiac.stroke,
      strokeWidth: 0.2
    });
    axis.push(house5house11Axis);

    // 6 + 12
    const house6Degree = (this.houses.hasOwnProperty('house6') && this.houses.house6.hasOwnProperty('degree')) ? this.houses.house6.degree : null;
    const house6Point = Calc.getPointOnCircle(zodiac.radius.outer, house6Degree, -2);
    const house12Point = Calc.getPointOnCircle(zodiac.radius.outer, Calc.getOppositeDegree(house6Degree), -2);
    const house6house12Axis = this.s.line(house6Point.x, house6Point.y, house12Point.x, house12Point.y);
    house6house12Axis.attr({
      stroke: zodiac.stroke,
      strokeWidth: 0.2
    });
    axis.push(house6house12Axis);

    return axis;
  }

  drawPlanet(planet, degree) {
    const planetImageWidth = 4;
    const planetImageHeight = 4;

    const linePoint1 = Calc.getPointOnCircle(zodiac.radius.inner, degree);
    const linePoint2 = Calc.getPointOnCircle(zodiac.radius.inner, degree, 1);
    const planetAuxiliaryLine = this.s.line(linePoint1.x, linePoint1.y, linePoint2.x, linePoint2.y);
    planetAuxiliaryLine.attr({
      stroke: zodiac.stroke,
      strokeWidth: 0.2
    });

    const planetPosition = Calc.getPointOnCircle(zodiac.radius.inner, degree, 3);
    const planetImagePositionX = planetPosition.x - planetImageWidth / 2;
    const planetImagePositionY = planetPosition.y - planetImageHeight / 2;

    let planetSymbolBackgroundRadius = null;
    if (planetImageWidth > planetImageHeight) {
      planetSymbolBackgroundRadius = planetImageWidth / 2;
    } else {
      planetSymbolBackgroundRadius = planetImageHeight / 2;
    }
    const planetSymbolBackground = this.s.circle(planetPosition.x, planetPosition.y, planetSymbolBackgroundRadius);
    planetSymbolBackground.attr({
      fill: "#F2F2F2"
    });

    const planetSymbol = this.s.image(planet.imageUrl, planetImagePositionX, planetImagePositionY, planetImageWidth, planetImageHeight);

    const meta = {};
    Object.assign(meta, planet);
    meta['degree'] = degree;
    meta['position'] = planetPosition;

    return {
      planet: planetSymbol,
      background: planetSymbolBackground,
      meta
    };
  }

  drawSun() {
    return this.drawPlanet(planets.find((elem) => {
      return elem.name == "Sun";
    }), this.planets.sun.degree);
  }

  drawMercury() {
    return this.drawPlanet(planets.find((elem) => {
      return elem.name == "Mercury";
    }), this.planets.mercury.degree);
  }

  drawVenus() {
    return this.drawPlanet(planets.find((elem) => {
      return elem.name == "Venus";
    }), this.planets.venus.degree);
  }

  drawMars() {
    return this.drawPlanet(planets.find((elem) => {
      return elem.name == "Mars";
    }), this.planets.mars.degree);
  }

  drawMoon() {
    return this.drawPlanet(planets.find((elem) => {
      return elem.name == "Moon";
    }), this.planets.moon.degree);
  }

  drawJupiter() {
    return this.drawPlanet(planets.find((elem) => {
      return elem.name == "Jupiter";
    }), this.planets.jupiter.degree);
  }

  drawSaturn() {
    return this.drawPlanet(planets.find((elem) => {
      return elem.name == "Saturn";
    }), this.planets.saturn.degree);
  }

  drawUranus() {
    return this.drawPlanet(planets.find((elem) => {
      return elem.name == "Uranus";
    }), this.planets.uranus.degree);
  }

  drawNeptune() {
    return this.drawPlanet(planets.find((elem) => {
      return elem.name == "Neptune";
    }), this.planets.neptune.degree);
  }

  drawPluto() {
    return this.drawPlanet(planets.find((elem) => {
      return elem.name == "Pluto";
    }), this.planets.pluto.degree);
  }

  correctCollidingPlanets(planets) {
    let planetsCoordinates = planets.map((planet) => {
      return {
        name: planet.name,
        x: planet.drawing.position.x,
        y: planet.drawing.position.y
      }
    }).sort((a, b) => {
      return a.x > b.x && a.y > b.y;
    });

    return;
  }
}
export let drawer = new Drawer();<commit_msg>Improves meta information<commit_after>import Snap from "snapsvg/dist/snap.svg-min";
import {Calc} from "./calc";
import {zodiac} from "./zodiac";
import {planets} from "./planets";

export class Drawer {
  draw(properties) {
    if (properties.hasOwnProperty('selector')) {
      this.selector = properties.selector;
    } else {
      throw new Error('Irregular selector');
    }

    this.planets = (properties.hasOwnProperty('planets')) ? properties.planets : null;
    this.houses = (properties.hasOwnProperty('houses')) ? properties.houses : null;

    this.s = Snap(this.selector);
    this.s.attr({viewBox: "-50 -50 100 100"});

    let drawn = {
      circles: this.drawZodiacCircles(),
      degrees: this.drawZodiacDegrees(),
      signs: this.drawZodiacSigns(),
      houses: {
        axes: this.drawHousesAxes(),
        meta: this.houses
      },
      planets: [
        this.drawSun(),
        this.drawMercury(),
        this.drawVenus(),
        this.drawMars(),
        this.drawMoon(),
        this.drawJupiter(),
        this.drawSaturn(),
        this.drawUranus(),
        this.drawNeptune(),
        this.drawPluto()
      ]
    };

    // drawn.planets = this.correctCollidingPlanets(drawn.planets);

    return drawn;
  }

  describeArc(radius, startDegree, endDegree) {

    let start = Calc.getPointOnCircle(radius, endDegree);
    let end = Calc.getPointOnCircle(radius, startDegree);
    let largeArcFlag = endDegree - startDegree <= 180 ? "0" : "1";

    let d = [
      "A", radius, radius, 0, largeArcFlag, 0, end.x, end.y
    ].join(" ");

    return d;
  }

  drawZodiacCircles() {
    let circles = {
      outer: this.s.circle(0, 0, zodiac.radius.outer),
      inner: this.s.circle(0, 0, zodiac.radius.inner),
      innerAuxiliary: this.s.circle(0, 0, zodiac.radius.innerAuxiliary)
    }

    circles.outer.attr({
      fill: "rgba(250, 250, 250, 0.15)",
      stroke: zodiac.stroke,
      strokeWidth: 0.2
    });
    circles.inner.attr({
      fill: "rgba(255, 255, 255, 0)",
      stroke: zodiac.stroke,
      strokeWidth: 0.2
    });
    circles.innerAuxiliary.attr({
      fill: "rgba(255, 255, 255, 0)",
      stroke: zodiac.stroke,
      strokeWidth: 0.1
    });

    return circles;
  }

  drawZodiacDegrees() {
    let degrees = [];

    for (let degree = 0; degree <= 360; degree++) {
      const radius = zodiac.radius.innerAuxiliary;
      const offsetFromRadius = 1;

      const point1 = Calc.getPointOnCircle(radius, degree);
      const point2 = Calc.getPointOnCircle(radius, degree, offsetFromRadius);

      const zodiacDegree = this.s.line(point1.x, point1.y, point2.x, point2.y);
      zodiacDegree.attr({
        index: degree,
        stroke: zodiac.stroke,
        strokeWidth: 0.1
      });

      degrees.push({
        meta: {
          degree,
          point1,
          point2
        },
        zodiacDegree
      });
    }

    return degrees;
  }

  drawZodiacSigns() {
    const zodiacSignImageWidth = 3;
    const zodiacSignImageHeight = 3;

    let signs = [];

    for (let sign = 0; sign <= 11; sign++) {
      const signMeta = zodiac.signs[sign];

      let degree = sign * 30;
      let degreeBetweenSigns = degree + 15;
      let degreePreviousSign = degree - 30;
      let degreeNextSign = degree + 30;

      const topLeftPoint = Calc.getPointOnCircle(zodiac.radius.outer, degree);
      const topRightPoint = Calc.getPointOnCircle(zodiac.radius.innerAuxiliary, degree);
      const rightArcDescription = this.describeArc(zodiac.radius.innerAuxiliary, degreeNextSign, degree);
      const bottomLeftPoint = Calc.getPointOnCircle(zodiac.radius.outer, degreeNextSign);
      const leftArcDescription = this.describeArc(zodiac.radius.outer, degreeNextSign, degree);

      const zodiacSignBackground = this.s.path([
        "M", topLeftPoint.x, topLeftPoint.y,
        "L", topRightPoint.x, topRightPoint.y,
        rightArcDescription,
        "L", bottomLeftPoint.x, bottomLeftPoint.y,
        "M", topLeftPoint.x, topLeftPoint.y,
        leftArcDescription,
        "M", topLeftPoint.x, topLeftPoint.y,
        "Z"
      ].join(" "));

      zodiacSignBackground.attr({
        fill: signMeta.fillColor(),
        stroke: zodiac.stroke,
        strokeWidth: 0.1
      });

      const zodiacSignPosition = Calc.getPointOnCircle(zodiac.radius.betweenOuterInner, degreeBetweenSigns)
      const zodiacSignImagePositionX = zodiacSignPosition.x - zodiacSignImageWidth / 2;
      const zodiacSignImagePositionY = zodiacSignPosition.y - zodiacSignImageHeight / 2;
      const zodiacSignSymbol = this.s.image(signMeta.imageUrl, zodiacSignImagePositionX, zodiacSignImagePositionY, zodiacSignImageWidth, zodiacSignImageHeight);

      let meta = {};
      Object.assign(meta, signMeta);
      meta['degree'] = {
        self: degree,
        nextSign: degreeNextSign,
        previousSign: degreePreviousSign
      };
      meta['position'] = zodiacSignPosition;

      signs.push({
        meta,
        symbol: zodiacSignSymbol,
        background: zodiacSignBackground
      });
    }

    return signs;
  }

  drawHousesAxes() {
    let axis = [];

    // 1 + 7
    const ascendantDegree = (this.houses.hasOwnProperty('house1') && this.houses.house1.hasOwnProperty('degree')) ? this.houses.house1.degree : null;
    const ascendantPoint = Calc.getPointOnCircle(zodiac.radius.outer, ascendantDegree, -2);
    const descendantPoint = Calc.getPointOnCircle(zodiac.radius.outer, Calc.getOppositeDegree(ascendantDegree), -2);
    const ascendantDescendantAxis = this.s.line(ascendantPoint.x, ascendantPoint.y, descendantPoint.x, descendantPoint.y);
    ascendantDescendantAxis.attr({
      stroke: zodiac.stroke,
      strokeWidth: 0.5
    });
    axis.push(ascendantDescendantAxis);

    // 2 + 8
    const house2Degree = (this.houses.hasOwnProperty('house2') && this.houses.house2.hasOwnProperty('degree')) ? this.houses.house2.degree : null;
    const house2Point = Calc.getPointOnCircle(zodiac.radius.outer, house2Degree, -2);
    const house8Point = Calc.getPointOnCircle(zodiac.radius.outer, Calc.getOppositeDegree(house2Degree), -2);
    const house2house8Axis = this.s.line(house2Point.x, house2Point.y, house8Point.x, house8Point.y);
    house2house8Axis.attr({
      stroke: zodiac.stroke,
      strokeWidth: 0.2
    });
    axis.push(house2house8Axis);

    // 3 + 9
    const house3Degree = (this.houses.hasOwnProperty('house3') && this.houses.house3.hasOwnProperty('degree')) ? this.houses.house3.degree : null;
    const house3Point = Calc.getPointOnCircle(zodiac.radius.outer, house3Degree, -2);
    const house9Point = Calc.getPointOnCircle(zodiac.radius.outer, Calc.getOppositeDegree(house3Degree), -2);
    const house3house9Axis = this.s.line(house3Point.x, house3Point.y, house9Point.x, house9Point.y);
    house3house9Axis.attr({
      stroke: zodiac.stroke,
      strokeWidth: 0.2
    });
    axis.push(house3house9Axis);

    // 4 + 10
    const immumCoelliDegree = (this.houses.hasOwnProperty('house4') && this.houses.house4.hasOwnProperty('degree')) ? this.houses.house4.degree : null;
    const immumCoelliPoint = Calc.getPointOnCircle(zodiac.radius.outer, immumCoelliDegree, -2);
    const mediumCoelliPoint = Calc.getPointOnCircle(zodiac.radius.outer, Calc.getOppositeDegree(immumCoelliDegree), -2);
    const immumMediumCoelliAxis = this.s.line(immumCoelliPoint.x, immumCoelliPoint.y, mediumCoelliPoint.x, mediumCoelliPoint.y);
    immumMediumCoelliAxis.attr({
      stroke: zodiac.stroke,
      strokeWidth: 0.5
    });
    axis.push(immumMediumCoelliAxis);

    // 5 + 11
    const house5Degree = (this.houses.hasOwnProperty('house5') && this.houses.house5.hasOwnProperty('degree')) ? this.houses.house5.degree : null;
    const house5Point = Calc.getPointOnCircle(zodiac.radius.outer, house5Degree, -2);
    const house11Point = Calc.getPointOnCircle(zodiac.radius.outer, Calc.getOppositeDegree(house5Degree), -2);
    const house5house11Axis = this.s.line(house5Point.x, house5Point.y, house11Point.x, house11Point.y);
    house5house11Axis.attr({
      stroke: zodiac.stroke,
      strokeWidth: 0.2
    });
    axis.push(house5house11Axis);

    // 6 + 12
    const house6Degree = (this.houses.hasOwnProperty('house6') && this.houses.house6.hasOwnProperty('degree')) ? this.houses.house6.degree : null;
    const house6Point = Calc.getPointOnCircle(zodiac.radius.outer, house6Degree, -2);
    const house12Point = Calc.getPointOnCircle(zodiac.radius.outer, Calc.getOppositeDegree(house6Degree), -2);
    const house6house12Axis = this.s.line(house6Point.x, house6Point.y, house12Point.x, house12Point.y);
    house6house12Axis.attr({
      stroke: zodiac.stroke,
      strokeWidth: 0.2
    });
    axis.push(house6house12Axis);

    return axis;
  }

  drawPlanet(planet, degree) {
    const planetImageWidth = 4;
    const planetImageHeight = 4;

    const linePoint1 = Calc.getPointOnCircle(zodiac.radius.inner, degree);
    const linePoint2 = Calc.getPointOnCircle(zodiac.radius.inner, degree, 1);
    const planetAuxiliaryLine = this.s.line(linePoint1.x, linePoint1.y, linePoint2.x, linePoint2.y);
    planetAuxiliaryLine.attr({
      stroke: zodiac.stroke,
      strokeWidth: 0.2
    });

    const planetPosition = Calc.getPointOnCircle(zodiac.radius.inner, degree, 3);
    const planetImagePositionX = planetPosition.x - planetImageWidth / 2;
    const planetImagePositionY = planetPosition.y - planetImageHeight / 2;

    let planetSymbolBackgroundRadius = null;
    if (planetImageWidth > planetImageHeight) {
      planetSymbolBackgroundRadius = planetImageWidth / 2;
    } else {
      planetSymbolBackgroundRadius = planetImageHeight / 2;
    }
    const planetSymbolBackground = this.s.circle(planetPosition.x, planetPosition.y, planetSymbolBackgroundRadius);
    planetSymbolBackground.attr({
      fill: "#F2F2F2"
    });

    const planetSymbol = this.s.image(planet.imageUrl, planetImagePositionX, planetImagePositionY, planetImageWidth, planetImageHeight);

    let meta = {};
    Object.assign(meta, planet);
    meta['degree'] = degree;
    meta['position'] = planetPosition;

    return {
      planet: planetSymbol,
      background: planetSymbolBackground,
      meta
    };
  }

  drawSun() {
    return this.drawPlanet(planets.find((elem) => {
      return elem.name == "Sun";
    }), this.planets.sun.degree);
  }

  drawMercury() {
    return this.drawPlanet(planets.find((elem) => {
      return elem.name == "Mercury";
    }), this.planets.mercury.degree);
  }

  drawVenus() {
    return this.drawPlanet(planets.find((elem) => {
      return elem.name == "Venus";
    }), this.planets.venus.degree);
  }

  drawMars() {
    return this.drawPlanet(planets.find((elem) => {
      return elem.name == "Mars";
    }), this.planets.mars.degree);
  }

  drawMoon() {
    return this.drawPlanet(planets.find((elem) => {
      return elem.name == "Moon";
    }), this.planets.moon.degree);
  }

  drawJupiter() {
    return this.drawPlanet(planets.find((elem) => {
      return elem.name == "Jupiter";
    }), this.planets.jupiter.degree);
  }

  drawSaturn() {
    return this.drawPlanet(planets.find((elem) => {
      return elem.name == "Saturn";
    }), this.planets.saturn.degree);
  }

  drawUranus() {
    return this.drawPlanet(planets.find((elem) => {
      return elem.name == "Uranus";
    }), this.planets.uranus.degree);
  }

  drawNeptune() {
    return this.drawPlanet(planets.find((elem) => {
      return elem.name == "Neptune";
    }), this.planets.neptune.degree);
  }

  drawPluto() {
    return this.drawPlanet(planets.find((elem) => {
      return elem.name == "Pluto";
    }), this.planets.pluto.degree);
  }

  correctCollidingPlanets(planets) {
    let planetsCoordinates = planets.map((planet) => {
      return {
        name: planet.name,
        x: planet.drawing.position.x,
        y: planet.drawing.position.y
      }
    }).sort((a, b) => {
      return a.x > b.x && a.y > b.y;
    });

    return;
  }
}
export let drawer = new Drawer();<|endoftext|>


<commit_before><commit_msg>Cleaning up the dps string slightly.<commit_after><|endoftext|>


<commit_before>function sampleCheck()
{
    var answer = document.getElementById("sampleA").value;
    if (answer.toLowerCase() == "popo")
    {
        $("#sampleVideo").modal();
    }
    else
    {
        document.getElementById("incorrectAnswer").src = "img/"+generateRandom()+".jpg";
        $("#sampleImgPusph").modal();
        document.getElementById("msg").innerHTML = "Are you sure he calls you "+answer;
    }
}

function generateRandom(){
                var num = Math.floor((Math.random() * 0) + 1);
                return num;
            }

<commit_msg>Delete answers.js<commit_after><|endoftext|>


<commit_before><commit_msg>added mootools<commit_after><|endoftext|>


<commit_before><commit_msg>Stray bracket<commit_after><|endoftext|>


<commit_before>// https://github.com/chunpu/min-request
// (ISC)

var http = require('http')
var url = require('url')
var util = require('util')
var debug = function() {}
if (util.debuglog) {
  debug = util.debuglog('request')
}

module.exports = exports = request

function canPipe(x) {
  return x && 'function' == typeof x.pipe
}

function request(raw, opt, cb) {
  if ('function' == opt) {
    cb = opt
    opt = {}
  }
  if (!/^http/i.test(raw)) {
    raw = 'http://' + raw
  }
  var parsed = url.parse(raw)
  var headers = opt.headers || {}
  var options = {
      hostname: parsed.hostname
    , port: parsed.port
    , path: parsed.path
    , auth: parsed.auth || undefined
  }
  var method = 'GET'
  var body = opt.body || opt.data
  var type, len

  if (null != body) {
    // string, buffer, stream, object
    method = 'POST'
    if (Buffer.isBuffer(body)) {
      type = 'bin'
      len = body.length
    } else if (canPipe(body)) {
      type = 'bin'
    } else {
      // json
      try {
        body = JSON.stringify(body)
      } catch (e) {
        return cb(e)
      }
      type = 'application/json;charset=utf-8'
      len = Buffer.byteLength(body)
    }
  }

  if (type) headers['Content-Type'] = type
  if (len) headers['Content-Length'] = len

  options.headers = headers
  options.method = opt.method || method
  debug('options: %j', options)

  var req = http.request(options, function(res) {
    var body = ''
    res.on('data', function(buf) {
      body += buf
    }).on('end', function() {
      res.body = body
      cb(null, res, res.body)
    }).on('error', cb)
  }).on('error', cb)

  if (body) {
    if (canPipe(body)) {
      return body.pipe(req)
    } else {
      req.write(body)
    }
  }

  req.end()
}<commit_msg>lint http/min-request<commit_after>// https://github.com/chunpu/min-request
// (ISC)

var http = require('http')
var url  = require('url')
var util = require('util')

var debug = function () {}

if (util.debuglog) {
  debug = util.debuglog('request')
}

module.exports = exports = request

function canPipe (x) {
  return x && typeof x.pipe == 'function'
}

function request (raw, opt, cb) {
  if (opt == 'function') {
    cb = opt
    opt = {}
  }

  if (!/^http/i.test(raw)) {
    raw = 'http://' + raw
  }

  var parsed = url.parse(raw)
  var headers = opt.headers || {}
  var options = {
    hostname: parsed.hostname,
    port: parsed.port,
    path: parsed.path,
    auth: parsed.auth || undefined
  }
  var method = 'GET'
  var body = opt.body || opt.data
  var type, len

  if (body != null) {
    // string, buffer, stream, object
    method = 'POST'
    if (Buffer.isBuffer(body)) {
      type = 'bin'
      len = body.length
    } else if (canPipe(body)) {
      type = 'bin'
    } else {
      // json
      try {
        body = JSON.stringify(body)
      } catch (e) {
        return cb(e)
      }
      type = 'application/json;charset=utf-8'
      len = Buffer.byteLength(body)
    }
  }

  if (type) headers['Content-Type'] = type
  if (len) headers['Content-Length'] = len

  options.headers = headers
  options.method = opt.method || method
  debug('options: %j', options)

  var req = http.request(options, function (res) {
    var body = ''
    res.on('data', function (buf) {
      body += buf
    }).on('end', function () {
      res.body = body
      cb(null, res, res.body)
    }).on('error', cb)
  }).on('error', cb)

  if (body) {
    if (canPipe(body)) {
      return body.pipe(req)
    } else {
      req.write(body)
    }
  }

  req.end()
}
<|endoftext|>