<commit_before>
var phet = {};

$(document).ready( function() {
    // constants
    var activeClass = 'ui-btn-active';

    var type = "type-easel";
    var test = "test-boxes";

    // hook up activity changes so we can toggle sets of buttons
    _.each( [
        [ 'type-easel', 'type-custom' ], // Easel / Custom
        [ 'test-boxes', 'test-text' ] // Separate tests
    ], function( list ) {
        _.each( list, function( selector ) {
            // set up initial buttons
            if( selector == type || selector == test ) {
                $( '#' + selector ).addClass( activeClass );
            }

            // handle toggling for each button
            $( '#' + selector ).on( 'click', function( event, ui ) {
                // update the button highlights
                _.each( list, function( button ) {
                    if( button == selector ) {
                        // select this button as active
                        $( '#' + button ).addClass( activeClass );
                    } else {
                        // and set others as inactive
                        $( '#' + button ).removeClass( activeClass );
                    }
                } );

                // change the test
                if( selector.substring( 0, 4 ) == "type" ) {
                    type = selector;
                } else {
                    test = selector;
                }
                changeTest();
            } );
        } );
    } );

    var main = $('#main');

    // closure used over this for running steps
    var step = function( timeElapsed ) {

    };

    // called whenever the test is supposed to change
    function changeTest() {
        // clear the main area
        main.empty();

        if( type == 'type-easel' ) {
            var canvas = document.createElement( 'canvas' );
            canvas.id = 'easel-canvas';
            canvas.width = main.width();
            canvas.height = main.height();
            main.append( canvas );

            var stage = new createjs.Stage(canvas);

            if( test == 'test-boxes' ) {
                var shape = new createjs.Shape();
                shape.graphics.beginFill('rgba(255,0,0,1)').drawRect( 0, 0, 100, 100 );
                shape.x = main.width() / 2;
                shape.y = main.height() / 2;
                stage.addChild(shape);

                step = function( timeElapsed ) {
                    shape.rotation += timeElapsed * 180 / Math.PI;
                    stage.update();
                };
            } else if( test == 'test-text' ) {
                var text = new createjs.Text( 'Test String', '20px Arial', '#555555' );
                stage.addChild( text );
                text.x = 100;
                text.y = 100;

                step = function( timeElapsed ) {
                    text.rotation += timeElapsed * 180 / Math.PI;
                    stage.update();
                };
            }
        } else {
            if( test == 'test-boxes' ) {

            } else if( test == 'test-text' ) {

            }
        }
    }

    // set up averaging FPS meter and calling of the step() function
    (function(){
        // records the last #fpsCount timestamps, and displays the average FPS over that time
        var fpsReadout = $('#fps-readout');
        var fpsCount = 10;
        var fpsIndex = 0;
        // stuffs timestamps in a round-robin fashion into here
        var timeEntries = _.map( _.range( fpsCount ), function( a ) { return 0; } );
        function updateFps() {
            var timestamp = Date.now();
            timeEntries[ fpsIndex ] = timestamp;
            fpsIndex = ( fpsIndex + 1 ) % fpsCount;
            var timeChange = ( timestamp - timeEntries[ fpsIndex ] ) / 1000;
            var fps = 10 / timeChange;
            if( fps < 1 ) {
                fpsReadout.text( "-" );
            } else {
                fpsReadout.text( fps.toFixed( 1 ) );
            }
        }

        var lastTime = 0;
        var timeElapsed = 0;

        // setting up regular calls for step()
        function tick() {
            window.requestAnimationFrame( tick, main[0] );
            var timeNow = new Date().getTime();
            if ( lastTime != 0 ) {
                timeElapsed = (timeNow - lastTime) / 1000.0;
            }
            lastTime = timeNow;

            if( timeElapsed != 0 ) {
                step( timeElapsed );
            }
            updateFps();
        }
        window.requestAnimationFrame( tick, main[0] );
    })();

    // handle window resizing
    var resizer = function () {
        main.width( window.innerWidth );
        main.height( window.innerHeight );
        changeTest();
    };
    $( window ).resize( resizer );
    resizer();

    // for text testing: see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#2dcontext
    // context: font, textAlign, textBaseline, direction
    // metrics: width, actualBoundingBoxLeft, actualBoundingBoxRight, etc.
} );
<commit_msg>adding rough version of square test<commit_after>
var phet = phet || {};
phet.tests = phet.tests || {};

$(document).ready( function() {
    // constants
    var activeClass = 'ui-btn-active';

    var type = "type-easel";
    var test = "test-boxes";

    // hook up activity changes so we can toggle sets of buttons
    _.each( [
        [ 'type-easel', 'type-custom' ], // Easel / Custom
        [ 'test-boxes', 'test-text' ] // Separate tests
    ], function( list ) {
        _.each( list, function( selector ) {
            // set up initial buttons
            if( selector == type || selector == test ) {
                $( '#' + selector ).addClass( activeClass );
            }

            // handle toggling for each button
            $( '#' + selector ).on( 'click', function( event, ui ) {
                // update the button highlights
                _.each( list, function( button ) {
                    if( button == selector ) {
                        // select this button as active
                        $( '#' + button ).addClass( activeClass );
                    } else {
                        // and set others as inactive
                        $( '#' + button ).removeClass( activeClass );
                    }
                } );

                // change the test
                if( selector.substring( 0, 4 ) == "type" ) {
                    type = selector;
                } else {
                    test = selector;
                }
                changeTest();
            } );
        } );
    } );

    var main = $('#main');

    // closure used over this for running steps
    var step = function( timeElapsed ) {

    };

    // called whenever the test is supposed to change
    function changeTest() {
        // clear the main area
        main.empty();

        if( type == 'type-easel' ) {
            var canvas = document.createElement( 'canvas' );
            canvas.id = 'easel-canvas';
            canvas.width = main.width();
            canvas.height = main.height();
            main.append( canvas );

            var stage = new createjs.Stage(canvas);

            if( test == 'test-boxes' ) {
                var shape = new createjs.Shape();
                shape.graphics.beginFill('rgba(255,0,0,1)').drawRect( 0, 0, 100, 100 );
                shape.x = main.width() / 2;
                shape.y = main.height() / 2;
                stage.addChild(shape);

                step = function( timeElapsed ) {
                    shape.rotation += timeElapsed * 180 / Math.PI;
                    stage.update();
                };
            } else if( test == 'test-text' ) {
                var text = new createjs.Text( 'Test String', '20px Arial', '#555555' );
                stage.addChild( text );
                text.x = 100;
                text.y = 100;

                step = function( timeElapsed ) {
                    text.rotation += timeElapsed * 180 / Math.PI;
                    stage.update();
                };
            }
        } else {
            var baseCanvas = document.createElement( 'canvas' );
            baseCanvas.id = 'base-canvas';
            baseCanvas.width = main.width();
            baseCanvas.height = main.height();
            main.append( baseCanvas );
            var baseContext = phet.canvas.initCanvas( baseCanvas );

            if( test == 'test-boxes' ) {
                var x = main.width() / 2;
                var y = main.height() / 2;
                var rotation = 0;
                baseContext.fillStyle = 'rgba(255,0,0,1)';
                step = function( timeElapsed ) {
                    // clear old location
                    baseContext.clearRect( x - 150, y - 150, 300, 300 );
                    // TODO: consider whether clearRect is faster if it's not under a transform!

                    baseContext.save();
                    rotation += timeElapsed;
                    baseContext.translate( x, y );
                    baseContext.rotate( rotation );

                    baseContext.beginPath();
                    baseContext.moveTo( 0, 0 );
                    baseContext.lineTo( 100, 0 );
                    baseContext.lineTo( 100, 100 );
                    baseContext.lineTo( 0, 100 );
                    baseContext.closePath();
                    baseContext.fill();

                    baseContext.restore();
                };
            } else if( test == 'test-text' ) {
                step = function( timeElapsed ) {

                };
            }
        }
    }

    // set up averaging FPS meter and calling of the step() function
    (function(){
        // records the last #fpsCount timestamps, and displays the average FPS over that time
        var fpsReadout = $('#fps-readout');
        var fpsCount = 10;
        var fpsIndex = 0;
        // stuffs timestamps in a round-robin fashion into here
        var timeEntries = _.map( _.range( fpsCount ), function( a ) { return 0; } );
        function updateFps() {
            var timestamp = Date.now();
            timeEntries[ fpsIndex ] = timestamp;
            fpsIndex = ( fpsIndex + 1 ) % fpsCount;
            var timeChange = ( timestamp - timeEntries[ fpsIndex ] ) / 1000;
            var fps = 10 / timeChange;
            if( fps < 1 ) {
                fpsReadout.text( "-" );
            } else {
                fpsReadout.text( fps.toFixed( 1 ) );
            }
        }

        var lastTime = 0;
        var timeElapsed = 0;

        // setting up regular calls for step()
        function tick() {
            window.requestAnimationFrame( tick, main[0] );
            var timeNow = new Date().getTime();
            if ( lastTime != 0 ) {
                timeElapsed = (timeNow - lastTime) / 1000.0;
            }
            lastTime = timeNow;

            if( timeElapsed != 0 ) {
                step( timeElapsed );
            }
            updateFps();
        }
        window.requestAnimationFrame( tick, main[0] );
    })();

    // handle window resizing
    var resizer = function () {
        main.width( window.innerWidth );
        main.height( window.innerHeight );
        changeTest();
    };
    $( window ).resize( resizer );
    resizer();

    // for text testing: see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#2dcontext
    // context: font, textAlign, textBaseline, direction
    // metrics: width, actualBoundingBoxLeft, actualBoundingBoxRight, etc.
} );
<|endoftext|>


<commit_before>/*
 * mobile select unit tests
 */

(function($){
	module("jquery.mobile.forms.select native");

	test( "native menu selections alter the button text", function(){
		var select = $( "#native-select-choice-few" ), setAndCheck;

		setAndCheck = function(key){
			var text;

			select.val( key ).selectmenu( 'refresh' );
			text = select.find( "option[value='" + key + "']" ).text();
			deepEqual( select.parent().find(".ui-btn-text").text(), text );
		};

		setAndCheck( 'rush' );
		setAndCheck( 'standard' );
	});

	asyncTest( "selecting a value removes the related buttons down state", function(){
		var select = $( "#native-select-choice-few" );

		$.testHelper.sequence([
			function() {
				// click the native menu parent button
				select.parent().trigger( 'vmousedown' );
			},

			function() {
				ok( select.parent().hasClass("ui-btn-down-c"), "button down class added" );
			},

			function() {
				// trigger a change on the select
				select.trigger( "change" );
			},

			function() {
				ok( !select.parent().hasClass("ui-btn-down-c"), "button down class removed" );
				start();
			}
		], 300);
	});

	// issue https://github.com/jquery/jquery-mobile/issues/2410
	test( "adding options and refreshing a custom select defaults the text", function() {
		var select = $( "#custom-refresh" ),
			button = select.siblings( "a" ).find( ".ui-btn-inner" ),
			text = "foo";

		deepEqual($.trim(button.text()), "default");
		select.find( "option" ).remove(); //remove the loading message
		select.append('<option value="1">' + text + '</option>');
		select.selectmenu( 'refresh' );
		deepEqual($.trim(button.text()), text);
	});

	// issue 2424
	test( "native selects should provide open and close as a no-op", function() {
		// exception will prevent test success if undef
		$( "#native-refresh" ).selectmenu( 'open' );
		$( "#native-refresh" ).selectmenu( 'close' );
		ok( true );
	});

	asyncTest( "The preventFocusZoom option is working as expected", function() {

		var zoomoptiondefault = $.mobile.selectmenu.prototype.options.preventFocusZoom;
		$.mobile.selectmenu.prototype.options.preventFocusZoom = true;

		$(document)
			.one("vmousedown.test", function(){
				ok( $.mobile.zoom.enabled === false, "zoom is disabled on vmousedown" );
			})
			.one("mouseup.test", function(){
				setTimeout(function() { // This empty setTimeout is to match the work-around for the issue reported in https://github.com/jquery/jquery-mobile/issues/5041
					ok( $.mobile.zoom.enabled === true, "zoom is enabled on mouseup" );
					$.mobile.selectmenu.prototype.options.preventFocusZoom = zoomoptiondefault;
					$(document).unbind(".test");
					$( "#select-choice-native" ).selectmenu( "option", "preventFocusZoom", zoomoptiondefault );
					start();
				}, 0);
		});

		$( "#select-choice-native" )
			.selectmenu( "option", "preventFocusZoom", true )
			.parent()
			.trigger( "vmousedown" )
			.trigger( "mouseup" );

	});

	asyncTest( "The preventFocusZoom option does not manipulate zoom when it is false", function() {

		var zoomstate = $.mobile.zoom.enabled,
			zoomoptiondefault = $.mobile.selectmenu.prototype.options.preventFocusZoom;

		$(document)
			.one("vmousedown.test", function(){
				ok( $.mobile.zoom.enabled === zoomstate, "zoom is unaffected on vmousedown" );
			})
			.one("mouseup.test", function(){
				ok( $.mobile.zoom.enabled === zoomstate, "zoom is unaffected on mouseup" );
				$(document).unbind(".test");
				$( "#select-choice-native" ).selectmenu( "option", "preventFocusZoom", zoomoptiondefault );
				start();

		});

		$( "#select-choice-native" )
			.selectmenu( "option", "preventFocusZoom", false )
			.parent()
			.trigger( "vmousedown" )
			.trigger( "mouseup" );

	});
})(jQuery);<commit_msg>Integration tests: Select: Updating test for correct button update.<commit_after>/*
 * mobile select unit tests
 */

(function($){
	module("jquery.mobile.forms.select native");

	test( "native menu selections alter the button text", function(){
		var select = $( "#native-select-choice-few" ), setAndCheck;

		setAndCheck = function(key){
			var text;

			select.val( key ).selectmenu( 'refresh' );
			text = select.find( "option[value='" + key + "']" ).text();
			deepEqual( select.prev( "span" ).text(), text );
		};

		setAndCheck( 'rush' );
		setAndCheck( 'standard' );
	});

	asyncTest( "selecting a value removes the related buttons down state", function(){
		var select = $( "#native-select-choice-few" );

		$.testHelper.sequence([
			function() {
				// click the native menu parent button
				select.parent().trigger( 'vmousedown' );
			},

			function() {
				ok( select.parent().hasClass("ui-btn-down-c"), "button down class added" );
			},

			function() {
				// trigger a change on the select
				select.trigger( "change" );
			},

			function() {
				ok( !select.parent().hasClass("ui-btn-down-c"), "button down class removed" );
				start();
			}
		], 300);
	});

	// issue https://github.com/jquery/jquery-mobile/issues/2410
	test( "adding options and refreshing a custom select defaults the text", function() {
		var select = $( "#custom-refresh" ),
			button = select.siblings( "a" ).find( ".ui-btn-inner" ),
			text = "foo";

		deepEqual($.trim(button.text()), "default");
		select.find( "option" ).remove(); //remove the loading message
		select.append('<option value="1">' + text + '</option>');
		select.selectmenu( 'refresh' );
		deepEqual($.trim(button.text()), text);
	});

	// issue 2424
	test( "native selects should provide open and close as a no-op", function() {
		// exception will prevent test success if undef
		$( "#native-refresh" ).selectmenu( 'open' );
		$( "#native-refresh" ).selectmenu( 'close' );
		ok( true );
	});

	asyncTest( "The preventFocusZoom option is working as expected", function() {

		var zoomoptiondefault = $.mobile.selectmenu.prototype.options.preventFocusZoom;
		$.mobile.selectmenu.prototype.options.preventFocusZoom = true;

		$(document)
			.one("vmousedown.test", function(){
				ok( $.mobile.zoom.enabled === false, "zoom is disabled on vmousedown" );
			})
			.one("mouseup.test", function(){
				setTimeout(function() { // This empty setTimeout is to match the work-around for the issue reported in https://github.com/jquery/jquery-mobile/issues/5041
					ok( $.mobile.zoom.enabled === true, "zoom is enabled on mouseup" );
					$.mobile.selectmenu.prototype.options.preventFocusZoom = zoomoptiondefault;
					$(document).unbind(".test");
					$( "#select-choice-native" ).selectmenu( "option", "preventFocusZoom", zoomoptiondefault );
					start();
				}, 0);
		});

		$( "#select-choice-native" )
			.selectmenu( "option", "preventFocusZoom", true )
			.parent()
			.trigger( "vmousedown" )
			.trigger( "mouseup" );

	});

	asyncTest( "The preventFocusZoom option does not manipulate zoom when it is false", function() {

		var zoomstate = $.mobile.zoom.enabled,
			zoomoptiondefault = $.mobile.selectmenu.prototype.options.preventFocusZoom;

		$(document)
			.one("vmousedown.test", function(){
				ok( $.mobile.zoom.enabled === zoomstate, "zoom is unaffected on vmousedown" );
			})
			.one("mouseup.test", function(){
				ok( $.mobile.zoom.enabled === zoomstate, "zoom is unaffected on mouseup" );
				$(document).unbind(".test");
				$( "#select-choice-native" ).selectmenu( "option", "preventFocusZoom", zoomoptiondefault );
				start();

		});

		$( "#select-choice-native" )
			.selectmenu( "option", "preventFocusZoom", false )
			.parent()
			.trigger( "vmousedown" )
			.trigger( "mouseup" );

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


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

'use strict';

tvcm.require('tvcm.range');
tvcm.require('tvcm.ui.d3');
tvcm.require('tvcm.ui.dom_helpers');
tvcm.require('tvcm.ui.chart_base');

tvcm.requireStylesheet('tvcm.ui.pie_chart');

tvcm.exportTo('tvcm.ui', function() {
  var ChartBase = tvcm.ui.ChartBase;
  var getColorOfKey = tvcm.ui.getColorOfKey;

  var MIN_RADIUS = 100;

  /**
   * @constructor
   */
  var PieChart = tvcm.ui.define('pie-chart', ChartBase);

  PieChart.prototype = {
    __proto__: ChartBase.prototype,

    decorate: function() {
      ChartBase.prototype.decorate.call(this);
      this.classList.add('pie-chart');

      this.data_ = undefined;
      this.seriesKeys_ = undefined;

      var chartAreaSel = d3.select(this.chartAreaElement);
      var pieGroupSel = chartAreaSel.append('g')
        .attr('class', 'pie-group');
      this.pieGroup_ = pieGroupSel.node();

      this.pathsGroup_ = pieGroupSel.append('g')
        .attr('class', 'paths')
        .node();
      this.labelsGroup_ = pieGroupSel.append('g')
        .attr('class', 'labels')
        .node();
      this.linesGroup_ = pieGroupSel.append('g')
        .attr('class', 'lines')
        .node();
    },

    get data() {
      return this.data_;
    },

    /**
     * @param {Array} data Data for the chart, where each element in the array
     * must be of the form {label: str, value: number}.
     */
    set data(data) {
      if (data !== undefined) {
        // Figure out the label values in the data set. E.g. from
        //   [{label: 'a', ...}, {label: 'b', ...}]
        // we would commpute ['a', 'y']. These become the series keys.
        var seriesKeys = [];
        var seenSeriesKeys = {};
        data.forEach(function(d) {
          var k = d.label;
          if (seenSeriesKeys[k])
            throw new Error('Label ' + k + ' has been used already');
          seriesKeys.push(k);
          seenSeriesKeys[k] = true;
        }, this);
        this.seriesKeys_ = seriesKeys;
      } else {
        this.seriesKeys_ = undefined;
      }
      this.data_ = data;
      this.updateContents_();
    },

    get margin() {
      var margin = {top: 0, right: 0, bottom: 0, left: 0};
      if (this.chartTitle_)
        margin.top += 40;
      return margin;
    },

    getMinSize: function() {
      if (!tvcm.ui.isElementAttachedToDocument(this))
        throw new Error('Cannot measure when unattached');
      this.updateContents_();

      var labelSel = d3.select(this.labelsGroup_).selectAll('.label');
      var maxLabelWidth = -Number.MAX_VALUE;
      var leftTextHeightSum = 0;
      var rightTextHeightSum = 0;
      labelSel.each(function(l) {
        var r = this.getBoundingClientRect();
        maxLabelWidth = Math.max(maxLabelWidth, r.width);
        if (this.style.textAnchor == 'end') {
          leftTextHeightSum += r.height;
        } else {
          rightTextHeightSum += r.height;
        }
      });

      var titleWidth = this.querySelector(
          '#title').getBoundingClientRect().width;
      var margin = this.margin;
      var marginWidth = margin.left + margin.right;
      var marginHeight = margin.top + margin.bottom;
      return {
        width: Math.max(2 * MIN_RADIUS + 2 * maxLabelWidth,
                        titleWidth * 1.1) + marginWidth,
        height: marginHeight + Math.max(2 * MIN_RADIUS,
                                        leftTextHeightSum,
                                        rightTextHeightSum) * 1.25
      };
    },

    getLegendKeys_: function() {
      // This class creates its own legend, instead of using ChartBase.
      return undefined;
    },

    updateScales_: function(width, height) {
      if (this.data_ === undefined)
        return;
    },

    updateContents_: function() {
      ChartBase.prototype.updateContents_.call(this);
      if (!this.data_)
        return;

      var width = this.chartAreaSize.width;
      var height = this.chartAreaSize.height;
      var radius = Math.max(MIN_RADIUS, Math.min(width, height) / 2);

      d3.select(this.pieGroup_).attr(
          'transform',
          'translate(' + width / 2 + ',' + height / 2 + ')');

      // Bind the pie layout to its data
      var pieLayout = d3.layout.pie()
        .value(function(d) { return d.value; })
        .sort(null);

      var piePathsSel = d3.select(this.pathsGroup_)
          .datum(this.data_)
          .selectAll('path')
          .data(pieLayout);

      function midAngle(d) {
        return d.startAngle + (d.endAngle - d.startAngle) / 2;
      }

      var pathsArc = d3.svg.arc()
        .innerRadius(0)
        .outerRadius(radius - 30);

      var valueLabelArc = d3.svg.arc()
        .innerRadius(radius - 100)
        .outerRadius(radius - 30);

      var lineBeginArc = d3.svg.arc()
        .innerRadius(radius - 50)
        .outerRadius(radius - 50);

      var lineEndArc = d3.svg.arc()
        .innerRadius(radius)
        .outerRadius(radius);

      // Paths.
      piePathsSel.enter().append('path')
        .attr('class', 'arc')
        .attr('fill', function(d, i) {
            var origData = this.data_[i];
            var highlighted = (origData.label ===
                               this.currentHighlightedLegendKey);
            return getColorOfKey(origData.label, highlighted);
          }.bind(this))
        .attr('d', pathsArc)
        .on('click', function(d, i) {
            var origData = this.data_[i];
            if (origData.onClick)
              origData.onClick(d, i);
            d3.event.stopPropagation();
          }.bind(this))
        .on('mouseenter', function(d, i) {
            var origData = this.data_[i];
            this.pushTempHighlightedLegendKey(origData.label);
          }.bind(this))
        .on('mouseleave', function(d, i) {
            var origData = this.data_[i];
            this.popTempHighlightedLegendKey(origData.label);
          }.bind(this));

      // Value labels.
      piePathsSel.enter().append('text')
        .attr('class', 'arc-text')
        .attr('transform', function(d) {
            return 'translate(' + valueLabelArc.centroid(d) + ')';
          })
        .attr('dy', '.35em')
        .style('text-anchor', 'middle')
        .text(function(d, i) {
            var origData = this.data_[i];
            if (origData.valueText === undefined)
              return '';

            if (d.endAngle - d.startAngle < 0.4)
              return '';
            return origData.valueText;
          }.bind(this));

      piePathsSel.exit().remove();

      // Labels.
      var labelSel = d3.select(this.labelsGroup_).selectAll('.label')
          .data(pieLayout(this.data_));
      labelSel.enter()
          .append('text')
          .attr('class', 'label')
          .attr('dy', '.35em');

      labelSel.text(function(d) {
        return d.data.label;
      });
      labelSel.attr('transform', function(d) {
        var pos = lineEndArc.centroid(d);
        pos[0] = radius * (midAngle(d) < Math.PI ? 1 : -1);
        return 'translate(' + pos + ')';
      });
      labelSel.style('text-anchor', function(d) {
        return midAngle(d) < Math.PI ? 'start' : 'end';
      });

      // Lines.
      var lineSel = d3.select(this.linesGroup_).selectAll('.line')
          .data(pieLayout(this.data_));
      lineSel.enter()
        .append('polyline')
        .attr('class', 'line')
        .attr('dy', '.35em');
      lineSel.attr('points', function(d) {
        var pos = lineEndArc.centroid(d);
        pos[0] = radius * 0.95 * (midAngle(d) < Math.PI ? 1 : -1);
        return [lineBeginArc.centroid(d), lineEndArc.centroid(d), pos];
      });
    },

    updateHighlight_: function() {
      ChartBase.prototype.updateHighlight_.call(this);
      // Update color of pie segments.
      var pathsGroupSel = d3.select(this.pathsGroup_);
      var that = this;
      pathsGroupSel.selectAll('.arc').each(function(d, i) {
        var origData = that.data_[i];
        var highlighted = origData.label == that.currentHighlightedLegendKey;
        var color = getColorOfKey(origData.label, highlighted);
        this.style.fill = color;
      });
    }
  };

  return {
    PieChart: PieChart
  };
});
<commit_msg>Elide long titles in pie_chart<commit_after>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

'use strict';

tvcm.require('tvcm.range');
tvcm.require('tvcm.ui.d3');
tvcm.require('tvcm.ui.dom_helpers');
tvcm.require('tvcm.ui.chart_base');

tvcm.requireStylesheet('tvcm.ui.pie_chart');

tvcm.exportTo('tvcm.ui', function() {
  var ChartBase = tvcm.ui.ChartBase;
  var getColorOfKey = tvcm.ui.getColorOfKey;

  var MIN_RADIUS = 100;

  /**
   * @constructor
   */
  var PieChart = tvcm.ui.define('pie-chart', ChartBase);

  PieChart.prototype = {
    __proto__: ChartBase.prototype,

    decorate: function() {
      ChartBase.prototype.decorate.call(this);
      this.classList.add('pie-chart');

      this.data_ = undefined;
      this.seriesKeys_ = undefined;

      var chartAreaSel = d3.select(this.chartAreaElement);
      var pieGroupSel = chartAreaSel.append('g')
        .attr('class', 'pie-group');
      this.pieGroup_ = pieGroupSel.node();

      this.pathsGroup_ = pieGroupSel.append('g')
        .attr('class', 'paths')
        .node();
      this.labelsGroup_ = pieGroupSel.append('g')
        .attr('class', 'labels')
        .node();
      this.linesGroup_ = pieGroupSel.append('g')
        .attr('class', 'lines')
        .node();
    },

    get data() {
      return this.data_;
    },

    /**
     * @param {Array} data Data for the chart, where each element in the array
     * must be of the form {label: str, value: number}.
     */
    set data(data) {
      if (data !== undefined) {
        // Figure out the label values in the data set. E.g. from
        //   [{label: 'a', ...}, {label: 'b', ...}]
        // we would commpute ['a', 'y']. These become the series keys.
        var seriesKeys = [];
        var seenSeriesKeys = {};
        data.forEach(function(d) {
          var k = d.label;
          if (seenSeriesKeys[k])
            throw new Error('Label ' + k + ' has been used already');
          seriesKeys.push(k);
          seenSeriesKeys[k] = true;
        }, this);
        this.seriesKeys_ = seriesKeys;
      } else {
        this.seriesKeys_ = undefined;
      }
      this.data_ = data;
      this.updateContents_();
    },

    get margin() {
      var margin = {top: 0, right: 0, bottom: 0, left: 0};
      if (this.chartTitle_)
        margin.top += 40;
      return margin;
    },

    getMinSize: function() {
      if (!tvcm.ui.isElementAttachedToDocument(this))
        throw new Error('Cannot measure when unattached');
      this.updateContents_();

      var labelSel = d3.select(this.labelsGroup_).selectAll('.label');
      var maxLabelWidth = -Number.MAX_VALUE;
      var leftTextHeightSum = 0;
      var rightTextHeightSum = 0;
      labelSel.each(function(l) {
        var r = this.getBoundingClientRect();
        maxLabelWidth = Math.max(maxLabelWidth, r.width);
        if (this.style.textAnchor == 'end') {
          leftTextHeightSum += r.height;
        } else {
          rightTextHeightSum += r.height;
        }
      });

      var titleWidth = this.querySelector(
          '#title').getBoundingClientRect().width;
      var margin = this.margin;
      var marginWidth = margin.left + margin.right;
      var marginHeight = margin.top + margin.bottom;
      return {
        width: Math.max(2 * MIN_RADIUS + 2 * maxLabelWidth,
                        titleWidth * 1.1) + marginWidth,
        height: marginHeight + Math.max(2 * MIN_RADIUS,
                                        leftTextHeightSum,
                                        rightTextHeightSum) * 1.25
      };
    },

    getLegendKeys_: function() {
      // This class creates its own legend, instead of using ChartBase.
      return undefined;
    },

    updateScales_: function(width, height) {
      if (this.data_ === undefined)
        return;
    },

    updateContents_: function() {
      ChartBase.prototype.updateContents_.call(this);
      if (!this.data_)
        return;

      var width = this.chartAreaSize.width;
      var height = this.chartAreaSize.height;
      var radius = Math.max(MIN_RADIUS, Math.min(width, height) / 2);

      d3.select(this.pieGroup_).attr(
          'transform',
          'translate(' + width / 2 + ',' + height / 2 + ')');

      // Bind the pie layout to its data
      var pieLayout = d3.layout.pie()
        .value(function(d) { return d.value; })
        .sort(null);

      var piePathsSel = d3.select(this.pathsGroup_)
          .datum(this.data_)
          .selectAll('path')
          .data(pieLayout);

      function midAngle(d) {
        return d.startAngle + (d.endAngle - d.startAngle) / 2;
      }

      var pathsArc = d3.svg.arc()
        .innerRadius(0)
        .outerRadius(radius - 30);

      var valueLabelArc = d3.svg.arc()
        .innerRadius(radius - 100)
        .outerRadius(radius - 30);

      var lineBeginArc = d3.svg.arc()
        .innerRadius(radius - 50)
        .outerRadius(radius - 50);

      var lineEndArc = d3.svg.arc()
        .innerRadius(radius)
        .outerRadius(radius);

      // Paths.
      piePathsSel.enter().append('path')
        .attr('class', 'arc')
        .attr('fill', function(d, i) {
            var origData = this.data_[i];
            var highlighted = (origData.label ===
                               this.currentHighlightedLegendKey);
            return getColorOfKey(origData.label, highlighted);
          }.bind(this))
        .attr('d', pathsArc)
        .on('click', function(d, i) {
            var origData = this.data_[i];
            if (origData.onClick)
              origData.onClick(d, i);
            d3.event.stopPropagation();
          }.bind(this))
        .on('mouseenter', function(d, i) {
            var origData = this.data_[i];
            this.pushTempHighlightedLegendKey(origData.label);
          }.bind(this))
        .on('mouseleave', function(d, i) {
            var origData = this.data_[i];
            this.popTempHighlightedLegendKey(origData.label);
          }.bind(this));

      // Value labels.
      piePathsSel.enter().append('text')
        .attr('class', 'arc-text')
        .attr('transform', function(d) {
            return 'translate(' + valueLabelArc.centroid(d) + ')';
          })
        .attr('dy', '.35em')
        .style('text-anchor', 'middle')
        .text(function(d, i) {
            var origData = this.data_[i];
            if (origData.valueText === undefined)
              return '';

            if (d.endAngle - d.startAngle < 0.4)
              return '';
            return origData.valueText;
          }.bind(this));

      piePathsSel.exit().remove();

      // Labels.
      var labelSel = d3.select(this.labelsGroup_).selectAll('.label')
          .data(pieLayout(this.data_));
      labelSel.enter()
          .append('text')
          .attr('class', 'label')
          .attr('dy', '.35em');

      labelSel.text(function(d) {
        if (d.data.label.length > 40)
          return d.data.label.substr(0, 40) + '...';
        return d.data.label;
      });
      labelSel.attr('transform', function(d) {
        var pos = lineEndArc.centroid(d);
        pos[0] = radius * (midAngle(d) < Math.PI ? 1 : -1);
        return 'translate(' + pos + ')';
      });
      labelSel.style('text-anchor', function(d) {
        return midAngle(d) < Math.PI ? 'start' : 'end';
      });

      // Lines.
      var lineSel = d3.select(this.linesGroup_).selectAll('.line')
          .data(pieLayout(this.data_));
      lineSel.enter()
        .append('polyline')
        .attr('class', 'line')
        .attr('dy', '.35em');
      lineSel.attr('points', function(d) {
        var pos = lineEndArc.centroid(d);
        pos[0] = radius * 0.95 * (midAngle(d) < Math.PI ? 1 : -1);
        return [lineBeginArc.centroid(d), lineEndArc.centroid(d), pos];
      });
    },

    updateHighlight_: function() {
      ChartBase.prototype.updateHighlight_.call(this);
      // Update color of pie segments.
      var pathsGroupSel = d3.select(this.pathsGroup_);
      var that = this;
      pathsGroupSel.selectAll('.arc').each(function(d, i) {
        var origData = that.data_[i];
        var highlighted = origData.label == that.currentHighlightedLegendKey;
        var color = getColorOfKey(origData.label, highlighted);
        this.style.fill = color;
      });
    }
  };

  return {
    PieChart: PieChart
  };
});
<|endoftext|>


<commit_before>'use strict';

const AWS = require('aws-sdk');
const zlib = require('zlib');
const region = process.env.AWS_REGION || 'us-west-2';
const dynamo = new AWS.DynamoDB({region: region});
const sqs = new AWS.SQS({region: region});

const userCountsLib = require('./lib/userCounts');
const overallCountsLib = require('./lib/overallCounts');

module.exports = {};
module.exports.getChildren = getChildren;
module.exports.mergeChildren = mergeChildren;

exports.handler = (event, context, callback) => {
    processNext(event, callback);
};

function processNext(context, callback) {
    getMessage(context)
        .then(getChildren)
        .then(mergeChildren)
        .then(packageValues)
        .then(writeToDynamo)
        .then(deleteMessage)
        .then(() => {
            processNext(context, callback);
        })
        .catch((err) => {
            if (err.no_messages) {
                // retries or concurrency checks here in the future
                return callback(null);
            } else {
                err.context = context;
                console.error(err);
                return callback(err);
            }
        });
}

function getMessage(context) {
    return new Promise((resolve, reject) => {
        if (context.source) {
            if (context.source === 'trigger.perTenMin') {
                context.queue = process.env.perTenMinQueue;
            } else {
                context.queue = process.env.perMinQueue;
            }
        } else {
            return reject(new Error('missing source'));
        }

        sqs.receiveMessage({
            QueueUrl: context.queue,
            VisibilityTimeout: 10,
            WaitTimeSeconds: 20
        }, (err, data) => {
            if (err) return reject(err);
            if (!data.Messages) return reject({no_messages: true});

            context.job = JSON.parse(data.Messages[0].Body);
            context.job.ReceiptHandle = data.Messages[0].ReceiptHandle;

            resolve(context);
        });
    });
}

function deleteMessage(context) {
    return new Promise((resolve, reject) => {
        sqs.deleteMessage({
            QueueUrl: context.queue,
            ReceiptHandle: context.job.ReceiptHandle
        }, (err, data) => {
            if (err) return reject(err);
            delete context.job;
            resolve(context);
        });
    });
}

function getChildren(context) {
    // get all the children for the given parent

    return new Promise((resolve, reject) => {
        // all jobs want these things for now, that might change
        const projExpression = ['#SEQUENCE', '#OVERALLCOUNTS'];
        const xprsnAttrNames = {
            '#PARENT': 'parent',
            '#OVERALLCOUNTS': 'overallCounts',
            '#SEQUENCE': 'sequence'
        };

        if (context.job.jobType === 'minute' ||
            context.job.jobType === 'hour') {
            projExpression.push('#USERCOUNTS');
            xprsnAttrNames['#USERCOUNTS'] = 'userCounts';
        }

        dynamo.query({
            TableName: process.env.MainTable,
            Select: 'SPECIFIC_ATTRIBUTES',
            KeyConditionExpression: '#PARENT = :parent',
            ProjectionExpression: projExpression.join(', '),
            ExpressionAttributeNames: xprsnAttrNames,
            ExpressionAttributeValues: {
                ':parent': {S: context.job.key}
            }
        }, (err, data) => {
            if (err) return reject(err);
            context.job.children = data.Items;
            resolve(context);
        });
    });
}

function mergeChildren(context) {
    // merges children into various formats for the given time period
    // minutes contain scalar values
    // everything else contains arrays, at various resolutions of minutely totals

    if (context.job.jobType === 'minute') {
        let mergedUsers = userCountsLib.mergeTotals(context.job.children);
        mergedUsers = userCountsLib.collapseTotals(mergedUsers);

        let mergedOverall = overallCountsLib.mergeTotals(context.job.children);
        mergedOverall = overallCountsLib.collapseTotals(mergedOverall);

        context.job.data = {
            userCounts: mergedUsers,
            overallCounts: mergedOverall
        };
    }

    if (context.job.jobType === 'hour') {
        let overallArray = overallCountsLib.arrayMinuteTotals(context.job.children);
        let userArray = userCountsLib.arrayMinuteTotals(context.job.children);

        context.job.data = {
            userCounts: userArray,
            overallCounts: overallArray
        };
    }

    delete context.job.children;
    return Promise.resolve(context);
}

function packageValues(context) {
    // pack up data for dynamo

    if (context.job.data.userCounts) {
        context.job.data.userCounts = {
            B: zlib.gzipSync(JSON.stringify(context.job.data.userCounts))
        };
    }

    if (context.job.data.overallCounts) {
        context.job.data.overallCounts = {
            B: zlib.gzipSync(JSON.stringify(context.job.data.overallCounts))
        };
    }

    return context;
}

function writeToDynamo(context) {
    // dynamically write all data

    return new Promise((resolve, reject) => {
        const attrs = [];
        for (const attr in context.job.data) {
            attrs.push(attr);
        }

        const attrNames = {};
        const updateExpression = [];
        const attrValues = {};

        attrs.forEach(attr => {
            const subName = '#' + attr.toUpperCase();
            const subValue = ':' + attr;
            attrNames[subName] = attr;
            updateExpression.push(subName + ' = ' + subValue);
            attrValues[subValue] = context.job.data[attr];
        });

        // come up with a better way of modifying parent and sequence length
        // like actually using Date(), negative slices feel sketch
        dynamo.updateItem({
            TableName: process.env.MainTable,
            Key: {
                parent: {S: context.job.key.slice(0, -3)},
                sequence: {N: context.job.key.slice(-2)}
            },
            UpdateExpression: 'SET ' + updateExpression.join(', '),
            ExpressionAttributeNames: attrNames,
            ExpressionAttributeValues: attrValues
        }, (err, data) => {
            if (err) return reject(err);
            resolve(context);
        });
    });
}
<commit_msg>Remove testing stuff<commit_after>'use strict';

const AWS = require('aws-sdk');
const zlib = require('zlib');
const region = process.env.AWS_REGION || 'us-west-2';
const dynamo = new AWS.DynamoDB({region: region});
const sqs = new AWS.SQS({region: region});

const userCountsLib = require('./lib/userCounts');
const overallCountsLib = require('./lib/overallCounts');

exports.handler = (event, context, callback) => {
    processNext(event, callback);
};

function processNext(context, callback) {
    getMessage(context)
        .then(getChildren)
        .then(mergeChildren)
        .then(packageValues)
        .then(writeToDynamo)
        .then(deleteMessage)
        .then(() => {
            processNext(context, callback);
        })
        .catch((err) => {
            if (err.no_messages) {
                // retries or concurrency checks here in the future
                return callback(null);
            } else {
                err.context = context;
                console.error(err);
                return callback(err);
            }
        });
}

function getMessage(context) {
    return new Promise((resolve, reject) => {
        if (context.source) {
            if (context.source === 'trigger.perTenMin') {
                context.queue = process.env.perTenMinQueue;
            } else {
                context.queue = process.env.perMinQueue;
            }
        } else {
            return reject(new Error('missing source'));
        }

        sqs.receiveMessage({
            QueueUrl: context.queue,
            VisibilityTimeout: 10,
            WaitTimeSeconds: 20
        }, (err, data) => {
            if (err) return reject(err);
            if (!data.Messages) return reject({no_messages: true});

            context.job = JSON.parse(data.Messages[0].Body);
            context.job.ReceiptHandle = data.Messages[0].ReceiptHandle;

            resolve(context);
        });
    });
}

function deleteMessage(context) {
    return new Promise((resolve, reject) => {
        sqs.deleteMessage({
            QueueUrl: context.queue,
            ReceiptHandle: context.job.ReceiptHandle
        }, (err, data) => {
            if (err) return reject(err);
            delete context.job;
            resolve(context);
        });
    });
}

function getChildren(context) {
    // get all the children for the given parent

    return new Promise((resolve, reject) => {
        // all jobs want these things for now, that might change
        const projExpression = ['#SEQUENCE', '#OVERALLCOUNTS'];
        const xprsnAttrNames = {
            '#PARENT': 'parent',
            '#OVERALLCOUNTS': 'overallCounts',
            '#SEQUENCE': 'sequence'
        };

        if (context.job.jobType === 'minute' ||
            context.job.jobType === 'hour') {
            projExpression.push('#USERCOUNTS');
            xprsnAttrNames['#USERCOUNTS'] = 'userCounts';
        }

        dynamo.query({
            TableName: process.env.MainTable,
            Select: 'SPECIFIC_ATTRIBUTES',
            KeyConditionExpression: '#PARENT = :parent',
            ProjectionExpression: projExpression.join(', '),
            ExpressionAttributeNames: xprsnAttrNames,
            ExpressionAttributeValues: {
                ':parent': {S: context.job.key}
            }
        }, (err, data) => {
            if (err) return reject(err);
            context.job.children = data.Items;
            resolve(context);
        });
    });
}

function mergeChildren(context) {
    // merges children into various formats for the given time period
    // minutes contain scalar values
    // everything else contains arrays, at various resolutions of minutely totals

    if (context.job.jobType === 'minute') {
        let mergedUsers = userCountsLib.mergeTotals(context.job.children);
        mergedUsers = userCountsLib.collapseTotals(mergedUsers);

        let mergedOverall = overallCountsLib.mergeTotals(context.job.children);
        mergedOverall = overallCountsLib.collapseTotals(mergedOverall);

        context.job.data = {
            userCounts: mergedUsers,
            overallCounts: mergedOverall
        };
    }

    if (context.job.jobType === 'hour') {
        let overallArray = overallCountsLib.arrayMinuteTotals(context.job.children);
        let userArray = userCountsLib.arrayMinuteTotals(context.job.children);

        context.job.data = {
            userCounts: userArray,
            overallCounts: overallArray
        };
    }

    delete context.job.children;
    return Promise.resolve(context);
}

function packageValues(context) {
    // pack up data for dynamo

    if (context.job.data.userCounts) {
        context.job.data.userCounts = {
            B: zlib.gzipSync(JSON.stringify(context.job.data.userCounts))
        };
    }

    if (context.job.data.overallCounts) {
        context.job.data.overallCounts = {
            B: zlib.gzipSync(JSON.stringify(context.job.data.overallCounts))
        };
    }

    return context;
}

function writeToDynamo(context) {
    // dynamically write all data

    return new Promise((resolve, reject) => {
        const attrs = [];
        for (const attr in context.job.data) {
            attrs.push(attr);
        }

        const attrNames = {};
        const updateExpression = [];
        const attrValues = {};

        attrs.forEach(attr => {
            const subName = '#' + attr.toUpperCase();
            const subValue = ':' + attr;
            attrNames[subName] = attr;
            updateExpression.push(subName + ' = ' + subValue);
            attrValues[subValue] = context.job.data[attr];
        });

        // come up with a better way of modifying parent and sequence length
        // like actually using Date(), negative slices feel sketch
        dynamo.updateItem({
            TableName: process.env.MainTable,
            Key: {
                parent: {S: context.job.key.slice(0, -3)},
                sequence: {N: context.job.key.slice(-2)}
            },
            UpdateExpression: 'SET ' + updateExpression.join(', '),
            ExpressionAttributeNames: attrNames,
            ExpressionAttributeValues: attrValues
        }, (err, data) => {
            if (err) return reject(err);
            resolve(context);
        });
    });
}
<|endoftext|>


<commit_before>

<commit_msg>add location to maps<commit_after>

<|endoftext|>


<commit_before>var OpenStreetMap_BlackAndWhite = L.tileLayer('http://{s}.tiles.wmflabs.org/bw-mapnik/{z}/{x}/{y}.png', {
	maxZoom: 18,
	attribution: '© OpenStreetMap'
});

var Stamen_Watercolor = L.tileLayer('https://stamen-tiles-{s}.a.ssl.fastly.net/watercolor/{z}/{x}/{y}.{ext}', {
	attribution: 'Map tiles by Stamen Design, CC BY 3.0 — Map data © OpenStreetMap',
	subdomains: 'abcd',
	minZoom: 1,
	maxZoom: 16,
	ext: 'png'
});

var Stamen_Toner = L.tileLayer('https://stamen-tiles-{s}.a.ssl.fastly.net/toner/{z}/{x}/{y}.{ext}', {
	attribution: 'Map tiles by Stamen Design, CC BY 3.0 — Map data © OpenStreetMap',
	subdomains: 'abcd',
	minZoom: 0,
	maxZoom: 20,
	ext: 'png'
});

var OpenTopoMap = L.tileLayer('https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png', {
	maxZoom: 17,
	attribution: 'Map data: © OpenStreetMap, SRTM | Map style: © OpenTopoMap (CC-BY-SA)'
});

// popdns - layer to show Population Density
var popdns = new L.layerGroup();
// rnweng - layer to show Renewable Energy Goals
var rnweng = new L.layerGroup();
// quake - layer to show quakes
var quake = new L.layerGroup();

var map = L.map('map', {
    center: [37.8, -96],
    zoom: 4,
    layers: [OpenStreetMap_BlackAndWhite]
});

var baseLayers = {
    "OSM B&W" : OpenStreetMap_BlackAndWhite,
    "Stamen Toner" : Stamen_Toner,
    "Stamen Watercolor" : Stamen_Watercolor,
    "Terrain Tiles" : OpenTopoMap

};

var overlays = {
    "Population Density": popdns,
    "State Renewable" : rnweng,
    "Earthquakes" : quake
};

var options = {
    "position" : 'topright',
    "collapsed" : false,
    "autoZIndex" : true
};
L.control.layers(baseLayers, overlays, options).addTo(map);

// ----------------------- Map Control Event Handling ------------------------------

map.on('overlayadd', function (eventLayer) {
    // Switch to the Population legendPopDensity...
    switch(eventLayer.name) {
        case 'Population Density':
            infoPopDensity.addTo(this);
            legendPopDensity.addTo(this);
            geojson.addTo(this);
            map.attributionControl.addAttribution(censusAttrib);
            break;
        case 'State Renewable':
            infoRnwEng.addTo(this);
            geojsonRnwEng.addTo(this);
            legendRnwEng.addTo(this);
            map.attributionControl.addAttribution(rnwengAttrib);
            break;
        case 'Earthquakes':
            // ql is a GeoJSON layer created during page load...
            ql.addTo(this);
            map.attributionControl.addAttribution(quakeAttrib);
            break;
        default:
            break;
    }
});

map.on('overlayremove', function (eventLayer) {
    // Switch to the Population legendPopDensity...
    switch(eventLayer.name) {
        case 'Population Density':
            this.removeControl(infoPopDensity);
            this.removeControl(legendPopDensity);
            this.removeControl(geojson);
            map.attributionControl.removeAttribution(censusAttrib);
            break;
        case 'State Renewable':
            this.removeControl(infoRnwEng);
            this.removeControl(geojsonRnwEng);
            this.removeControl(legendRnwEng);
            map.attributionControl.removeAttribution(rnwengAttrib);
            break;
        case 'Earthquakes':
            this.removeControl(ql);
            map.attributionControl.removeAttribution(quakeAttrib);
            break;
        default:
            break;
    }

});

<commit_msg>updated tile fetch to https, had missed one<commit_after>var OpenStreetMap_BlackAndWhite = L.tileLayer('https://{s}.tiles.wmflabs.org/bw-mapnik/{z}/{x}/{y}.png', {
	maxZoom: 18,
	attribution: '© OpenStreetMap'
});

var Stamen_Watercolor = L.tileLayer('https://stamen-tiles-{s}.a.ssl.fastly.net/watercolor/{z}/{x}/{y}.{ext}', {
	attribution: 'Map tiles by Stamen Design, CC BY 3.0 — Map data © OpenStreetMap',
	subdomains: 'abcd',
	minZoom: 1,
	maxZoom: 16,
	ext: 'png'
});

var Stamen_Toner = L.tileLayer('https://stamen-tiles-{s}.a.ssl.fastly.net/toner/{z}/{x}/{y}.{ext}', {
	attribution: 'Map tiles by Stamen Design, CC BY 3.0 — Map data © OpenStreetMap',
	subdomains: 'abcd',
	minZoom: 0,
	maxZoom: 20,
	ext: 'png'
});

var OpenTopoMap = L.tileLayer('https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png', {
	maxZoom: 17,
	attribution: 'Map data: © OpenStreetMap, SRTM | Map style: © OpenTopoMap (CC-BY-SA)'
});

// popdns - layer to show Population Density
var popdns = new L.layerGroup();
// rnweng - layer to show Renewable Energy Goals
var rnweng = new L.layerGroup();
// quake - layer to show quakes
var quake = new L.layerGroup();

var map = L.map('map', {
    center: [37.8, -96],
    zoom: 4,
    layers: [OpenStreetMap_BlackAndWhite]
});

var baseLayers = {
    "OSM B&W" : OpenStreetMap_BlackAndWhite,
    "Stamen Toner" : Stamen_Toner,
    "Stamen Watercolor" : Stamen_Watercolor,
    "Terrain Tiles" : OpenTopoMap

};

var overlays = {
    "Population Density": popdns,
    "State Renewable" : rnweng,
    "Earthquakes" : quake
};

var options = {
    "position" : 'topright',
    "collapsed" : false,
    "autoZIndex" : true
};
L.control.layers(baseLayers, overlays, options).addTo(map);

// ----------------------- Map Control Event Handling ------------------------------

map.on('overlayadd', function (eventLayer) {
    // Switch to the Population legendPopDensity...
    switch(eventLayer.name) {
        case 'Population Density':
            infoPopDensity.addTo(this);
            legendPopDensity.addTo(this);
            geojson.addTo(this);
            map.attributionControl.addAttribution(censusAttrib);
            break;
        case 'State Renewable':
            infoRnwEng.addTo(this);
            geojsonRnwEng.addTo(this);
            legendRnwEng.addTo(this);
            map.attributionControl.addAttribution(rnwengAttrib);
            break;
        case 'Earthquakes':
            // ql is a GeoJSON layer created during page load...
            ql.addTo(this);
            map.attributionControl.addAttribution(quakeAttrib);
            break;
        default:
            break;
    }
});

map.on('overlayremove', function (eventLayer) {
    // Switch to the Population legendPopDensity...
    switch(eventLayer.name) {
        case 'Population Density':
            this.removeControl(infoPopDensity);
            this.removeControl(legendPopDensity);
            this.removeControl(geojson);
            map.attributionControl.removeAttribution(censusAttrib);
            break;
        case 'State Renewable':
            this.removeControl(infoRnwEng);
            this.removeControl(geojsonRnwEng);
            this.removeControl(legendRnwEng);
            map.attributionControl.removeAttribution(rnwengAttrib);
            break;
        case 'Earthquakes':
            this.removeControl(ql);
            map.attributionControl.removeAttribution(quakeAttrib);
            break;
        default:
            break;
    }

});

<|endoftext|>


<commit_before>const METRIC_NS = `ciscospark_widget_`;
const LOAD_START = `widget:ready`;

const metrics = {};
let metricsQueue = [];
const metricsCount = {};
/**
 * Temporarily save metric to sessionStorage
 * @param {string} key
 * @param  {any} data
 * @returns {null}
 */
export function saveTempMetric(key, data) {
  metrics[key] = data;
}

export function getTempMetric(key) {
  const data = metrics[key];
  return {key, data};
}

// Helpers for saving metrics to queue before Spark is ready to send metrics

export function saveMetricToQueue(key, data) {
  metricsQueue.push({key, data});
}

export function saveElapsedTimeToQueue(key) {
  const elapsedTime = getElapsedTime();
  saveMetricToQueue(key, elapsedTime);
}

export function sendMetricsInQueue(spark) {
  metricsQueue.forEach(({key, data}) => {
    sendPerfMetric({key, data}, spark);
  });
  metricsQueue = [];
}

/**
 * Immediately send metric
 * @param  {object} metric
 * @param  {string} metric.key
 * @param  {any} metric.data
 * @param  {object} spark
 * @returns {Promise}
 */
export function sendPerfMetric({key, data, fields, tags}, spark) {
  try {
    const [name, action] = key.split(`:`);

    const count = metricsCount[key];
    if (count) {
      metricsCount[key] = count + 1;
    }
    else {
      metricsCount[key] = 1;
    }

    const formattedData = {
      type: [`operational`],
      tags: Object.assign({
        action
      }, tags),
      fields: Object.assign({
        protocol: window.location.protocol,
        hostname: window.location.hostname,
        pathname: window.location.pathname,
        widgetVersion: process.env.REACT_CISCOSPARK_VERSION,
        jsSdkVersion: spark.version,
        iteration: metricsCount[key],
        data
      }, fields)
    };
    return spark.metrics.submitClientMetrics(`${METRIC_NS}${name}`, formattedData);
  }
  catch (e) {
    return console.warn(`clientMetrics: ${key} metrics was not sent`, e); // eslint-disable-line no-console
  }
}

/**
 * Send metric stored in session
 * @param  {string} key
 * @param  {object} spark
 * @returns {Promise}
 */
export function sendTempMetric(key, spark) {
  let metric = getTempMetric(key);
  metric = isNaN(metric) ? metric : Number(metric);
  return sendPerfMetric(metric, spark);
}

/**
 * Save start time
 * @param  {object} spark
 * @returns {null}
 */
export function saveAndSendLoadStart(spark) {
  const now = saveLoadStart();
  sendLoadStart(spark);
  return now;
}

/**
 * Send start time
 * @param  {object} spark
 * @returns {Promise}
 */
export function sendLoadStart(spark) {
  const data = getTempMetric(LOAD_START);
  return sendPerfMetric(data, spark);
}

/**
 * Save start time
 * @returns {number} now
 */
export function saveLoadStart() {
  const now = window.performance.now();
  saveTempMetric(LOAD_START, now);
  return now;
}

function getElapsedTime() {
  const now = window.performance.now();
  const start = getTempMetric(LOAD_START).data;
  return start && now - start;
}

/**
 * Save time elapsed for event
 * @type {type}
 */

export function saveElapsedTime(key) {
  const elapsedTime = getElapsedTime();
  saveTempMetric(key, elapsedTime);
}

/**
 * Send time from starting load
 * @param  {string} key
 * @param  {object} spark
 * @param  {object} fields
 * @returns {Promise}
 */
export function sendElapsedTimeMetric(key, spark, fields) {
  let elapsedTime = getElapsedTime();
  if (!elapsedTime) {
    saveAndSendLoadStart(spark);
    elapsedTime = 0;
  }
  return sendPerfMetric({key, data: elapsedTime, fields}, spark);
}

export function sendDurationMetric(key, start, end, spark) {
  const startMetric = getTempMetric(start).data;
  const endMetric = getTempMetric(end).data;
  return sendPerfMetric({key, data: endMetric - startMetric}, spark);
}
<commit_msg>fix(react-component-utils): Disable metrics<commit_after>const METRIC_NS = `ciscospark_widget_`; // eslint-disable-line no-unused-vars
const LOAD_START = `widget:ready`;

const metrics = {};
let metricsQueue = [];
const metricsCount = {}; // eslint-disable-line no-unused-vars
/**
 * Temporarily save metric to sessionStorage
 * @param {string} key
 * @param  {any} data
 * @returns {null}
 */
export function saveTempMetric(key, data) {
  metrics[key] = data;
}

export function getTempMetric(key) {
  const data = metrics[key];
  return {key, data};
}

// Helpers for saving metrics to queue before Spark is ready to send metrics

export function saveMetricToQueue(key, data) {
  metricsQueue.push({key, data});
}

export function saveElapsedTimeToQueue(key) {
  const elapsedTime = getElapsedTime();
  saveMetricToQueue(key, elapsedTime);
}

export function sendMetricsInQueue(spark) {
  metricsQueue.forEach(({key, data}) => {
    sendPerfMetric({key, data}, spark);
  });
  metricsQueue = [];
}

/**
 * Immediately send metric
 * @param  {object} metric
 * @param  {string} metric.key
 * @param  {any} metric.data
 * @param  {object} spark
 * @returns {Promise}
 */
export function sendPerfMetric({key, data, fields, tags}, spark) { // eslint-disable-line no-unused-vars
  // try {
  //   const [name, action] = key.split(`:`);
  //
  //   const count = metricsCount[key];
  //   if (count) {
  //     metricsCount[key] = count + 1;
  //   }
  //   else {
  //     metricsCount[key] = 1;
  //   }
  //
  //   const formattedData = {
  //     type: [`operational`],
  //     tags: Object.assign({
  //       action
  //     }, tags),
  //     fields: Object.assign({
  //       protocol: window.location.protocol,
  //       hostname: window.location.hostname,
  //       pathname: window.location.pathname,
  //       widgetVersion: process.env.REACT_CISCOSPARK_VERSION,
  //       jsSdkVersion: spark.version,
  //       iteration: metricsCount[key],
  //       data
  //     }, fields)
  //   };
  //   return spark.metrics.submitClientMetrics(`${METRIC_NS}${name}`, formattedData);
  // }
  // catch (e) {
  //   return console.warn(`clientMetrics: ${key} metrics was not sent`, e); // eslint-disable-line no-console
  // }
  return false;
}

/**
 * Send metric stored in session
 * @param  {string} key
 * @param  {object} spark
 * @returns {Promise}
 */
export function sendTempMetric(key, spark) {
  let metric = getTempMetric(key);
  metric = isNaN(metric) ? metric : Number(metric);
  return sendPerfMetric(metric, spark);
}

/**
 * Save start time
 * @param  {object} spark
 * @returns {null}
 */
export function saveAndSendLoadStart(spark) {
  const now = saveLoadStart();
  sendLoadStart(spark);
  return now;
}

/**
 * Send start time
 * @param  {object} spark
 * @returns {Promise}
 */
export function sendLoadStart(spark) {
  const data = getTempMetric(LOAD_START);
  return sendPerfMetric(data, spark);
}

/**
 * Save start time
 * @returns {number} now
 */
export function saveLoadStart() {
  const now = window.performance.now();
  saveTempMetric(LOAD_START, now);
  return now;
}

function getElapsedTime() {
  const now = window.performance.now();
  const start = getTempMetric(LOAD_START).data;
  return start && now - start;
}

/**
 * Save time elapsed for event
 * @type {type}
 */

export function saveElapsedTime(key) {
  const elapsedTime = getElapsedTime();
  saveTempMetric(key, elapsedTime);
}

/**
 * Send time from starting load
 * @param  {string} key
 * @param  {object} spark
 * @param  {object} fields
 * @returns {Promise}
 */
export function sendElapsedTimeMetric(key, spark, fields) {
  let elapsedTime = getElapsedTime();
  if (!elapsedTime) {
    saveAndSendLoadStart(spark);
    elapsedTime = 0;
  }
  return sendPerfMetric({key, data: elapsedTime, fields}, spark);
}

export function sendDurationMetric(key, start, end, spark) {
  const startMetric = getTempMetric(start).data;
  const endMetric = getTempMetric(end).data;
  return sendPerfMetric({key, data: endMetric - startMetric}, spark);
}
<|endoftext|>


<commit_before>const Glue = require('glue');
const ioc = require('electrolyte');
const handlebars = require('handlebars');
const manifestPromise = require('./manifest');
const bookshelf = require('./src/lib/bookshelf');
const logger = require('./src/lib/logger');

var options = {
  relativeTo: __dirname + '/src'
};

manifestPromise.then(manifest => {
  Glue.compose(manifest, options, async function(err, server) {
    if (err) {
      throw err;
    }

    server.auth.strategy('access_token', 'access_token', { token_type: 'access_token' });
    server.auth.strategy('client_credentials', 'access_token', { token_type: 'client_credentials' });
    server.auth.strategy('oidc_session', 'oidc_session');
    server.auth.strategy('email_token', 'email_token', {
      findToken: async id => {
        try {
          let token = await bookshelf.model('email_token')
            .forge({ token: id })
            .where('expires_at', '>', bookshelf.knex.fn.now())
            .fetch();
          if (!token) {
            token = await bookshelf.model('user_password_reset_token')
              .forge({ token })
              .where('expires_at', '>', bookshelf.knex.fn.now())
              .fetch();
          }
          return token;
        }
        catch (error){
          throw error;
        }
      },
      findUser: async(id) => {
        return await bookshelf.model('user').where({ id }).fetch();
      }
    });

    ioc.use(id => {
      if (id === 'server') {
        server['@literal'] = true;
        return server;
      }
    });

    // Configure templating engine for emails
    server.views({
      engines: {
        hbs: handlebars
      },
      relativeTo: __dirname,
      path: './templates',
      layoutPath: './templates/layout',
      layout: 'default',
    });

    // Register routes
    let routes;
    try {
      routes = [
        await ioc.create('api/api-routes'),
        await ioc.create('user/user-routes'),
      ];
    } catch(e) {
      server.log(['error'], e);
    }

    try {
      server.route([{
        method: 'GET',
        path: '/health-check',
        handler: (req, reply) => reply('all good'),
      }]);
      routes.forEach(routes => {
        server.route(routes);
      });

      server.start(function () {
        for (let i = 0; i < server.connections.length; i++) {
          const message = `${server.connections[i].info.protocol === 'https' ? 'SSL ' : ''}Server running at: ${server.connections[i].info.uri}`
          server.log(['info'], message);
        }
      });
    } catch (e) {
      server.log(['error'], e);
    }
  });
}).catch(e => {
  logger.error(e);
  process.exit(1);
});
<commit_msg>Change email token expired check to be in server.js<commit_after>const Glue = require('glue');
const ioc = require('electrolyte');
const handlebars = require('handlebars');
const manifestPromise = require('./manifest');
const bookshelf = require('./src/lib/bookshelf');
const logger = require('./src/lib/logger');

var options = {
  relativeTo: __dirname + '/src'
};

manifestPromise.then(manifest => {
  Glue.compose(manifest, options, async function(err, server) {
    if (err) {
      throw err;
    }

    server.auth.strategy('access_token', 'access_token', { token_type: 'access_token' });
    server.auth.strategy('client_credentials', 'access_token', { token_type: 'client_credentials' });
    server.auth.strategy('oidc_session', 'oidc_session');
    server.auth.strategy('email_token', 'email_token', {
      findToken: async id => {
        try {
          let token = await bookshelf.model('email_token')
            .forge({ token: id })
            .fetch();
          if (token && token.get('expires_at') < new Date()) {
            // Token is expired
            return false;
          }
          if (!token) {
            token = await bookshelf.model('user_password_reset_token')
              .forge({ token })
              .where('expires_at', '>', bookshelf.knex.fn.now())
              .fetch();
          }
          return token;
        }
        catch (error){
          throw error;
        }
      },
      findUser: async(id) => {
        return await bookshelf.model('user').where({ id }).fetch();
      }
    });

    ioc.use(id => {
      if (id === 'server') {
        server['@literal'] = true;
        return server;
      }
    });

    // Configure templating engine for emails
    server.views({
      engines: {
        hbs: handlebars
      },
      relativeTo: __dirname,
      path: './templates',
      layoutPath: './templates/layout',
      layout: 'default',
    });

    // Register routes
    let routes;
    try {
      routes = [
        await ioc.create('api/api-routes'),
        await ioc.create('user/user-routes'),
      ];
    } catch(e) {
      server.log(['error'], e);
    }

    try {
      server.route([{
        method: 'GET',
        path: '/health-check',
        handler: (req, reply) => reply('all good'),
      }]);
      routes.forEach(routes => {
        server.route(routes);
      });

      server.start(function () {
        for (let i = 0; i < server.connections.length; i++) {
          const message = `${server.connections[i].info.protocol === 'https' ? 'SSL ' : ''}Server running at: ${server.connections[i].info.uri}`
          server.log(['info'], message);
        }
      });
    } catch (e) {
      server.log(['error'], e);
    }
  });
}).catch(e => {
  logger.error(e);
  process.exit(1);
});
<|endoftext|>


<commit_before>var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var compress = require('compression');
var kue = require('kue');
var jobs = kue.createQueue({
  redis: 'redis://127.0.0.1:6379'
});

var slideshow = require('./../slideshow/slideshow');
var facebook = require('./../slideshow/facebook');

var serverSettings = {
  port: process.env.PORT || 3000
};

var app = express();
app.use(compress());
app.use(express.static(path.resolve('dist')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

/***************************
 * Routes
 * **************************/
app.post('/publish-slideshow', function(req, res) {
  var urls = req.body.urls;
  var token = req.body.token;
  var songPath = req.body.songPath;
  function createJob() {
    var job = jobs.create('slideshows', {
      token: token,
      songPath: songPath,
      urls: urls
    });
    job.on('complete', function (){
      console.log('Job', job.id, 'with token', job.data.token, 'is done');
    }).on('failed', function (){
      console.log('Job', job.id, 'with token', job.data.token, 'has failed');
      createJob()
    });
    job.save();
  }
  createJob()

  res.status(200).send(JSON.stringify({ data: 'all good in the hood' }));
});

app.get('*', function(req, res) {
  res.sendFile(path.resolve('dist/index.html'));
});

app.listen(serverSettings.port, function() {
  console.log('Server listening on port ' + serverSettings.port);
});
<commit_msg>updating route for publish slideshow<commit_after>var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var compress = require('compression');
var kue = require('kue');
var jobs = kue.createQueue({
  redis: 'redis://127.0.0.1:6379'
});

var slideshow = require('./../slideshow/slideshow');
var facebook = require('./../slideshow/facebook');

var serverSettings = {
  port: process.env.PORT || 3000
};

var app = express();
app.use(compress());
app.use(express.static(path.resolve('dist')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

/***************************
 * Routes
 * **************************/
app.post('/api/publish-slideshow', function(req, res) {
  var urls = req.body.urls;
  var token = req.body.token;
  var songPath = req.body.songPath;
  function createJob() {
    var job = jobs.create('slideshows', {
      token: token,
      songPath: songPath,
      urls: urls
    });
    job.on('complete', function (){
      console.log('Job', job.id, 'with token', job.data.token, 'is done');
    }).on('failed', function (){
      console.log('Job', job.id, 'with token', job.data.token, 'has failed');
      createJob()
    });
    job.save();
  }
  createJob()

  res.status(200).send(JSON.stringify({ data: 'all good in the hood' }));
});

app.get('*', function(req, res) {
  res.sendFile(path.resolve('dist/index.html'));
});

app.listen(serverSettings.port, function() {
  console.log('Server listening on port ' + serverSettings.port);
});
<|endoftext|>


<commit_before>// var $ = require('jquery');
// window.$ = $

window.jQuery = $ = require('jquery');
require('bootstrap/dist/js/bootstrap');
require('./js/jquery.easing.min');
require('./js/avatarSection');
var SnackBar = require('node-snackbar/dist/snackbar');

// WOW cloned from 'amd' branch of wowjs
var WOW = require('./node_modules/WOW/dist/wow.js');

$(document).ready(function(){
    $('a.page-scroll').bind('click', function(event) {
        var $anchor = $(this);
        $('html, body').stop().animate({
            scrollTop: ($($anchor.attr('href')).offset().top - 50)
        }, 1250, 'easeInOutExpo');
        event.preventDefault();
    });

    $('body').scrollspy({
        target: '.navbar-fixed-top',
        offset: 51
    });

    $('.navbar-collapse ul li a').click(function() {
        $('.navbar-toggle:visible').click();
    });

    $('#mainNav').affix({
        offset: {
            top: 100
        }
    });

    new WOW().init();

    $('.contact-form').on('submit', function(event){
        event.preventDefault();
        $.ajax({
            url: "/contact_email",
            type: "POST",
            data: {
                contact_name: $('.contact-name').val(),
                contact_email: $('.contact-email').val(),
                contact_message: $('.contact-message').val()
            }
        }).done(function (data, textStatus, jqXHR){
            console.log("success! : " + textStatus + ' ' + data.message);

            // WRITE SUCCESSFUL EMAIL LOGIC
            document.getElementById("contact-form").reset();

            SnackBar.show({
                text: data.message,
                textColor: "#f05f40",
                pos: "bottom-right",
                actionText: "Thanks!",
                actionTextColor: "#f05f40",
                backgroundColor: "#333",
                duration: 1100
             });

            console.log("Success finished!");

        }).fail(function (jqXHR, textStatus, errorThrown) {
            console.log(`Failed! At : ${textStatus}, ${errorThrown}, ${jqXHR}`);

            SnackBar.show({
                text: `${textStatus.toUpperCase()}! ${errorThrown}! Please try again later!`,
                textColor: "#f05f40",
                pos: "bottom-right",
                actionText: "Thanks!",
                actionTextColor: "#f05f40",
                backgroundColor: "#333",
                duration: 1500
             });
        });
    });

    $('.social-hide-a').on('click', function(e){
        e.preventDefault();
        // $('.roro').css({'transform': 'rotate(180deg)'});
        $('ul.social-icons').toggle({
            duration: 800,
            easing: 'easeInOutExpo',
            complete: function(){
                if($('.roro').css('transform') == 'none'){
                    $('.roro').css({'transform': 'rotate(180deg)'});
                } else {
                    $('.roro').css({'transform': ''});
                }
            }
        })
    })

});

// {
//     animation: true,
//     container: '.contact-submit',
//     content: data.message,
//     delay: { "show": 800, "hide": 200 },
//     html: false,
//     placement: 'right',
//     title: 'Thank you!'
// }
<commit_msg>Change WOW to wowjs<commit_after>// var $ = require('jquery');
// window.$ = $

window.jQuery = $ = require('jquery');
require('bootstrap/dist/js/bootstrap');
require('./js/jquery.easing.min');
require('./js/avatarSection');
var SnackBar = require('node-snackbar/dist/snackbar');

// WOW cloned from 'amd' branch of wowjs
var WOW = require('./node_modules/wowjs/dist/wow.js');

$(document).ready(function(){
    $('a.page-scroll').bind('click', function(event) {
        var $anchor = $(this);
        $('html, body').stop().animate({
            scrollTop: ($($anchor.attr('href')).offset().top - 50)
        }, 1250, 'easeInOutExpo');
        event.preventDefault();
    });

    $('body').scrollspy({
        target: '.navbar-fixed-top',
        offset: 51
    });

    $('.navbar-collapse ul li a').click(function() {
        $('.navbar-toggle:visible').click();
    });

    $('#mainNav').affix({
        offset: {
            top: 100
        }
    });

    new WOW().init();

    $('.contact-form').on('submit', function(event){
        event.preventDefault();
        $.ajax({
            url: "/contact_email",
            type: "POST",
            data: {
                contact_name: $('.contact-name').val(),
                contact_email: $('.contact-email').val(),
                contact_message: $('.contact-message').val()
            }
        }).done(function (data, textStatus, jqXHR){
            console.log("success! : " + textStatus + ' ' + data.message);

            // WRITE SUCCESSFUL EMAIL LOGIC
            document.getElementById("contact-form").reset();

            SnackBar.show({
                text: data.message,
                textColor: "#f05f40",
                pos: "bottom-right",
                actionText: "Thanks!",
                actionTextColor: "#f05f40",
                backgroundColor: "#333",
                duration: 1100
             });

            console.log("Success finished!");

        }).fail(function (jqXHR, textStatus, errorThrown) {
            console.log(`Failed! At : ${textStatus}, ${errorThrown}, ${jqXHR}`);

            SnackBar.show({
                text: `${textStatus.toUpperCase()}! ${errorThrown}! Please try again later!`,
                textColor: "#f05f40",
                pos: "bottom-right",
                actionText: "Thanks!",
                actionTextColor: "#f05f40",
                backgroundColor: "#333",
                duration: 1500
             });
        });
    });

    $('.social-hide-a').on('click', function(e){
        e.preventDefault();
        // $('.roro').css({'transform': 'rotate(180deg)'});
        $('ul.social-icons').toggle({
            duration: 800,
            easing: 'easeInOutExpo',
            complete: function(){
                if($('.roro').css('transform') == 'none'){
                    $('.roro').css({'transform': 'rotate(180deg)'});
                } else {
                    $('.roro').css({'transform': ''});
                }
            }
        })
    })

});

// {
//     animation: true,
//     container: '.contact-submit',
//     content: data.message,
//     delay: { "show": 800, "hide": 200 },
//     html: false,
//     placement: 'right',
//     title: 'Thank you!'
// }
<|endoftext|>


<commit_before>/*
 * Copyright 2013 BlackBerry Limited.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 */

var Application = {

    // Application Constructor
    initialize: function() {
        this.bindEvents();
    },

    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
    },

    // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the 'receivedEvent'
    // function, we must explicity call 'app.receivedEvent(...);'
    onDeviceReady: function() {
        Application.receivedEvent('deviceready');

        bb.init({
            actionBarDark: true,
            controlsDark: true,
            listsDark: false,

            // Fires "before" styling is applied and "before" the screen is inserted in the DOM
            onscreenready: function(element, id) {},

            // Fires "after" styling is applied and "after" the screen is inserted in the DOM
            ondomready: function(element, id) {
                blackberry.event.addEventListener("invoked", function(invocationInfo) {
                    printToLog("Handler start . . .");
                    if (invocationInfo.target) {
                        console.log(nvocationInfo.target);
                    }
                    if (invocationInfo.type) {
                        console.log(nvocationInfo.type);
                    }
                    if (invocationInfo.action) {
                        console.log(nvocationInfo.action);
                    }
                    if (invocationInfo.data) {
                        console.log(nvocationInfo.data);
                    }
                });

            }
        });

        // start the app
        bb.pushScreen('home.html', 'home');
    },

    // Update DOM on a Received Event
    receivedEvent: function(id) {
        console.log('Received Event: ' + id);
    }
};<commit_msg>fix errors.<commit_after>/*
 * Copyright 2013 BlackBerry Limited.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 */

var Application = {

    // Application Constructor
    initialize: function() {
        this.bindEvents();
    },

    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
    },

    // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the 'receivedEvent'
    // function, we must explicity call 'app.receivedEvent(...);'
    onDeviceReady: function() {
        Application.receivedEvent('deviceready');

        bb.init({
            actionBarDark: true,
            controlsDark: true,
            listsDark: false,

            // Fires "before" styling is applied and "before" the screen is inserted in the DOM
            onscreenready: function(element, id) {},

            // Fires "after" styling is applied and "after" the screen is inserted in the DOM
            ondomready: function(element, id) {
                blackberry.event.addEventListener("invoked", function(invocationInfo) {
                    console.log("Handler start . . .");
                    if (invocationInfo.target) {
                        console.log(invocationInfo.target);
                    }
                    if (invocationInfo.type) {
                        console.log(invocationInfo.type);
                    }
                    if (invocationInfo.action) {
                        console.log(invocationInfo.action);
                    }
                    if (invocationInfo.data) {
                        console.log(invocationInfo.data);
                    }
                });

            }
        });

        // start the app
        bb.pushScreen('home.html', 'home');
    },

    // Update DOM on a Received Event
    receivedEvent: function(id) {
        console.log('Received Event: ' + id);
    }
};
<|endoftext|>


<commit_before>/**
 * @class Oskari.mapframework.bundle.postprocessor.PostProcessorBundleInstance
 *
 * Used for highlighting wfs features on pageload etc. Calls other bundles to accomplish stuff
 * after everything has been loaded and started.
 *
 * See Oskari.mapframework.bundle.postprocessor.PostProcessorBundle for bundle definition.
 *
 */
Oskari.clazz.define("Oskari.mapframework.bundle.postprocessor.PostProcessorBundleInstance",

/**
 * @method create called automatically on construction
 * @static
 */
function() {
    this.sandbox = null;
}, {
    /**
     * @static
     * @property __name
     */
    __name : 'PostProcessor',
    /**
     * @method getName
     * @return {String} the name for the component
     */
    "getName" : function() {
        return this.__name;
    },
    /**
     * @method start
     * implements BundleInstance protocol start methdod
     */
    "start" : function() {
        var me = this;
        var sandbox = Oskari.$("sandbox");
        this.sandbox = sandbox;

        sandbox.register(this);
        if(this.state) {
            var hiliteLayerId = this.state.highlightFeatureLayerId;

            if(hiliteLayerId) {
                var isLoaded = sandbox.findMapLayerFromAllAvailable(hiliteLayerId) != null;
                if(isLoaded) {
                    this._highlightFeature(hiliteLayerId, this.state.highlightFeatureId);
                }
                else {
                    // layer not loaded ->
                    // register listening to 'MapLayerEvent' and let it trigger a retry
                    for(p in me.eventHandlers) {
                        sandbox.registerForEventByName(me, p);
                    }
                }
            }

        }
    },
    /**
     * @method _highlightFeature
     * @private
     * Adds the layer if its not yet selected
     * @param {String} layerId
     * @param {String/String[]} featureId single or array of feature ids to hilight
     */
    _highlightFeature : function(layerId, featureId) {
        if(featureId && layerId) {
            var layer = this.sandbox.findMapLayerFromAllAvailable(layerId);
            if(layer) {
                var builder = this.sandbox.getEventBuilder('WFSFeaturesSelectedEvent');
                var featureIdList = [];
                // check if the param is already an array
                if(Object.prototype.toString.call( featureId ) === '[object Array]' ) {
                    featureIdList = featureId;
                }
                else {
                    featureIdList.push(featureId);
                }
                var event = builder(featureIdList, layer);
                this.sandbox.notifyAll(event);

                var points = this.state.featurePoints;
                if(points) {
                    this._showPoints(points);
                }
            }
            else {
                this.sandbox.printWarn('Postprocessing failed for feature ' + featureId +
                ' and layer ' + layerId);
            }
        }
    },
    /**
     * @method _showPoints
     * @private
     * Sends a mapmoverequest to fit the points on the map viewport
     * @param {Object[]} points array of objects containing lon/lat properties
     */
    _showPoints : function(points) {
        var olPoints = new OpenLayers.Geometry.MultiPoint();
        var count = 0;
        for(; count < points.length; ++count) {
            var point = points[count];
            var olPoint = new OpenLayers.Geometry.Point(point.lat, point.lon);
            olPoints.addPoint(olPoint);
        }
        var bounds = olPoints.getBounds();
        var centroid = olPoints.getCentroid();

        var rb = this.sandbox.getRequestBuilder('MapMoveRequest');
        if(rb && count > 0) {
            if(count == 1) {
                // zoom to level 9 if a single point
                var req = rb(centroid.x, centroid.y, 9);
                this.sandbox.request(this, req);
            }
            else {
                var req = rb(centroid.x, centroid.y, bounds);
                this.sandbox.request(this, req);
            }
        }
    },
    /**
     * @method onEvent
     * @param {Oskari.mapframework.event.Event} event a Oskari event object
     * Event is handled forwarded to correct #eventHandlers if found or discarded if not.
     */
    onEvent : function(event) {

        var handler = this.eventHandlers[event.getName()];
        if(!handler) {
            return;
        }
        return handler.apply(this, [event]);
    },
    /**
     * @property {Object} eventHandlers
     * @static
     */
    eventHandlers : {
        /**
         * @method MapLayerEvent
         * If start has already campleted hilighting, this won't trigger, if not
         * this calls highlight no the selected target
         * @param {Oskari.mapframework.event.common.MapLayerEvent} event
         */
        'MapLayerEvent' : function(event) {
            // layerId in event is null for initial ajax load
            if('add' == event.getOperation() && !event.getLayerId()) {
                this._highlightFeature(this.state.highlightFeatureLayerId, this.state.highlightFeatureId);
            }
        }
    },
    /**
     * @method init
     * implements Module protocol init method - does nothing atm
     */
    "init" : function() {
        return null;
    },
    /**
     * @method update
     * implements BundleInstance protocol update method - does nothing atm
     */
    "update" : function() {

    },
    /**
     * @method stop
     * implements BundleInstance protocol stop method
     */
    "stop" : function() {
    }
}, {
    /**
     * @property {String[]} protocol
     * @static
     */
    "protocol" : ["Oskari.bundle.BundleInstance", 'Oskari.mapframework.module.Module']
});
<commit_msg>[PORTTISK-1151] map is moved to location based on feature points in postprocessor state and highlight is requested even if the layer is not loaded in to the system (as in published map it likely wont be)<commit_after>/**
 * @class Oskari.mapframework.bundle.postprocessor.PostProcessorBundleInstance
 *
 * Used for highlighting wfs features on pageload etc. Calls other bundles to accomplish stuff
 * after everything has been loaded and started.
 *
 * See Oskari.mapframework.bundle.postprocessor.PostProcessorBundle for bundle definition.
 *
 */
Oskari.clazz.define("Oskari.mapframework.bundle.postprocessor.PostProcessorBundleInstance",

/**
 * @method create called automatically on construction
 * @static
 */
function() {
    this.sandbox = null;
}, {
    /**
     * @static
     * @property __name
     */
    __name : 'PostProcessor',
    /**
     * @method getName
     * @return {String} the name for the component
     */
    "getName" : function() {
        return this.__name;
    },
    /**
     * @method start
     * implements BundleInstance protocol start methdod
     */
    "start" : function() {
        var me = this;
        var sandbox = Oskari.$("sandbox");
        this.sandbox = sandbox;

        sandbox.register(this);
        if(this.state) {
            var hiliteLayerId = this.state.highlightFeatureLayerId;
            this._highlightFeature(hiliteLayerId, this.state.highlightFeatureId);
        }
    },
    /**
     * @method _highlightFeature
     * @private
     * Adds the layer if its not yet selected
     * @param {String} layerId
     * @param {String/String[]} featureId single or array of feature ids to hilight
     */
    _highlightFeature : function(layerId, featureId) {
        if(featureId && layerId) {

            // move map to location
            var points = this.state.featurePoints;
            if(points) {
                this._showPoints(points);
            }

            // request for highlight image, note that the map must be in correct
            // location BEFORE this or we get a blank image
            var builder = this.sandbox.getEventBuilder('WFSFeaturesSelectedEvent');
            var featureIdList = [];
            // check if the param is already an array
            if(Object.prototype.toString.call( featureId ) === '[object Array]' ) {
                featureIdList = featureId;
            }
            else {
                featureIdList.push(featureId);
            }
            // create dummy layer since the real one might not be available and we only need it for id
            var dummyLayer = Oskari.clazz.create('Oskari.mapframework.domain.WfsLayer');
            dummyLayer.setId(layerId);
            var event = builder(featureIdList, dummyLayer);
            this.sandbox.notifyAll(event);
        }
    },
    /**
     * @method _showPoints
     * @private
     * Sends a mapmoverequest to fit the points on the map viewport
     * @param {Object[]} points array of objects containing lon/lat properties
     */
    _showPoints : function(points) {
        var olPoints = new OpenLayers.Geometry.MultiPoint();
        var count = 0;
        for(; count < points.length; ++count) {
            var point = points[count];
            var olPoint = new OpenLayers.Geometry.Point(point.lat, point.lon);
            olPoints.addPoint(olPoint);
        }
        var bounds = olPoints.getBounds();
        var centroid = olPoints.getCentroid();

        var rb = this.sandbox.getRequestBuilder('MapMoveRequest');
        if(rb && count > 0) {
            if(count == 1) {
                // zoom to level 9 if a single point
                var req = rb(centroid.x, centroid.y, 9);
                this.sandbox.request(this, req);
            }
            else {
                var req = rb(centroid.x, centroid.y, bounds);
                this.sandbox.request(this, req);
            }
        }
    },
    /**
     * @method onEvent
     * @param {Oskari.mapframework.event.Event} event a Oskari event object
     * Event is handled forwarded to correct #eventHandlers if found or discarded if not.
     */
    onEvent : function(event) {

        var handler = this.eventHandlers[event.getName()];
        if(!handler) {
            return;
        }
        return handler.apply(this, [event]);
    },
    /**
     * @property {Object} eventHandlers
     * @static
     */
    eventHandlers : {
        /**
         * @method MapLayerEvent
         * If start has already campleted hilighting, this won't trigger, if not
         * this calls highlight no the selected target
         * @param {Oskari.mapframework.event.common.MapLayerEvent} event
         */
        'MapLayerEvent' : function(event) {
            // layerId in event is null for initial ajax load
            if('add' == event.getOperation() && !event.getLayerId()) {
                this._highlightFeature(this.state.highlightFeatureLayerId, this.state.highlightFeatureId);
            }
        }
    },
    /**
     * @method init
     * implements Module protocol init method - does nothing atm
     */
    "init" : function() {
        return null;
    },
    /**
     * @method update
     * implements BundleInstance protocol update method - does nothing atm
     */
    "update" : function() {

    },
    /**
     * @method stop
     * implements BundleInstance protocol stop method
     */
    "stop" : function() {
    }
}, {
    /**
     * @property {String[]} protocol
     * @static
     */
    "protocol" : ["Oskari.bundle.BundleInstance", 'Oskari.mapframework.module.Module']
});
<|endoftext|>


<commit_before>import Webiny from 'Webiny';

class Fieldset extends Webiny.Ui.Component {

}

Fieldset.defaultProps = {
    renderer() {
        return (

{this.props.title}

{this.props.children}

        );
    }
};

export default Fieldset;
<commit_msg>Form fieldset component now supports icon prop<commit_after>import Webiny from 'Webiny';

class Fieldset extends Webiny.Ui.Component {

}

Fieldset.defaultProps = {
    renderer() {
        let icon = null;
        if (_.get(this.props, 'icon', false)) {
            icon = <Webiny.Ui.Components.Icon icon={this.props.icon}/>;
        }

        return (

{icon}{this.props.title}

{this.props.children}

        );
    }
};

export default Fieldset;
<|endoftext|>