<commit_before>/**
 * @author mrdoob / http://mrdoob.com/
 */

import { ArrayCamera } from '../../cameras/ArrayCamera.js';
import { EventDispatcher } from '../../core/EventDispatcher.js';
import { PerspectiveCamera } from '../../cameras/PerspectiveCamera.js';
import { Vector3 } from '../../math/Vector3.js';
import { Vector4 } from '../../math/Vector4.js';
import { WebGLAnimation } from '../webgl/WebGLAnimation.js';
import { WebXRController } from './WebXRController.js';

function WebXRManager( renderer, gl ) {

	var scope = this;

	var session = null;

	var framebufferScaleFactor = 1.0;

	var referenceSpace = null;
	var referenceSpaceType = 'local-floor';

	var pose = null;

	var controllers = [];
	var inputSourcesMap = new Map();

	//

	var cameraL = new PerspectiveCamera();
	cameraL.layers.enable( 1 );
	cameraL.viewport = new Vector4();

	var cameraR = new PerspectiveCamera();
	cameraR.layers.enable( 2 );
	cameraR.viewport = new Vector4();

	var cameraVR = new ArrayCamera( [ cameraL, cameraR ] );
	cameraVR.layers.enable( 1 );
	cameraVR.layers.enable( 2 );

	var _currentDepthNear = null;
	var _currentDepthFar = null;

	//

	this.enabled = false;

	this.isPresenting = false;

	this.getController = function ( index ) {

		var controller = controllers[ index ];

		if ( controller === undefined ) {

			controller = new WebXRController();
			controllers[ index ] = controller;

		}

		return controller.getTargetRaySpace();

	};

	this.getControllerGrip = function ( index ) {

		var controller = controllers[ index ];

		if ( controller === undefined ) {

			controller = new WebXRController();
			controllers[ index ] = controller;

		}

		return controller.getGripSpace();

	};

	//

	function onSessionEvent( event ) {

		var controller = inputSourcesMap.get( event.inputSource );

		if ( controller ) {

			controller.dispatchEvent( { type: event.type } );

		}

	}

	function onSessionEnd() {

		inputSourcesMap.forEach( function ( controller, inputSource ) {

			controller.disconnect( inputSource );

		} );

		inputSourcesMap.clear();

		//

		renderer.setFramebuffer( null );
		renderer.setRenderTarget( renderer.getRenderTarget() ); // Hack #15830
		animation.stop();

		scope.isPresenting = false;

		scope.dispatchEvent( { type: 'sessionend' } );

	}

	function onRequestReferenceSpace( value ) {

		referenceSpace = value;

		animation.setContext( session );
		animation.start();

		scope.isPresenting = true;

		scope.dispatchEvent( { type: 'sessionstart' } );

	}

	this.setFramebufferScaleFactor = function ( value ) {

		framebufferScaleFactor = value;

		if ( scope.isPresenting === true ) {

			console.warn( 'THREE.WebXRManager: Cannot change framebuffer scale while presenting XR content.' );

		}

	};

	this.setReferenceSpaceType = function ( value ) {

		referenceSpaceType = value;

		if ( scope.isPresenting === true ) {

			console.warn( 'THREE.WebXRManager: Cannot change reference space type while presenting XR content.' );

		}

	};

	this.getReferenceSpace = function () {

		return referenceSpace;

	};

	this.getSession = function () {

		return session;

	};

	this.setSession = function ( value ) {

		session = value;

		if ( session !== null ) {

			session.addEventListener( 'select', onSessionEvent );
			session.addEventListener( 'selectstart', onSessionEvent );
			session.addEventListener( 'selectend', onSessionEvent );
			session.addEventListener( 'squeeze', onSessionEvent );
			session.addEventListener( 'squeezestart', onSessionEvent );
			session.addEventListener( 'squeezeend', onSessionEvent );
			session.addEventListener( 'end', onSessionEnd );

			var attributes = gl.getContextAttributes();

			var layerInit = {
				antialias: attributes.antialias,
				alpha: attributes.alpha,
				depth: attributes.depth,
				stencil: attributes.stencil,
				framebufferScaleFactor: framebufferScaleFactor
			};

			// eslint-disable-next-line no-undef
			var baseLayer = new XRWebGLLayer( session, gl, layerInit );

			session.updateRenderState( { baseLayer: baseLayer } );

			session.requestReferenceSpace( referenceSpaceType ).then( onRequestReferenceSpace );

			//

			session.addEventListener( 'inputsourceschange', updateInputSources );

		}

	};

	function updateInputSources( event ) {

		var inputSources = session.inputSources;

		// Assign inputSources to available controllers

		for ( var i = 0; i < controllers.length; i ++ ) {

			inputSourcesMap.set( inputSources[ i ], controllers[ i ] );

		}

		// Notify disconnected

		for ( var i = 0; i < event.removed.length; i ++ ) {

			var inputSource = event.removed[ i ];
			var controller = inputSourcesMap.get( inputSource );

			if ( controller ) {

				controller.dispatchEvent( { type: 'disconnected', data: inputSource } );
				inputSourcesMap.delete( inputSource );

			}

		}

		// Notify connected

		for ( var i = 0; i < event.added.length; i ++ ) {

			var inputSource = event.added[ i ];
			var controller = inputSourcesMap.get( inputSource );

			if ( controller ) {

				controller.dispatchEvent( { type: 'connected', data: inputSource } );

			}

		}

	}

	//

	var cameraLPos = new Vector3();
	var cameraRPos = new Vector3();

	/**
	 * @author jsantell / https://www.jsantell.com/
	 *
	 * Assumes 2 cameras that are parallel and share an X-axis, and that
	 * the cameras' projection and world matrices have already been set.
	 * And that near and far planes are identical for both cameras.
	 * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
	 */
	function setProjectionFromUnion( camera, cameraL, cameraR ) {

		cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
		cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );

		var ipd = cameraLPos.distanceTo( cameraRPos );

		var projL = cameraL.projectionMatrix.elements;
		var projR = cameraR.projectionMatrix.elements;

		// VR systems will have identical far and near planes, and
		// most likely identical top and bottom frustum extents.
		// Use the left camera for these values.
		var near = projL[ 14 ] / ( projL[ 10 ] - 1 );
		var far = projL[ 14 ] / ( projL[ 10 ] + 1 );
		var topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
		var bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];

		var leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
		var rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
		var left = near * leftFov;
		var right = near * rightFov;

		// Calculate the new camera's position offset from the
		// left camera. xOffset should be roughly half `ipd`.
		var zOffset = ipd / ( - leftFov + rightFov );
		var xOffset = zOffset * - leftFov;

		// TODO: Better way to apply this offset?
		cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
		camera.translateX( xOffset );
		camera.translateZ( zOffset );
		camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
		camera.matrixWorldInverse.getInverse( camera.matrixWorld );

		// Find the union of the frustum values of the cameras and scale
		// the values so that the near plane's position does not change in world space,
		// although must now be relative to the new union camera.
		var near2 = near + zOffset;
		var far2 = far + zOffset;
		var left2 = left - xOffset;
		var right2 = right + ( ipd - xOffset );
		var top2 = topFov * far / far2 * near2;
		var bottom2 = bottomFov * far / far2 * near2;

		camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );

	}

	function updateCamera( camera, parent ) {

		if ( parent === null ) {

			camera.matrixWorld.copy( camera.matrix );

		} else {

			camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );

		}

		camera.matrixWorldInverse.getInverse( camera.matrixWorld );

	}

	this.getCamera = function ( camera ) {

		cameraVR.near = cameraR.near = cameraL.near = camera.near;
		cameraVR.far = cameraR.far = cameraL.far = camera.far;

		if ( _currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far ) {

			// Note that the new renderState won't apply until the next frame. See #18320

			session.updateRenderState( {
				depthNear: cameraVR.near,
				depthFar: cameraVR.far
			} );

			_currentDepthNear = cameraVR.near;
			_currentDepthFar = cameraVR.far;

		}

		var parent = camera.parent;
		var cameras = cameraVR.cameras;

		updateCamera( cameraVR, parent );

		for ( var i = 0; i < cameras.length; i ++ ) {

			updateCamera( cameras[ i ], parent );

		}

		// update camera and its children

		camera.matrixWorld.copy( cameraVR.matrixWorld );

		var children = camera.children;

		for ( var i = 0, l = children.length; i < l; i ++ ) {

			children[ i ].updateMatrixWorld( true );

		}

		setProjectionFromUnion( cameraVR, cameraL, cameraR );

		return cameraVR;

	};

	// Animation Loop

	var onAnimationFrameCallback = null;

	function onAnimationFrame( time, frame ) {

		pose = frame.getViewerPose( referenceSpace );

		if ( pose !== null ) {

			var views = pose.views;
			var baseLayer = session.renderState.baseLayer;

			renderer.setFramebuffer( baseLayer.framebuffer );

			for ( var i = 0; i < views.length; i ++ ) {

				var view = views[ i ];
				var viewport = baseLayer.getViewport( view );

				var camera = cameraVR.cameras[ i ];
				camera.matrix.fromArray( view.transform.matrix );
				camera.projectionMatrix.fromArray( view.projectionMatrix );
				camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );

				if ( i === 0 ) {

					cameraVR.matrix.copy( camera.matrix );

				}

			}

		}

		//

		var inputSources = session.inputSources;

		for ( var i = 0; i < controllers.length; i ++ ) {

			var controller = controllers[ i ];
			var inputSource = inputSources[ i ];

			controller.update( inputSource, frame, referenceSpace );

		}

		if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame );

	}

	var animation = new WebGLAnimation();
	animation.setAnimationLoop( onAnimationFrame );

	this.setAnimationLoop = function ( callback ) {

		onAnimationFrameCallback = callback;

	};

	this.dispose = function () {};

}

Object.assign( WebXRManager.prototype, EventDispatcher.prototype );

export { WebXRManager };
<commit_msg>WebXRManager: Clean up.<commit_after>/**
 * @author mrdoob / http://mrdoob.com/
 */

import { ArrayCamera } from '../../cameras/ArrayCamera.js';
import { EventDispatcher } from '../../core/EventDispatcher.js';
import { PerspectiveCamera } from '../../cameras/PerspectiveCamera.js';
import { Vector3 } from '../../math/Vector3.js';
import { Vector4 } from '../../math/Vector4.js';
import { WebGLAnimation } from '../webgl/WebGLAnimation.js';
import { WebXRController } from './WebXRController.js';

function WebXRManager( renderer, gl ) {

	var scope = this;

	var session = null;

	var framebufferScaleFactor = 1.0;

	var referenceSpace = null;
	var referenceSpaceType = 'local-floor';

	var pose = null;

	var controllers = [];
	var inputSourcesMap = new Map();

	//

	var cameraL = new PerspectiveCamera();
	cameraL.layers.enable( 1 );
	cameraL.viewport = new Vector4();

	var cameraR = new PerspectiveCamera();
	cameraR.layers.enable( 2 );
	cameraR.viewport = new Vector4();

	var cameraVR = new ArrayCamera( [ cameraL, cameraR ] );
	cameraVR.layers.enable( 1 );
	cameraVR.layers.enable( 2 );

	var _currentDepthNear = null;
	var _currentDepthFar = null;

	//

	this.enabled = false;

	this.isPresenting = false;

	this.getController = function ( index ) {

		var controller = controllers[ index ];

		if ( controller === undefined ) {

			controller = new WebXRController();
			controllers[ index ] = controller;

		}

		return controller.getTargetRaySpace();

	};

	this.getControllerGrip = function ( index ) {

		var controller = controllers[ index ];

		if ( controller === undefined ) {

			controller = new WebXRController();
			controllers[ index ] = controller;

		}

		return controller.getGripSpace();

	};

	//

	function onSessionEvent( event ) {

		var controller = inputSourcesMap.get( event.inputSource );

		if ( controller ) {

			controller.dispatchEvent( { type: event.type } );

		}

	}

	function onSessionEnd() {

		inputSourcesMap.forEach( function ( controller, inputSource ) {

			controller.disconnect( inputSource );

		} );

		inputSourcesMap.clear();

		//

		renderer.setFramebuffer( null );
		renderer.setRenderTarget( renderer.getRenderTarget() ); // Hack #15830
		animation.stop();

		scope.isPresenting = false;

		scope.dispatchEvent( { type: 'sessionend' } );

	}

	function onRequestReferenceSpace( value ) {

		referenceSpace = value;

		animation.setContext( session );
		animation.start();

		scope.isPresenting = true;

		scope.dispatchEvent( { type: 'sessionstart' } );

	}

	this.setFramebufferScaleFactor = function ( value ) {

		framebufferScaleFactor = value;

		if ( scope.isPresenting === true ) {

			console.warn( 'THREE.WebXRManager: Cannot change framebuffer scale while presenting.' );

		}

	};

	this.setReferenceSpaceType = function ( value ) {

		referenceSpaceType = value;

		if ( scope.isPresenting === true ) {

			console.warn( 'THREE.WebXRManager: Cannot change reference space type while presenting.' );

		}

	};

	this.getReferenceSpace = function () {

		return referenceSpace;

	};

	this.getSession = function () {

		return session;

	};

	this.setSession = function ( value ) {

		session = value;

		if ( session !== null ) {

			session.addEventListener( 'select', onSessionEvent );
			session.addEventListener( 'selectstart', onSessionEvent );
			session.addEventListener( 'selectend', onSessionEvent );
			session.addEventListener( 'squeeze', onSessionEvent );
			session.addEventListener( 'squeezestart', onSessionEvent );
			session.addEventListener( 'squeezeend', onSessionEvent );
			session.addEventListener( 'end', onSessionEnd );

			var attributes = gl.getContextAttributes();

			var layerInit = {
				antialias: attributes.antialias,
				alpha: attributes.alpha,
				depth: attributes.depth,
				stencil: attributes.stencil,
				framebufferScaleFactor: framebufferScaleFactor
			};

			// eslint-disable-next-line no-undef
			var baseLayer = new XRWebGLLayer( session, gl, layerInit );

			session.updateRenderState( { baseLayer: baseLayer } );

			session.requestReferenceSpace( referenceSpaceType ).then( onRequestReferenceSpace );

			//

			session.addEventListener( 'inputsourceschange', updateInputSources );

		}

	};

	function updateInputSources( event ) {

		var inputSources = session.inputSources;

		// Assign inputSources to available controllers

		for ( var i = 0; i < controllers.length; i ++ ) {

			inputSourcesMap.set( inputSources[ i ], controllers[ i ] );

		}

		// Notify disconnected

		for ( var i = 0; i < event.removed.length; i ++ ) {

			var inputSource = event.removed[ i ];
			var controller = inputSourcesMap.get( inputSource );

			if ( controller ) {

				controller.dispatchEvent( { type: 'disconnected', data: inputSource } );
				inputSourcesMap.delete( inputSource );

			}

		}

		// Notify connected

		for ( var i = 0; i < event.added.length; i ++ ) {

			var inputSource = event.added[ i ];
			var controller = inputSourcesMap.get( inputSource );

			if ( controller ) {

				controller.dispatchEvent( { type: 'connected', data: inputSource } );

			}

		}

	}

	//

	var cameraLPos = new Vector3();
	var cameraRPos = new Vector3();

	/**
	 * @author jsantell / https://www.jsantell.com/
	 *
	 * Assumes 2 cameras that are parallel and share an X-axis, and that
	 * the cameras' projection and world matrices have already been set.
	 * And that near and far planes are identical for both cameras.
	 * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
	 */
	function setProjectionFromUnion( camera, cameraL, cameraR ) {

		cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
		cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );

		var ipd = cameraLPos.distanceTo( cameraRPos );

		var projL = cameraL.projectionMatrix.elements;
		var projR = cameraR.projectionMatrix.elements;

		// VR systems will have identical far and near planes, and
		// most likely identical top and bottom frustum extents.
		// Use the left camera for these values.
		var near = projL[ 14 ] / ( projL[ 10 ] - 1 );
		var far = projL[ 14 ] / ( projL[ 10 ] + 1 );
		var topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
		var bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];

		var leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
		var rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
		var left = near * leftFov;
		var right = near * rightFov;

		// Calculate the new camera's position offset from the
		// left camera. xOffset should be roughly half `ipd`.
		var zOffset = ipd / ( - leftFov + rightFov );
		var xOffset = zOffset * - leftFov;

		// TODO: Better way to apply this offset?
		cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
		camera.translateX( xOffset );
		camera.translateZ( zOffset );
		camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
		camera.matrixWorldInverse.getInverse( camera.matrixWorld );

		// Find the union of the frustum values of the cameras and scale
		// the values so that the near plane's position does not change in world space,
		// although must now be relative to the new union camera.
		var near2 = near + zOffset;
		var far2 = far + zOffset;
		var left2 = left - xOffset;
		var right2 = right + ( ipd - xOffset );
		var top2 = topFov * far / far2 * near2;
		var bottom2 = bottomFov * far / far2 * near2;

		camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );

	}

	function updateCamera( camera, parent ) {

		if ( parent === null ) {

			camera.matrixWorld.copy( camera.matrix );

		} else {

			camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );

		}

		camera.matrixWorldInverse.getInverse( camera.matrixWorld );

	}

	this.getCamera = function ( camera ) {

		cameraVR.near = cameraR.near = cameraL.near = camera.near;
		cameraVR.far = cameraR.far = cameraL.far = camera.far;

		if ( _currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far ) {

			// Note that the new renderState won't apply until the next frame. See #18320

			session.updateRenderState( {
				depthNear: cameraVR.near,
				depthFar: cameraVR.far
			} );

			_currentDepthNear = cameraVR.near;
			_currentDepthFar = cameraVR.far;

		}

		var parent = camera.parent;
		var cameras = cameraVR.cameras;

		updateCamera( cameraVR, parent );

		for ( var i = 0; i < cameras.length; i ++ ) {

			updateCamera( cameras[ i ], parent );

		}

		// update camera and its children

		camera.matrixWorld.copy( cameraVR.matrixWorld );

		var children = camera.children;

		for ( var i = 0, l = children.length; i < l; i ++ ) {

			children[ i ].updateMatrixWorld( true );

		}

		setProjectionFromUnion( cameraVR, cameraL, cameraR );

		return cameraVR;

	};

	// Animation Loop

	var onAnimationFrameCallback = null;

	function onAnimationFrame( time, frame ) {

		pose = frame.getViewerPose( referenceSpace );

		if ( pose !== null ) {

			var views = pose.views;
			var baseLayer = session.renderState.baseLayer;

			renderer.setFramebuffer( baseLayer.framebuffer );

			for ( var i = 0; i < views.length; i ++ ) {

				var view = views[ i ];
				var viewport = baseLayer.getViewport( view );

				var camera = cameraVR.cameras[ i ];
				camera.matrix.fromArray( view.transform.matrix );
				camera.projectionMatrix.fromArray( view.projectionMatrix );
				camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );

				if ( i === 0 ) {

					cameraVR.matrix.copy( camera.matrix );

				}

			}

		}

		//

		var inputSources = session.inputSources;

		for ( var i = 0; i < controllers.length; i ++ ) {

			var controller = controllers[ i ];
			var inputSource = inputSources[ i ];

			controller.update( inputSource, frame, referenceSpace );

		}

		if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame );

	}

	var animation = new WebGLAnimation();
	animation.setAnimationLoop( onAnimationFrame );

	this.setAnimationLoop = function ( callback ) {

		onAnimationFrameCallback = callback;

	};

	this.dispose = function () {};

}

Object.assign( WebXRManager.prototype, EventDispatcher.prototype );

export { WebXRManager };
<|endoftext|>


<commit_before>var createGraph = function(fileName)
{
  d3.select('#somegraph').remove();
  var margin = {top: 20, right: 80, bottom: 30, left: 70},
      width = 660 - margin.left - margin.right,
      height = 400 - margin.top - margin.bottom;

  var x = d3.scale.ordinal().rangeRoundBands([0, width]);

  var y = d3.scale.linear()
      .range([height, 0]);

  var color = d3.scale.category10();

  var xAxis = d3.svg.axis()
      .scale(x)
      .ticks(10)
      .orient("bottom");

  var yAxis = d3.svg.axis()
      .scale(y)
      .orient("left");

  var line = d3.svg.line()
      .interpolate("basis")
      .x(function(d) { return x(d.period); })
      .y(function(d) { return y(d.logs); });

  var svg = d3.select("body").append("svg")
      .attr('id','somegraph')
      .attr("width", width + margin.left + margin.right)
      .attr("height", height + margin.top + margin.bottom)
    .append("g")
      .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

  d3.json(fileName, function(error, data) {
    if (error) throw error;

    color.domain(d3.keys(data[0]).filter(function(key) { return key !== "period"; }));

    var continents = color.domain().map(function(name) {
      return {
        name: name,
        values: data.map(function(d) {
          return {period: d.period, logs: +d[name]};
        })
      };
    });

    x.domain(data.map(function(d) { return d.period; }));

    y.domain([
      d3.min(continents, function(c) { return d3.min(c.values, function(v) { return v.logs; }); }),
      d3.max(continents, function(c) { return d3.max(c.values, function(v) { return v.logs; }); })
    ]);

    svg.append("g")
        .attr("class", "x axis")
        .attr("transform", "translate(0," + height + ")")
        .call(xAxis);

    svg.append("g")
        .attr("class", "y axis")
        .call(yAxis)
      .append("text")
        .attr("transform", "rotate(-90)")
        .attr("y", 6)
        .attr("dy", ".71em")
        .style("text-anchor", "end")
        .text("Number of logs (period-wise)");

    var city = svg.selectAll(".city")
        .data(continents)
      .enter().append("g")
        .attr("class", "city");

    city.append("path")
        .attr("class", "line")
        .attr("d", function(d) { return line(d.values); })
        .style("stroke", function(d) { return color(d.name); });

        var legend = svg.selectAll(".legend")
        .data(color.domain().slice().reverse())
      .enter().append("g")
        .attr("class", "legend")
        .attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; });

    legend.append("rect")
        .attr("x", width - 18)
        .attr("width", 18)
        .attr("height", 18)
        .style("fill", color)
        .attr("transform", "translate(50,-10)");

    legend.append("text")
        .attr("x", width - 24)
        .attr("y", 9)
        .attr("dy", ".35em")
        .style("text-anchor", "end")
        .text(function(d) { return d; })
        .attr("transform", "translate(50,-10)");;

  });

}
function addPara(tab,when)
{
  $(tab + " p").remove();
  $(tab).append("
Number of logs for all of " + when + "
");
  $(tab + " p").css("margin-top","20px");
  $(tab + " p").css("font-size","17px");
}
$(function(){
  $('#y2015').click(function(){
      $('#dropdownMenu1').html('2015');
      addPara("#tab1","2015");
      createGraph("json/rate/monthwise_log.json");
  });
  $('#y15').click(function(){
      $('#dropdownMenu2').html('2015');
      $('#jan').click(function(){
        $('#dropdownMenu3').html('January');
        addPara("#tab2","January");
        createGraph("json/rate/Jan_log.json");
      });
      $('#feb').click(function(){
        $('#dropdownMenu3').html('February');
        addPara("#tab2","February");
        createGraph("json/rate/Feb_log.json");
      });
      $('#mar').click(function(){
        $('#dropdownMenu3').html('March');
        addPara("#tab2","March");
        createGraph("json/rate/Mar_log.json");
      });
      $('#apr').click(function(){
        $('#dropdownMenu3').html('April');
        addPara("#tab2","April");
        createGraph("json/rate/Apr_log.json");
      });
      $('#may').click(function(){
        $('#dropdownMenu3').html('May');
        addPara("#tab2","May");
        createGraph("json/rate/May_log.json");
      });
      $('#jun').click(function(){
        $('#dropdownMenu3').html('June');
        addPara("#tab2","June");
        createGraph("json/rate/Jun_log.json");
      });
      $('#jul').click(function(){
        $('#dropdownMenu3').html('July');
        addPara("#tab2","July");
        createGraph("json/rate/Jul_log.json");
      });
      $('#aug').click(function(){
        $('#dropdownMenu3').html('August');
        addPara("#tab2","August");
        createGraph("json/rate/Aug_log.json");
      });
      $('#sep').click(function(){
        $('#dropdownMenu3').html('September');
        addPara("#tab2","September");
        createGraph("json/rate/Sep_log.json");
      });
      $('#oct').click(function(){
        $('#dropdownMenu3').html('October');
        addPara("#tab2","October");
        createGraph("json/rate/Oct_log.json");
      });
      $('#nov').click(function(){
        $('#dropdownMenu3').html('November');
        addPara("#tab2","November");
        createGraph("json/rate/Nov_log.json");
      });
      $('#dec').click(function(){
        $('#dropdownMenu3').html('December');
        addPara("#tab2","December");
        createGraph("json/rate/Dec_log.json");
      });
      $('#y2015').click(function(){
          $('#dropdownMenu1').html('2015');
          createGraph("json/rate/monthwise_log.json");
      });
  });
  $('#year_tab').click(function(){
      $('#dropdownMenu2').html('Year');
      $('#dropdownMenu3').html('Month');
  });
  $('#month_tab').click(function(){
      $('#dropdownMenu1').html('Year');
  });
});
<commit_msg>Improved efficiency<commit_after>var createGraph = function(fileName)
{
  d3.select('#somegraph').remove();
  var margin = {top: 20, right: 80, bottom: 30, left: 70},
      width = 660 - margin.left - margin.right,
      height = 400 - margin.top - margin.bottom;

  var x = d3.scale.ordinal().rangeRoundBands([0, width]);

  var y = d3.scale.linear()
      .range([height, 0]);

  var color = d3.scale.category10();

  var xAxis = d3.svg.axis()
      .scale(x)
      .ticks(10)
      .orient("bottom");

  var yAxis = d3.svg.axis()
      .scale(y)
      .orient("left");

  var line = d3.svg.line()
      .interpolate("basis")
      .x(function(d) { return x(d.period); })
      .y(function(d) { return y(d.logs); });

  var svg = d3.select("body").append("svg")
      .attr('id','somegraph')
      .attr("width", width + margin.left + margin.right)
      .attr("height", height + margin.top + margin.bottom)
    .append("g")
      .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

  d3.json(fileName, function(error, data) {
    if (error) throw error;

    color.domain(d3.keys(data[0]).filter(function(key) { return key !== "period"; }));

    var continents = color.domain().map(function(name) {
      return {
        name: name,
        values: data.map(function(d) {
          return {period: d.period, logs: +d[name]};
        })
      };
    });

    x.domain(data.map(function(d) { return d.period; }));

    y.domain([
      d3.min(continents, function(c) { return d3.min(c.values, function(v) { return v.logs; }); }),
      d3.max(continents, function(c) { return d3.max(c.values, function(v) { return v.logs; }); })
    ]);

    svg.append("g")
        .attr("class", "x axis")
        .attr("transform", "translate(0," + height + ")")
        .call(xAxis);

    svg.append("g")
        .attr("class", "y axis")
        .call(yAxis)
      .append("text")
        .attr("transform", "rotate(-90)")
        .attr("y", 6)
        .attr("dy", ".71em")
        .style("text-anchor", "end")
        .text("Number of logs (period-wise)");

    var city = svg.selectAll(".city")
        .data(continents)
      .enter().append("g")
        .attr("class", "city");

    city.append("path")
        .attr("class", "line")
        .attr("d", function(d) { return line(d.values); })
        .style("stroke", function(d) { return color(d.name); });

        var legend = svg.selectAll(".legend")
        .data(color.domain().slice().reverse())
      .enter().append("g")
        .attr("class", "legend")
        .attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; });

    legend.append("rect")
        .attr("x", width - 18)
        .attr("width", 18)
        .attr("height", 18)
        .style("fill", color)
        .attr("transform", "translate(50,-10)");

    legend.append("text")
        .attr("x", width - 24)
        .attr("y", 9)
        .attr("dy", ".35em")
        .style("text-anchor", "end")
        .text(function(d) { return d; })
        .attr("transform", "translate(50,-10)");;

  });

}
function addPara(tab,when)
{
  $(tab + " p").remove();
  $(tab).append("
Number of logs for all of " + when + "
");
  $(tab + " p").css("margin-top","20px");
  $(tab + " p").css("font-size","17px");
}
$(function(){
  $('#y2015').click(function(){
      $('#dropdownMenu1').html('2015');
      addPara("#tab1","2015");
      createGraph("json/rate/monthwise_log.json");
  });
  $('#y15').click(function(){
      $('#dropdownMenu2').html('2015');
      $('#jan').click(function(){
        $('#dropdownMenu3').html('January');
        addPara("#tab2","January");
        createGraph("json/rate/Jan_log.json");
      });
      $('#feb').click(function(){
        $('#dropdownMenu3').html('February');
        addPara("#tab2","February");
        createGraph("json/rate/Feb_log.json");
      });
      $('#mar').click(function(){
        $('#dropdownMenu3').html('March');
        addPara("#tab2","March");
        createGraph("json/rate/Mar_log.json");
      });
      $('#apr').click(function(){
        $('#dropdownMenu3').html('April');
        addPara("#tab2","April");
        createGraph("json/rate/Apr_log.json");
      });
      $('#may').click(function(){
        $('#dropdownMenu3').html('May');
        addPara("#tab2","May");
        createGraph("json/rate/May_log.json");
      });
      $('#jun').click(function(){
        $('#dropdownMenu3').html('June');
        addPara("#tab2","June");
        createGraph("json/rate/Jun_log.json");
      });
      $('#jul').click(function(){
        $('#dropdownMenu3').html('July');
        addPara("#tab2","July");
        createGraph("json/rate/Jul_log.json");
      });
      $('#aug').click(function(){
        $('#dropdownMenu3').html('August');
        addPara("#tab2","August");
        createGraph("json/rate/Aug_log.json");
      });
      $('#sep').click(function(){
        $('#dropdownMenu3').html('September');
        addPara("#tab2","September");
        createGraph("json/rate/Sep_log.json");
      });
      $('#oct').click(function(){
        $('#dropdownMenu3').html('October');
        addPara("#tab2","October");
        createGraph("json/rate/Oct_log.json");
      });
      $('#nov').click(function(){
        $('#dropdownMenu3').html('November');
        addPara("#tab2","November");
        createGraph("json/rate/Nov_log.json");
      });
      $('#dec').click(function(){
        $('#dropdownMenu3').html('December');
        addPara("#tab2","December");
        createGraph("json/rate/Dec_log.json");
      });
      $('#y2015').click(function(){
          $('#dropdownMenu1').html('2015');
          addPara("#tab1","2015");
          createGraph("json/rate/monthwise_log.json");
      });
  });
  $('#year_tab').click(function(){
      $('#dropdownMenu2').html('Year');
      $('#dropdownMenu3').html('Month');
  });
  $('#month_tab').click(function(){
      $('#dropdownMenu1').html('Year');
  });
});
<|endoftext|>


<commit_before>/** Material definition */
var Material=Serializable.extend({
	/** Constructor
		@param shader Shader that will be used
		@param uniforms Shader uniforms as object described in Shader.use
		@param samplers Shader samplers as array described in Shader.bindSamplers/unbindSamplers
		@param descriptor MaterialDescriptor instance [optional] */
	init: function(shader, uniforms, samplers, descriptor) {
		this._super();
		this.name = 'Unnamed';
		this.shader = shader; ///< Instance of Shader
		this.uniforms = uniforms; ///< Shader uniforms as described by Shader
		this.samplers = samplers; ///< Shader samplers list
		this.descriptor = descriptor;
	},

	type: function() {
		return "Material";
	},

	/** Binds material
		@param uniforms Optional extra uniforms to go with the material
		@param samplers Optional extra samplers to go with the material */
	bind: function(uniforms, samplers) {
		if (!this.shader) return;

		this.shader.use(this.uniforms);
		if (uniforms)
			this.shader.bindUniforms(uniforms);

		if ((!this.samplers || this.samplers.length == 0) && (!samplers || samplers.length == 0)) {
			if (this.shader.context.engine)
				this.shader.bindSamplers([this.shader.context.engine.WhiteTextureSampler]);
		}
		else {
			if (samplers)
				this.shader.bindSamplers(this.samplers.concat(samplers));
			else
				this.shader.bindSamplers(this.samplers);
		}
	},

	/** Unbinds material
		@param samplers Optional extra samplers to go with the material (the same that were passed to bind()) */
	unbind: function(samplers) {
		if(!this.shader) return;

		if ((!this.samplers || this.samplers.length == 0) && (!samplers || samplers.length == 0)) {
			if (this.shader.context.engine)
				this.shader.unbindSamplers([this.shader.context.engine.WhiteTextureSampler]);
		}
		else {
			if (samplers)
				this.shader.unbindSamplers(this.samplers.concat(samplers));
			else
				this.shader.unbindSamplers(this.samplers);
		}
	},

	instantiate: function() {
		var uniforms = {};
		for (var i in this.uniforms) {
			uniforms[i] = this.uniforms[i].clone();
		}

		var samplers = [];
		for (var i in this.samplers) {
			if(typeof this.samplers[i] == "object")
				samplers.push(this.samplers[i].clone());
		}

		var copy = new Material(this.shader, uniforms, samplers, this.descriptor);
		copy.name = this.name+" (instance)";
		return copy;
	}
});<commit_msg>Fix: more efficient sampler list generation<commit_after>/** Material definition */
var Material=Serializable.extend({
	/** Constructor
		@param shader Shader that will be used
		@param uniforms Shader uniforms as object described in Shader.use
		@param samplers Shader samplers as array described in Shader.bindSamplers/unbindSamplers
		@param descriptor MaterialDescriptor instance [optional] */
	init: function(shader, uniforms, samplers, descriptor) {
		this._super();
		this.name = 'Unnamed';
		this.shader = shader; ///< Instance of Shader
		this.uniforms = uniforms; ///< Shader uniforms as described by Shader
		this.samplers = samplers; ///< Shader samplers list
		this.descriptor = descriptor;

		this.boundSamplers = new Array();
		this.numBoundSamplers = 0;
	},

	type: function() {
		return "Material";
	},

	internalBindSampler: function(sampler) {
		this.boundSamplers[this.numBoundSamplers++] = sampler;
	},

	/** Binds material
		@param uniforms Optional extra uniforms to go with the material
		@param samplers Optional extra samplers to go with the material */
	bind: function(uniforms, samplers) {
		if (!this.shader) return;

		this.shader.use(this.uniforms);
		if (uniforms)
			this.shader.bindUniforms(uniforms);

		if ((!this.samplers || this.samplers.length == 0) && (!samplers || samplers.length == 0)) {
			if (this.shader.context.engine)
				this.internalBindSampler(this.shader.context.engine.WhiteTextureSampler);
		}
		else {
			if (samplers) {
				for (var i=0; i<samplers.length; ++i)
					this.internalBindSampler(samplers[i]);
			}

			for (var i=0; i<this.samplers.length; ++i)
				this.internalBindSampler(this.samplers[i]);
		}

		this.shader.bindSamplers(this.boundSamplers);
	},

	/** Unbinds material
		@param samplers Optional extra samplers to go with the material (the same that were passed to bind()) */
	unbind: function(samplers) {
		if (!this.shader)
			return;

		this.shader.unbindSamplers(this.boundSamplers);

		for (var i=0; i<this.boundSamplers.length; ++i) {
			this.boundSamplers[i] = null;
		}
		this.numBoundSamplers = 0;
	},

	instantiate: function() {
		var uniforms = {};
		for (var i in this.uniforms) {
			uniforms[i] = this.uniforms[i].clone();
		}

		var samplers = [];
		for (var i in this.samplers) {
			if(typeof this.samplers[i] == "object")
				samplers.push(this.samplers[i].clone());
		}

		var copy = new Material(this.shader, uniforms, samplers, this.descriptor);
		copy.name = this.name+" (instance)";
		return copy;
	}
});
<|endoftext|>


<commit_before>var delay;

function myFunction() {
    delay = setTimeout(showPage, 2000);
}

function showPage() {
    document.getElementById("loader").style.display = "none";
    document.getElementById("content").style.display = "block";
}
 $(function(){
    $('.hamburger').on('click', function(e){
        e.stopPropagation();
        $('.menu').toggle('slow');
    });
    $('body').on('click', function(){
        $('.menu').hide();
    });
    $('.menu').on('click', function(e){
        e.stopPropagation();
    });
});

<commit_msg>refs #7<commit_after>function myFunction() {
    setTimeout(showPage, 2000);
}

function showPage() {
    document.getElementById("loader").style.display = "none";
    document.getElementById("content").style.display = "block";
}
 $(function(){
    $('.hamburger').on('click', function(e){
        e.stopPropagation();
        $('.menu').toggle('slow');
    });
    $('body').on('click', function(){
        $('.menu').hide();
    });
    $('.menu').on('click', function(e){
        e.stopPropagation();
    });
});

<|endoftext|>


<commit_before>var width = 1100;
var height = 700;
var value = 0;
var context;
var level = 1;
var balls = [
  {active:true,x:200,y:200,dx:.707,dy:.707,color:"#0000ff",radius:20,damage:8},
  {active:true,x:100,y:100,dx:-.707,dy:.707,color:"#ff0000",radius:10,damage:20},
  {active:true,x:300,y:300,dx:.707,dy:-.707,color:"#00ff00",radius:30,damage:13},
  {active:false,x:400,y:400,dx:-1,dy:-1,color:"#ffff00",radius:15,damage:13}
];
var enemies = [];
function addValue(number) {
  value = value + number;
  document.getElementById("value").innerHTML = value;
}
function init() {
  context= myCanvas.getContext('2d');
  newLevel();
  setInterval(draw,10);
}
function newLevel() {
  level++;
  document.getElementById("level").innerHTML = level;
  enemies = [];
  for(i = 0;i<5;i++){
    var healthTemp = Math.floor(Math.pow(rand(100,200),level/2));
    enemies.push({x:rand(100, 1000),y:rand(100, 600),health:healthTemp,sHealth:healthTemp,active:true,radius:rand(20,60)});
  }
}
function rand(min,max){
  return min + (Math.floor(Math.random() * (max-min)));
}
function dec2hex(dec) {
    return Number(parseInt( dec , 10)).toString(16);
}
function levelCheck(){
  var allDisabled = true;
  for(var l = 0; l<enemies.length; l++){
    enemyCheck = enemies[l];
    if(enemyCheck.active){
      allDisabled = false;
    }
  }
  if(allDisabled){
    newLevel();
  }
}
function draw(){
  context.clearRect(0,0,width,height);
  for(var i = 0; i<enemies.length; i++){
    var enemyDraw = enemies[i];
    if(enemyDraw.active){
      context.beginPath();
      context.fillStyle="#000000";
      context.arc(enemyDraw.x,enemyDraw.y,enemyDraw.radius,0,Math.PI*2,true);
      context.closePath();
      context.fill();
      context.font = "30px Arial";
      context.fillText(Math.round((enemy.health/enemy.sHealth)*100)+"%",enemyDraw.x-10,enemyDraw.y+10);
    }
  }
  for(var i = 0; i<balls.length; i++){
    var ball = balls[i]
    if(ball.active){
      context.beginPath();
      context.fillStyle=ball.color;
      context.arc(ball.x,ball.y,ball.radius,0,Math.PI*2,true);
      context.closePath();
      context.fill();
      for(var e = 0; e<enemies.length; e++){
        var enemy = enemies[e];
        if(enemy.active){
          if(Math.pow(ball.x-enemy.x,2)+Math.pow(ball.y-enemy.y,2)<=Math.pow(enemy.radius+ball.radius,2)){
            if(enemy.health>ball.damage)
              {
                enemy.health -= ball.damage;
              }
            else
              {
                enemy.active = false;
                addValue(enemy.sHealth);
                levelCheck();
              }
            ball.dx = (ball.x - enemy.x)/Math.sqrt(Math.pow(ball.x-enemy.x,2)+Math.pow(ball.y-enemy.y,2));
            ball.dy = (ball.y - enemy.y)/Math.sqrt(Math.pow(ball.x-enemy.x,2)+Math.pow(ball.y-enemy.y,2));
          }
        }
      }
      if(ball.x<=ball.radius || ball.x>=(width-ball.radius)) ball.dx=-ball.dx;
      if(ball.y<=ball.radius || ball.y>=(height-ball.radius)) ball.dy=-ball.dy;
      ball.x+=ball.dx*4;
      ball.y+=ball.dy*4;
    }
  }
}
<commit_msg>Fixed another error<commit_after>var width = 1100;
var height = 700;
var value = 0;
var context;
var level = 1;
var balls = [
  {active:true,x:200,y:200,dx:.707,dy:.707,color:"#0000ff",radius:20,damage:8},
  {active:true,x:100,y:100,dx:-.707,dy:.707,color:"#ff0000",radius:10,damage:20},
  {active:true,x:300,y:300,dx:.707,dy:-.707,color:"#00ff00",radius:30,damage:13},
  {active:false,x:400,y:400,dx:-1,dy:-1,color:"#ffff00",radius:15,damage:13}
];
var enemies = [];
function addValue(number) {
  value = value + number;
  document.getElementById("value").innerHTML = value;
}
function init() {
  context= myCanvas.getContext('2d');
  newLevel();
  setInterval(draw,10);
}
function newLevel() {
  level++;
  document.getElementById("level").innerHTML = level;
  enemies = [];
  for(i = 0;i<5;i++){
    var healthTemp = Math.floor(Math.pow(rand(100,200),level/2));
    enemies.push({x:rand(100, 1000),y:rand(100, 600),health:healthTemp,sHealth:healthTemp,active:true,radius:rand(20,60)});
  }
}
function rand(min,max){
  return min + (Math.floor(Math.random() * (max-min)));
}
function dec2hex(dec) {
    return Number(parseInt( dec , 10)).toString(16);
}
function levelCheck(){
  var allDisabled = true;
  for(var l = 0; l<enemies.length; l++){
    enemyCheck = enemies[l];
    if(enemyCheck.active){
      allDisabled = false;
    }
  }
  if(allDisabled){
    newLevel();
  }
}
function draw(){
  context.clearRect(0,0,width,height);
  for(var i = 0; i<enemies.length; i++){
    var enemyDraw = enemies[i];
    if(enemyDraw.active){
      context.beginPath();
      context.fillStyle="#000000";
      context.arc(enemyDraw.x,enemyDraw.y,enemyDraw.radius,0,Math.PI*2,true);
      context.closePath();
      context.fill();
      context.font = "30px Arial";
      context.fillText(Math.round((enemyDraw.health/enemyDraw.sHealth)*100)+"%",enemyDraw.x-10,enemyDraw.y+10);
    }
  }
  for(var i = 0; i<balls.length; i++){
    var ball = balls[i]
    if(ball.active){
      context.beginPath();
      context.fillStyle=ball.color;
      context.arc(ball.x,ball.y,ball.radius,0,Math.PI*2,true);
      context.closePath();
      context.fill();
      for(var e = 0; e<enemies.length; e++){
        var enemy = enemies[e];
        if(enemy.active){
          if(Math.pow(ball.x-enemy.x,2)+Math.pow(ball.y-enemy.y,2)<=Math.pow(enemy.radius+ball.radius,2)){
            if(enemy.health>ball.damage)
              {
                enemy.health -= ball.damage;
              }
            else
              {
                enemy.active = false;
                addValue(enemy.sHealth);
                levelCheck();
              }
            ball.dx = (ball.x - enemy.x)/Math.sqrt(Math.pow(ball.x-enemy.x,2)+Math.pow(ball.y-enemy.y,2));
            ball.dy = (ball.y - enemy.y)/Math.sqrt(Math.pow(ball.x-enemy.x,2)+Math.pow(ball.y-enemy.y,2));
          }
        }
      }
      if(ball.x<=ball.radius || ball.x>=(width-ball.radius)) ball.dx=-ball.dx;
      if(ball.y<=ball.radius || ball.y>=(height-ball.radius)) ball.dy=-ball.dy;
      ball.x+=ball.dx*4;
      ball.y+=ball.dy*4;
    }
  }
}
<|endoftext|>


<commit_before>var main = function(){
    $('#fullpage').fullpage({
//        anchors:["lang","welcome","projects","contacts"]
    });

    $(".langbtn").click(function(){

        if($(this).html() =="English"){
            var langfile= "lang/en.json"
            console.log(langfile);
        } else if($(this).html() =="عربي"){
            var langfile= "lang/ar.json"
            console.log(langfile);
       }
        $.getJSON(langfile,function(data){
//            $("html").attr("lang",data.lang);            $('#greeting').append(data.greeting.forEach(parsep));
            $('#greeting').empty();
            $.each(data.greeting, function(i,val){
                console.log(val);
                $('#greeting').append($('
').html(val));

            });
            $('#typed-strings').empty();
            $.each(data.introlist, function(i,val){
                console.log(val);
                $('#typed-strings').append($('
').html(val));
            });
            $('#projects').empty();
            var $project;
            var $title;
            var $description;
            var $links;
            var $link;
            var $status;
            var $version;
            $.each(data.projects, function(i,val){
                $project = $('
').attr('class','slide');
                $title = $('
').html(val.title);
                $description = $('
').html(val.description);
                $links = $('
').attr('id','links');
                // APPEND
                $project.append($title);
                $project.append($description);
                $project.append($links);

                $.each(val.links,function(key,val){
                    $link =$('').attr('href',val).html(key);
                    $links.append($link);
                });
                $status=$('
').text(val.status);
                $version=$('
').text(val.version);
                $('#projects').append(project);
            });
        });
    });
};

$(function() {

    $("#hi").typed({
        strings: ["Hi", "I am Omar ^1500"],
        // stringsElement: $('#typed-strings'),
        typeSpeed: 40,
        backDelay: 1000,
        loop: false,
        contentType: 'html', // or text
        // defaults to false for infinite loop
        loopCount: false,
        callback: function() { $(".typed-cursor").remove();
            newTyped(); },
        resetCallback: function() {}
    });

    $(".reset").click(function() {
        $("#typed").typed('reset');
    });

});

function newTyped() {

    $(function() {

        $("#typed").typed({
//             strings: ["Typed.js is a jQuery plugin.", "It types out sentences.", "And then deletes them.", "Try it out!"],
            stringsElement: $('#typed-strings'),
            typeSpeed: 40,
            backDelay: 1000,
            loop: false,
            contentType: 'html', // or text
            // defaults to false for infinite loop
            loopCount: false,
//            callback: function() { foo(); }
        });

        $(".reset").click(function() {
            $("#typed").typed('reset');
        });

    });

}

$(document).ready(function() {
  main();
});

<commit_msg>update<commit_after>var main = function(){
    $('#fullpage').fullpage({
//        anchors:["lang","welcome","projects","contacts"]
    });

    $(".langbtn").click(function(){

        if($(this).html() =="English"){
            var langfile= "lang/en.json"
            console.log(langfile);
        } else if($(this).html() =="عربي"){
            var langfile= "lang/ar.json"
            console.log(langfile);
       };
        $.getJSON(langfile,function(data){
            $("html").attr("lang",data.lang);
            $('#greeting').empty();
            $.each(data.greeting, function(i,val){
                console.log(val);
                $('#greeting').append($('
').html(val));

            });
            $('#typed-strings').empty();
            $.each(data.introlist, function(i,val){
                console.log(val);
                $('#typed-strings').append($('
').html(val));
            });
            $('#projects').empty();
            var $project;
            var $title;
            var $description;
            var $links;
            var $link;
            var $status;
            var $version;
            $.each(data.projects, function(i,val){
                $project = $('
').attr('class','slide');
                $title = $('
').html(val.title);
                $description = $('
').html(val.description);
                $links = $('
').attr('id','links');
                // APPEND
                $project.append($title);
                $project.append($description);
                $project.append($links);

                $.each(val.links,function(key,val){
                    $link =$('').attr('href',val).html(key);
                    $links.append($link);
                });
                $status=$('
').text(val.status);
                $version=$('
').text(val.version);
                $('#projects').append(project);
            });
        });
    });
};

$(function() {

    $("#hi").typed({
        strings: ["Hi", "I am Omar ^1500"],
        // stringsElement: $('#typed-strings'),
        typeSpeed: 40,
        backDelay: 1000,
        loop: false,
        contentType: 'html', // or text
        // defaults to false for infinite loop
        loopCount: false,
        callback: function() { $(".typed-cursor").remove();
            newTyped(); },
        resetCallback: function() {}
    });

    $(".reset").click(function() {
        $("#typed").typed('reset');
    });

});

function newTyped() {

    $(function() {

        $("#typed").typed({
//             strings: ["Typed.js is a jQuery plugin.", "It types out sentences.", "And then deletes them.", "Try it out!"],
            stringsElement: $('#typed-strings'),
            typeSpeed: 40,
            backDelay: 1000,
            loop: false,
            contentType: 'html', // or text
            // defaults to false for infinite loop
            loopCount: false,
//            callback: function() { foo(); }
        });

        $(".reset").click(function() {
            $("#typed").typed('reset');
        });

    });

}

$(document).ready(function() {
  main();
});

<|endoftext|>


<commit_before>/*global L, d3*/
/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global define, $, jQuery, alert */

var centerOfBostonCoordinates = [42.312626, -71.071870], //center was calculated from the bounds of hand designed grid
    mymap = L.map('map').setView(centerOfBostonCoordinates, 12),
    i, //incrementor
    j; //incrementor

//optional function of marking peter's location
function markPjfanLocation() {
    "use strict";
    var pjfanLocationCoordinates = [42.3629, -71.0890],
        pjfanMarkerIcon = L.icon({
            iconUrl: 'icons/pjfan_marker_icon.png',
            iconSize: [80, 107],
            iconAnchor: [40, 106]
        }),
        pjfanLocationMarker = L.marker(pjfanLocationCoordinates, {icon: pjfanMarkerIcon}).addTo(mymap);
    pjfanLocationMarker.bindPopup("Peter \"BBOY\" Fan's Location");
}
//must retrieve Mapbox API key from node server
function getMapboxApiKey() {
    "use strict";
    $.ajax({
        type: "GET",
        url: "http://localhost:8080",
        dataType: "text",
        crossDomain: true,
        success: function (data) {
            L.mapbox.accessToken = data;
            L.tileLayer('https://api.mapbox.com/styles/v1/mapbox/dark-v9/tiles/256/{z}/{x}/{y}?access_token=' + data, {
                attribution: 'Map data © OpenStreetMap contributors, CC-BY-SA, Imagery © Mapbox',
                accessToken: data
            }).addTo(mymap);
        },
        error: function (xhr, ajaxOptions, thrownError) {
            console.log(xhr.status);
            console.log(thrownError);
        }
    });
}
getMapboxApiKey();

//create choropleth grid
var grid = [],
    minLatitude = 42.227953,
    minLongitude = -71.190647,
    boundWidth = 0.237555,
    boundHeight = 0.169347,
    increment = 0.004234;
//    increment = 0.008467;
for (i = 0; i < (boundHeight - increment); i += increment) {
    for (j = 0; j < (boundWidth - increment); j += increment) {
        var gridboxCoordinates = [],
            gridbox;
        gridboxCoordinates.push([minLatitude + i, minLongitude + j]);
        gridboxCoordinates.push([minLatitude + increment + i, minLongitude + j]);
        gridboxCoordinates.push([minLatitude + increment + i, minLongitude + increment + j]);
        gridboxCoordinates.push([minLatitude + i, minLongitude + increment + j]);
        gridbox = L.polygon(
            gridboxCoordinates,
            {
                fillColor: "#ff0000", //red
                stroke: false,
                fillOpacity: 0
            }
        ).addTo(mymap);
        grid.push(gridbox);
    }
}

//create text arrays for display and query
var years = ["2012", "2013", "2014", "2015", "2016"],
    months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
    displayMonths = [],
    postMonths = [],
    queryResults,
    queryTotal;
for (i in years) {
    for (j in months) {
        if (!(years[i] === "2012" && (months[j] === "January" || months[j] === "February" || months[j] === "March" || months[j] === "April" || months[j] === "May" || months[j] === "June"))) {
            displayMonths.push(months[j] + " " + years[i]);
            if (years[i] === "2012") {
                postMonths.push("Twelve" + months[j]);
            } else if (years[i] === "2013") {
                postMonths.push("Thirteen" + months[j]);
            } else if (years[i] === "2014") {
                postMonths.push("Fourteen" + months[j]);
            } else if (years[i] === "2015") {
                postMonths.push("Fifteen" + months[j]);
            } else if (years[i] === "2016") {
                postMonths.push("Sixteen" + months[j]);
            }
        }
    }
}

//sticky query bar
var queryBarElement = document.getElementById("wrapper-query");
window.addEventListener('scroll', function () {
    if (window.pageYOffset >= 44) {
        queryBarElement.classList.add("fixed");
    } else {
        queryBarElement.classList.remove("fixed");
    }
});

function createHorizontalChart(id, data) {
    "use strict";
    var chart = d3.select(id),
        chartWidth = 750,
        barHeight = 15,
        values = Object.values(data);
    var x = d3.scaleLinear()
        .domain([0, d3.max(values)])
        .range([0, chartWidth - (barHeight * 2)]);
    var xAxis = d3.axisBottom(x)
        .tickSize(barHeight * values.length + 5);

    chart.classed("hidden", false);
    chart.attr("width", chartWidth)
        .attr("height", barHeight * (values.length + 2) + 5);
    chart.append("g")
        .attr("transform", "translate(" + barHeight + ", " + barHeight + ")")
        .call(xAxis);
    var bar = chart.selectAll("svg")
        .data(values)
        .enter().append("g")
            .attr("class", "bar")
            .attr("transform", function(d, i) {return "translate(" + barHeight + ", " +  barHeight * (i + 1) + ")";});
    bar.append("rect")
        .attr("width", function(d) { return x(d); })
        .attr("height", barHeight - 1)
        .attr("fill", "#d85d5d");
    bar.append("text")
        .attr("transform", "translate(2, " + (barHeight - (barHeight / 4)) + ")")
        // .attr("fill", "lightGrey")
        .attr("font-family", "Verdana")
        .attr("font-size", 10)
        .text(function(d, i) {return Object.keys(data)[i];});
}
function createWordCloud(id, data){
    //remove all streets that have less then 4 incidents on them
    for (var key in data) {
        if (data[key] < 4) {
            delete data[key];
        }
    }
    var wordcloud = d3.select(id);
    wordcloud.classed("hidden", false);
    wordcloud.selectAll("g")
        .data(Object.keys(data))
        .enter().append("p")
            .text(function(d) {return d;})
            .attr("style", function(d) {return "font-size:" + (data[d] / 10 + 6) + "px"});
}
function createBubbleChart(id, data) {
    var districtData = [],
        key;
    for (key in data) {
        var district = {
            "name": key,
            "frequency": data[key]
        };
        districtData.push(district);
    }
    var tree = d3.hierarchy({children: districtData})
        .sum(function(d) {return d.frequency;});

    var width = 750;

    var bubbleChart = d3.select("#bubblechart-districts")
        .attr("width", width)
        .attr("height", width)
        .classed("hidden", false);

    var color = d3.scaleOrdinal(d3.schemeCategory20);

    var pack = d3.pack()
        .size([width, width]);

    var node = bubbleChart.selectAll(".node")
        .data(pack(tree).leaves())
        .enter().append("g")
            .attr("class", "node")
            .attr("transform", function(d) {return "translate(" + d.x + ", " + d.y + ")";});
    node.append("circle")
        .attr("r", function(d) {return d.r;})
        .style("fill", function(d) {return color(d.data.name);});
    node.append("text")
        .text(function(d) {return d.data.name;});
    node.append("title")
        .text(function(d) {return "District: " + d.data.name + "\n" + "Incidents: " + d.value;});
}

//retrieve data for the month being queried
function query(post) {
    "use strict";
    console.log(post);
    document.getElementById("histogram-category").innerHTML = ""; //clear previous histogram
    document.getElementById("wordcloud-streets").innerHTML = ""; //clear previous wordcloud
    var queryResults = {
            'category': {},
            'districts': {},
            'shooting': {
                'No': 0,
                'Yes': 0
            },
            'dayMonth': {},
            'time': {},
            'hours': {},
            'dayWeek': {
                'Sunday': 0,
                'Monday': 0,
                'Tuesday': 0,
                'Wednesday': 0,
                'Thursday': 0,
                'Friday': 0,
                'Saturday': 0
            },
            'ucr': {
                'Part One': 0,
                'Part Two': 0,
                'Part Three': 0,
                'Other': 0,
                'NA': 0
            },
            'streets': {}
        },
        queryTotal = 0;
    $.ajax({
        type: "POST",
        url: "http://localhost:8000",
        data: post,
        crossDomain: true,
        success: function (data) {
            data = JSON.parse(data);
            queryTotal = data.length;
            console.log(queryTotal + " entries received");
            var gridIndices = [];
            for (i = 0; i < data.length; i++) {
                if (queryResults.category[data[i].incident] === undefined) {
                    queryResults.category[data[i].incident] = 1;
                } else {
                    queryResults.category[data[i].incident]++;
                }
                if (queryResults.districts[data[i].district] === undefined) {
                    queryResults.districts[data[i].district] = 1;
                } else {
                    queryResults.districts[data[i].district]++;
                }
                if (queryResults.streets[data[i].street] === undefined) {
                    queryResults.streets[data[i].street] = 1;
                } else {
                    queryResults.streets[data[i].street]++;
                }
                if (queryResults.time[data[i].hour + ":" + data[i].minute] === undefined) {
                    queryResults.time[data[i].hour + ":" + data[i].minute] = 1;
                } else {
                    queryResults.time[data[i].hour + ":" + data[i].minute]++;
                }
                if (queryResults.hours[data[i].hour] === undefined) {
                    queryResults.hours[data[i].hour] = 1;
                } else {
                    queryResults.hours[data[i].hour]++;
                }
                if (queryResults.dayMonth[data[i].day] === undefined) {
                    queryResults.dayMonth[data[i].day] = 1;
                } else {
                    queryResults.dayMonth[data[i].day]++;
                }
                queryResults.shooting[data[i].shooting]++;
                queryResults.dayWeek[data[i].day_of_week]++;
                queryResults.ucr[data[i].ucr]++;

                var row = Math.ceil((data[i].latitude - minLatitude) / increment),
                    column = Math.ceil((data[i].longitude - minLongitude) / increment),
                    gridIndex = (((row - 1) * Math.round(boundWidth / increment)) + column - 1);
                if (gridIndices[gridIndex] === undefined) {
                    gridIndices[gridIndex] = 1;
                } else {
                    gridIndices[gridIndex]++;
                }
            }
            var tot = 0;
            for (i = 0; i < gridIndices.length; i++) {
                if (gridIndices[i] !== undefined && grid[i] !== undefined) {
//                    console.log("index:" + i + " sum:" + gridIndices[i] + " opacity:" + (gridIndices[i] / 250));
                    grid[i].setStyle({fillOpacity: (gridIndices[i] / 100)});
                }
            }
            createHorizontalChart("#histogram-category", queryResults.category);
            createWordCloud("#wordcloud-streets", queryResults.streets);
            createBubbleChart("#bubblechart-districts", queryResults.districts);
            console.log("All entries processed");
        },
        error: function (xhr, ajaxOptions, thrownError) {
            console.log(xhr.status);
            console.log(thrownError);
        }
    });
    console.log(queryResults);
}
function queryDatabase(newValue) {
    "use strict";
    var postData = {
        month: postMonths[newValue]
    };
    query(postData);
}
function showValue(newValue) {
    "use strict";
    document.getElementById("slider-value").innerHTML = displayMonths[newValue];
}

function getColors() {
    "use strict";
    var incidents = {};
    $.ajax({
        type: "POST",
        url: "http://localhost:8000",
        data: {month: "IncidentFrequency"},
        crossDomain: true,
        success: function (data) {
            data = JSON.parse(data);
            for (i = 0; i < data.length; i++) {
                var inc = document.createElement("div");
                inc.style.cssText = "float:left;width:300px;height:30px;text-align:center;background-color:" + data[i].color + ";";
                inc.innerHTML = data[i].name + " - " + data[i].total;
                document.getElementById("colors").appendChild(inc);
            }
        }
    });
}
//getColors();<commit_msg>added a function to create a chloropleth calender<commit_after>/*global L, d3*/
/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global define, $, jQuery, alert */

var centerOfBostonCoordinates = [42.312626, -71.071870], //center was calculated from the bounds of hand designed grid
    mymap = L.map('map').setView(centerOfBostonCoordinates, 12),
    i, //incrementor
    j; //incrementor

//optional function of marking peter's location
function markPjfanLocation() {
    "use strict";
    var pjfanLocationCoordinates = [42.3629, -71.0890],
        pjfanMarkerIcon = L.icon({
            iconUrl: 'icons/pjfan_marker_icon.png',
            iconSize: [80, 107],
            iconAnchor: [40, 106]
        }),
        pjfanLocationMarker = L.marker(pjfanLocationCoordinates, {icon: pjfanMarkerIcon}).addTo(mymap);
    pjfanLocationMarker.bindPopup("Peter \"BBOY\" Fan's Location");
}
//must retrieve Mapbox API key from node server
function getMapboxApiKey() {
    "use strict";
    $.ajax({
        type: "GET",
        url: "http://localhost:8080",
        dataType: "text",
        crossDomain: true,
        success: function (data) {
            L.mapbox.accessToken = data;
            L.tileLayer('https://api.mapbox.com/styles/v1/mapbox/dark-v9/tiles/256/{z}/{x}/{y}?access_token=' + data, {
                attribution: 'Map data © OpenStreetMap contributors, CC-BY-SA, Imagery © Mapbox',
                accessToken: data
            }).addTo(mymap);
        },
        error: function (xhr, ajaxOptions, thrownError) {
            console.log(xhr.status);
            console.log(thrownError);
        }
    });
}
getMapboxApiKey();

//create choropleth grid
var grid = [],
    minLatitude = 42.227953,
    minLongitude = -71.190647,
    boundWidth = 0.237555,
    boundHeight = 0.169347,
    increment = 0.004234;
//    increment = 0.008467;
for (i = 0; i < (boundHeight - increment); i += increment) {
    for (j = 0; j < (boundWidth - increment); j += increment) {
        var gridboxCoordinates = [],
            gridbox;
        gridboxCoordinates.push([minLatitude + i, minLongitude + j]);
        gridboxCoordinates.push([minLatitude + increment + i, minLongitude + j]);
        gridboxCoordinates.push([minLatitude + increment + i, minLongitude + increment + j]);
        gridboxCoordinates.push([minLatitude + i, minLongitude + increment + j]);
        gridbox = L.polygon(
            gridboxCoordinates,
            {
                fillColor: "#ff0000", //red
                stroke: false,
                fillOpacity: 0
            }
        ).addTo(mymap);
        grid.push(gridbox);
    }
}

//create text arrays for display and query
var years = ["2012", "2013", "2014", "2015", "2016"],
    months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
    displayMonths = [],
    postMonths = [];
for (i in years) {
    for (j in months) {
        if (!(years[i] === "2012" && (months[j] === "January" || months[j] === "February" || months[j] === "March" || months[j] === "April" || months[j] === "May" || months[j] === "June"))) {
            displayMonths.push(months[j] + " " + years[i]);
            if (years[i] === "2012") {
                postMonths.push("Twelve" + months[j]);
            } else if (years[i] === "2013") {
                postMonths.push("Thirteen" + months[j]);
            } else if (years[i] === "2014") {
                postMonths.push("Fourteen" + months[j]);
            } else if (years[i] === "2015") {
                postMonths.push("Fifteen" + months[j]);
            } else if (years[i] === "2016") {
                postMonths.push("Sixteen" + months[j]);
            }
        }
    }
}

//sticky query bar
var queryBarElement = document.getElementById("wrapper-query");
window.addEventListener('scroll', function () {
    if (window.pageYOffset >= 44) {
        queryBarElement.classList.add("fixed");
    } else {
        queryBarElement.classList.remove("fixed");
    }
});

function createHorizontalChart(id, data) {
    "use strict";
    var chart = d3.select(id),
        chartWidth = 750,
        barHeight = 15,
        values = Object.values(data);
    var x = d3.scaleLinear()
        .domain([0, d3.max(values)])
        .range([0, chartWidth - (barHeight * 2)]);
    var xAxis = d3.axisBottom(x)
        .tickSize(barHeight * values.length + 5);

    chart.classed("hidden", false);
    chart.attr("width", chartWidth)
        .attr("height", barHeight * (values.length + 2) + 5);
    chart.append("g")
        .attr("transform", "translate(" + barHeight + ", " + barHeight + ")")
        .call(xAxis);
    var bar = chart.selectAll("svg")
        .data(values)
        .enter().append("g")
            .attr("class", "bar")
            .attr("transform", function(d, i) {return "translate(" + barHeight + ", " +  barHeight * (i + 1) + ")";});
    bar.append("rect")
        .attr("width", function(d) { return x(d); })
        .attr("height", barHeight - 1)
        .attr("fill", "#d85d5d");
    bar.append("text")
        .attr("transform", "translate(2, " + (barHeight - (barHeight / 4)) + ")")
        // .attr("fill", "lightGrey")
        .attr("font-family", "Verdana")
        .attr("font-size", 10)
        .text(function(d, i) {return Object.keys(data)[i];});
}
function createWordCloud(id, data){
    //remove all streets that have less then 4 incidents on them
    for (var key in data) {
        if (data[key] < 4) {
            delete data[key];
        }
    }
    var wordcloud = d3.select(id);
    wordcloud.classed("hidden", false);
    wordcloud.selectAll("g")
        .data(Object.keys(data))
        .enter().append("p")
            .text(function(d) {return d;})
            .attr("style", function(d) {return "font-size:" + (data[d] / 10 + 6) + "px"});
}
function createBubbleChart(id, data) {
    var districtData = [],
        key;
    for (key in data) {
        var district = {
            "name": key,
            "frequency": data[key]
        };
        districtData.push(district);
    }
    var tree = d3.hierarchy({children: districtData})
        .sum(function(d) {return d.frequency;});

    var width = 750;

    var bubbleChart = d3.select("#bubblechart-districts")
        .attr("width", width)
        .attr("height", width)
        .classed("hidden", false);

    var color = d3.scaleOrdinal(d3.schemeCategory20);

    var pack = d3.pack()
        .size([width, width]);

    var node = bubbleChart.selectAll(".node")
        .data(pack(tree).leaves())
        .enter().append("g")
            .attr("class", "node")
            .attr("transform", function(d) {return "translate(" + d.x + ", " + d.y + ")";});
    node.append("circle")
        .attr("r", function(d) {return d.r;})
        .style("fill", function(d) {return color(d.data.name);});
    node.append("text")
        .text(function(d) {return d.data.name;});
    node.append("title")
        .text(function(d) {return "District: " + d.data.name + "\n" + "Incidents: " + d.value;});
}
function createChloroplethChart(id, data, month, firstDay){
    var daysWeek = {"Sunday": 0, "Monday": 1, "Tuesday": 2, "Wednesday": 3, "Thursday": 4, "Friday": 5, "Saturday": 6};
    var values = Object.values(data);
    var coordinates = []
        row = 0,
        col = 0;
    for (i = 0; i < values.length; i++) {
        if (i === 0) { col = daysWeek[firstDay]; }
        if (col > 6) { col = 0; row++; }
        coordinates.push([row, col]);
        col++;
    }

    var width = 750,
        gridboxWidth = width / 7,
        monthLabelHeight = 100,
        weeksLabelHeight = 30;

    var grid = d3.select(id)
        .attr("width", width)
        .attr("height", (gridboxWidth * (coordinates[coordinates.length - 1][0] + 1)) + monthLabelHeight + weeksLabelHeight)
        .classed("hidden", false);

    var monthLabel = grid.append("g")
        .attr("class", "monthlabel");
    monthLabel.append("rect")
        .attr("width", width)
        .attr("height", monthLabelHeight);
    monthLabel.append("text")
        .attr("x", "50%")
        .attr("y", "10%")
        .text(month);

    var weeksLabel = grid.append("g")
    var weekday = weeksLabel.selectAll("g")
        .data(Object.keys(daysWeek))
        .enter().append("g")
            .attr("width", width)
            .attr("transform", function(d, i) {return "translate(" + i * gridboxWidth + ", 100)";});
    weekday.append("rect")
        .attr("width", gridboxWidth)
        .attr("height", weeksLabelHeight)
        .attr("fill", "grey")
    weekday.append("text")
        .attr("transform", "translate(55, 20)")
        .attr("fill", "white")
        .attr("font-size", "12px")
        .attr("text-anchor", "middle")
        .text(function(d) {return d;});

    var background = grid.append("rect")
        .attr("transform", "translate(0, 130)")
        .attr("width", width)
        .attr("height", (gridboxWidth * (coordinates[coordinates.length - 1][0] + 1)))
        .attr("fill", "white");

    var days = grid.selectAll(".days")
        .data(coordinates)
        .enter().append("g")
            .attr("class", "days")
            .attr("transform", function(d){return "translate(" + (gridboxWidth * d[1]) + ", " + (gridboxWidth * d[0] + 130) + ")";});
    days.append("rect")
        .attr("width", gridboxWidth - 1)
        .attr("height", gridboxWidth - 1)
        .attr("fill-opacity", function(d, i) {return values[i] / 375;})
        .attr("class", "days");
    days.append("text")
        .attr("x", 50)
        .attr("y", 60)
        .text(function(d, i) {return (i + 1);});
}
//retrieve data for the month being queried
function query(post, monthNumber) {
    "use strict";
    console.log(post);
    document.getElementById("histogram-category").innerHTML = ""; //clear previous histogram
    document.getElementById("wordcloud-streets").innerHTML = ""; //clear previous wordcloud
    document.getElementById("bubblechart-districts").innerHTML = ""; //clear previous bubble chart
    document.getElementById("chlorogrid-daymonth").innerHTML = ""; //clear previous chloropleth grid
    var queryResults = {
            'category': {},
            'districts': {},
            'shooting': {
                'No': 0,
                'Yes': 0
            },
            'firstDay': "",
            'dayMonth': {},
            'time': {},
            'hours': {},
            'dayWeek': {
                'Sunday': 0,
                'Monday': 0,
                'Tuesday': 0,
                'Wednesday': 0,
                'Thursday': 0,
                'Friday': 0,
                'Saturday': 0
            },
            'ucr': {
                'Part One': 0,
                'Part Two': 0,
                'Part Three': 0,
                'Other': 0,
                'NA': 0
            },
            'streets': {}
        },
        queryTotal = 0;
    $.ajax({
        type: "POST",
        url: "http://localhost:8000",
        data: post,
        crossDomain: true,
        success: function (data) {
            data = JSON.parse(data);
            queryTotal = data.length;
            console.log(queryTotal + " entries received");
            var gridIndices = [];
            for (i = 0; i < data.length; i++) {
                if (queryResults.category[data[i].incident] === undefined) {
                    queryResults.category[data[i].incident] = 1;
                } else {
                    queryResults.category[data[i].incident]++;
                }
                if (queryResults.districts[data[i].district] === undefined) {
                    queryResults.districts[data[i].district] = 1;
                } else {
                    queryResults.districts[data[i].district]++;
                }
                if (queryResults.streets[data[i].street] === undefined) {
                    queryResults.streets[data[i].street] = 1;
                } else {
                    queryResults.streets[data[i].street]++;
                }
                if (queryResults.time[data[i].hour + ":" + data[i].minute] === undefined) {
                    queryResults.time[data[i].hour + ":" + data[i].minute] = 1;
                } else {
                    queryResults.time[data[i].hour + ":" + data[i].minute]++;
                }
                if (queryResults.hours[data[i].hour] === undefined) {
                    queryResults.hours[data[i].hour] = 1;
                } else {
                    queryResults.hours[data[i].hour]++;
                }
                if (queryResults.dayMonth[data[i].day] === undefined) {
                    queryResults.dayMonth[data[i].day] = 1;
                } else {
                    queryResults.dayMonth[data[i].day]++;
                }
                queryResults.shooting[data[i].shooting]++;
                queryResults.dayWeek[data[i].day_of_week]++;
                queryResults.ucr[data[i].ucr]++;
                if (queryResults.firstDay === "" && +data[i].day === 1) {
                    queryResults.firstDay = data[i].day_of_week;
                }

                var row = Math.ceil((data[i].latitude - minLatitude) / increment),
                    column = Math.ceil((data[i].longitude - minLongitude) / increment),
                    gridIndex = (((row - 1) * Math.round(boundWidth / increment)) + column - 1);
                if (gridIndices[gridIndex] === undefined) {
                    gridIndices[gridIndex] = 1;
                } else {
                    gridIndices[gridIndex]++;
                }
            }
            var tot = 0;
            for (i = 0; i < gridIndices.length; i++) {
                if (gridIndices[i] !== undefined && grid[i] !== undefined) {
//                    console.log("index:" + i + " sum:" + gridIndices[i] + " opacity:" + (gridIndices[i] / 250));
                    grid[i].setStyle({fillOpacity: (gridIndices[i] / 100)});
                }
            }
            createHorizontalChart("#histogram-category", queryResults.category);
            createWordCloud("#wordcloud-streets", queryResults.streets);
            createBubbleChart("#bubblechart-districts", queryResults.districts);
            createChloroplethChart("#chlorogrid-daymonth", queryResults.dayMonth, displayMonths[monthNumber], queryResults.firstDay);
            console.log("All entries processed");
        },
        error: function (xhr, ajaxOptions, thrownError) {
            console.log(xhr.status);
            console.log(thrownError);
        }
    });
    console.log(queryResults);
}
function queryDatabase(newValue) {
    "use strict";
    var postData = {
        month: postMonths[newValue]
    };
    query(postData, newValue);
}
function showValue(newValue) {
    "use strict";
    document.getElementById("slider-value").innerHTML = displayMonths[newValue];
}

function getColors() {
    "use strict";
    var incidents = {};
    $.ajax({
        type: "POST",
        url: "http://localhost:8000",
        data: {month: "IncidentFrequency"},
        crossDomain: true,
        success: function (data) {
            data = JSON.parse(data);
            for (i = 0; i < data.length; i++) {
                var inc = document.createElement("div");
                inc.style.cssText = "float:left;width:300px;height:30px;text-align:center;background-color:" + data[i].color + ";";
                inc.innerHTML = data[i].name + " - " + data[i].total;
                document.getElementById("colors").appendChild(inc);
            }
        }
    });
}
//getColors();<|endoftext|>


<commit_before>jQuery(function($) {
  var x = 0;
  var y = 0;
  var width;
  var height;
  var original;

  function jcrop_target(Id) {
    return function(c) {
      updateCoords(Id, c);
    };
  }

  function updateCoords(Id, c) {
    Id.closest('form').find('input[name=_x]').val(c.x);
    Id.closest('form').find('input[name=_y]').val(c.y);
    Id.closest('form').find('input[name=_w]').val(c.width);
    Id.closest('form').find('input[name=_h]').val(c.height);
    Id.closest('form').find('input[name=rotate]').val(c.rotate);
    Id.closest('form').find('input[name=scaleX]').val(c.scaleX);
    Id.closest('form').find('input[name=scaleY]').val(c.scaleY);
  }
  jQuery('.customImg').each(function() {
    width = jQuery(this).attr('customWidth');
    height = jQuery(this).attr('customHeight');
    original = jQuery(this).attr('original');
    if (original != 1) {
      jQuery(this).cropper({
         aspectRatio: width / height,
         maxWidth: width,
         maxHeight: height,
         guides: false,
         background: false,
         dragCrop: false,
         rotatable: false,
         scalable: false,
         cropBoxResizable: false,
         modal: true,
         strict: true,
         highlight: true,
         autoCrop: true,
         cropBoxMovable: true,
         crop: function (e) {
          //  console.log(e);
            updateCoords(jQuery(this), e);
          }
      });

      var cropBoxData = jQuery(this).cropper('getData');

      cropBoxData.width = parseInt(width);
      cropBoxData.height = parseInt(height);

      jQuery(this).cropper('setData', cropBoxData);

      cropBoxData = jQuery(this).cropper('getData');

      updateCoords(jQuery(this), cropBoxData);

    }

  });
  function post_form_data(data) {

        jQuery.ajax({
          type: 'POST',
          url: baseUrl + 'save.php',
          dataType:'json',
          data: {images: data},
          beforeSend: function() {
            jQuery("#saveAll").removeClass('btn-primary');
            jQuery("#saveAll").addClass('btn-success');
             jQuery("#saveAll").text('Saving...');
         },
          success: function(resp) {
            // console.log(resp);
            var file = resp.file;
            var width = resp.width;
            var height = resp.height;
            window.location.href = baseUrl + "show.php?file=" + file + '&w=' + width  + '&h=' + height;
          },
          error: function(e) {
            // console.log('error: ', e);
            jQuery("#saveAll").removeClass('btn-success');
            jQuery("#saveAll").addClass('btn-primary');
            jQuery("#saveAll").text('Save all');
          }
        });
  }
  jQuery("#saveAll").on('click', function(e) {
    var customImages = [];
    jQuery('.customizeImagesForms').each(function() {
      if (jQuery(this).find('img').attr('original') != 1) {

        customImages.push(jQuery(this).serializeArray());

      }
    });
    post_form_data(customImages);

  });

});
// Simple event handler, called from onChange and onSelect
// event handlers, as per the Jcrop invocation above
function showCoords(c) {}
<commit_msg>Zoom issue fixed<commit_after>jQuery(function($) {
  var x = 0;
  var y = 0;
  var width;
  var height;
  var original;

  function jcrop_target(Id) {
    return function(c) {
      updateCoords(Id, c);
    };
  }

  function updateCoords(Id, c) {
    Id.closest('form').find('input[name=_x]').val(c.x);
    Id.closest('form').find('input[name=_y]').val(c.y);
    Id.closest('form').find('input[name=_w]').val(c.width);
    Id.closest('form').find('input[name=_h]').val(c.height);
    Id.closest('form').find('input[name=rotate]').val(c.rotate);
    Id.closest('form').find('input[name=scaleX]').val(c.scaleX);
    Id.closest('form').find('input[name=scaleY]').val(c.scaleY);
  }
  jQuery('.customImg').each(function() {
    width = jQuery(this).attr('customWidth');
    height = jQuery(this).attr('customHeight');
    original = jQuery(this).attr('original');
    if (original != 1) {
      jQuery(this).cropper({
         aspectRatio: width / height,
         maxWidth: width,
         maxHeight: height,
         guides: false,
         background: false,
         dragCrop: false,
         rotatable: false,
         scalable: false,
         cropBoxResizable: false,
         modal: true,
         strict: true,
         highlight: true,
         autoCrop: true,
         cropBoxMovable: true,
         crop: function (e) {
          //  console.log(e);
            updateCoords(jQuery(this), e);
          }
      });

      var getData = jQuery(this).cropper('getCropBoxData');

      getData.width = parseInt(width);
      getData.height = parseInt(height);

      jQuery(this).cropper('setCropBoxData', getData);

      getData = jQuery(this).cropper('getCropBoxData');

      updateCoords(jQuery(this), getData);

    }

  });
  function post_form_data(data) {

        jQuery.ajax({
          type: 'POST',
          url: baseUrl + 'save.php',
          dataType:'json',
          data: {images: data},
          beforeSend: function() {
            jQuery("#saveAll").removeClass('btn-primary');
            jQuery("#saveAll").addClass('btn-success');
             jQuery("#saveAll").text('Saving...');
         },
          success: function(resp) {
            // console.log(resp);
            var file = resp.file;
            var width = resp.width;
            var height = resp.height;
            window.location.href = baseUrl + "show.php?file=" + file + '&w=' + width  + '&h=' + height;
          },
          error: function(e) {
            // console.log('error: ', e);
            jQuery("#saveAll").removeClass('btn-success');
            jQuery("#saveAll").addClass('btn-primary');
            jQuery("#saveAll").text('Save all');
          }
        });
  }
  jQuery("#saveAll").on('click', function(e) {
    var customImages = [];
    jQuery('.customizeImagesForms').each(function() {
      if (jQuery(this).find('img').attr('original') != 1) {

        customImages.push(jQuery(this).serializeArray());

      }
    });
    post_form_data(customImages);

  });

});
// Simple event handler, called from onChange and onSelect
// event handlers, as per the Jcrop invocation above
function showCoords(c) {}
<|endoftext|>


<commit_before>var fs = require('fs');
var u = require('util');
var c = require('chalk');
var redis = require('redis');
var pp = require('prttty');
var argv = require('minimist')(process.argv.slice(2));

var queueName = argv.q || argv.queue;
if(!queueName) {
	console.log("usage: node ./slurper.js --queue 'name'");
	process.exit(-1);
}

var client = redis.createClient();

function die(why){
	console.log(why);
	process.exit(-1);
}

function put_thing_in_thing()
{
	client.blpop(queueName, 0, function(err,data){

		if(err)
		{
			console.error(err);
			process.exit(-1);
		}

		var d = JSON.parse(data[1]);

		// select type
		var type = what_thing_is_this(d);

		console.log(type[0](type[1]), '=>', pp.render(d));

		do_thing_to_it(type[1], d);

	});
}

put_thing_in_thing();

function what_thing_is_this(data){

	var l = data.label;
	var t = data.type;

	if(l === "hg:liesIn")
		return [c.bgBlue, 'LIES_IN'];

	if(l === "hg:sameHgConcept")
		return [c.bgYellow, 'SAME_AS'];

	if (/^hg:/.test(t))
		return [c.bgCyan, 'PIT'];

	return [c.bgRed, 'UNKNOWN'];
}

function do_thing_to_it(type, data){

	var dataset = 'test';
	var uri = u.format('/%s/%s', dataset, type)
	if (data.id)
		uri += '/' + data.id;

	var request = require('request');
	var doc = data.data || data || {};

	if(data.name)
		doc.name = data.name;

	if(data.type)
		doc.hgType = data.type;

	if(data.geometry)
		delete data.geometry;
		// doc.geometry = docata.geometry;

	// var doc = {he:123, werkt: { niet: [1,2,3] }};

	console.log(c.bgWhite('REQ'), '=>', uri, pp.render(doc));
	request.post('http://localhost:5000' + uri, {form: {doc: doc}}, function(err,resp,body){
		var f = (body && JSON.parse(body).ok) ? c.bgGreen : c.bgRed;
		console.log(f('RES', '<=', body));
		// loop
		process.nextTick(put_thing_in_thing);
	});

}
<commit_msg>better dying<commit_after>var fs = require('fs');
var u = require('util');
var c = require('chalk');
var redis = require('redis');
var pp = require('prttty');
var argv = require('minimist')(process.argv.slice(2));

var queueName = argv.q || argv.queue;
if(!queueName) {
	console.log("usage: node ./slurper.js --queue 'name'");
	process.exit(-1);
}

var client = redis.createClient();

function die(err, why){
	if(err)
	{
		console.log(why);
		console.error(err);
		process.exit(-1);
	}
}

function put_thing_in_thing()
{
	client.blpop(queueName, 0, function(err,data){

		if(err)
		{
			console.error(err);
			process.exit(-1);
		}

		var d = JSON.parse(data[1]);

		// select type
		var type = what_thing_is_this(d);

		console.log(type[0](type[1]), '=>', pp.render(d));

		do_thing_to_it(type[1], d);

	});
}

put_thing_in_thing();

function what_thing_is_this(data){

	var l = data.label;
	var t = data.type;

	if(l === "hg:liesIn")
		return [c.bgBlue, 'LIES_IN'];

	if(l === "hg:sameHgConcept")
		return [c.bgYellow, 'SAME_AS'];

	if (/^hg:/.test(t))
		return [c.bgCyan, 'PIT'];

	return [c.bgRed, 'UNKNOWN'];
}

function do_thing_to_it(type, data){

	var dataset = 'test';
	var uri = u.format('/%s/%s', dataset, type)
	if (data.id)
		uri += '/' + data.id;

	var request = require('request');
	var doc = data.data || data || {};

	if(data.name)
		doc.name = data.name;

	if(data.type)
		doc.hgType = data.type;

	if(data.geometry)
		delete data.geometry;
		// doc.geometry = docata.geometry;

	// var doc = {he:123, werkt: { niet: [1,2,3] }};

	console.log(c.bgWhite('REQ'), '=>', uri, pp.render(doc));
	request.post('http://localhost:5000' + uri, {form: {doc: doc}}, function(err,resp,body){
		var f = (body && JSON.parse(body).ok) ? c.bgGreen : c.bgRed;
		console.log(f('RES', '<=', body));
		// loop
		process.nextTick(put_thing_in_thing);
	});

}
<|endoftext|>


<commit_before>'use strict';

var assert = require('assert'),
    express = require('express'),
    App = require('../');

/*
 * Simple helper function that creates a basic
 * app that mixes in express.
 */
function expressApp(port) {
  var options = typeof port === 'number'
    ? { http: port }
    : port;

  return new App(options, express());
}

describe('broadway', function () {
  it('should define the correct interface', function () {
    var app = new App();
    assert.ok(app.preboot);
    assert.ok(app.mixin);
    assert.ok(app.start);
    assert.ok(app.close);
    assert.ok(app._listen);
  });

  describe('new App(options?, [base])', function () {
    it('should accept only options', function () {
      var app = new App({ http: 8080 });
      assert.equal(app.options.http, 8080);
    });

    it('should accept options and a base', function () {
      var base = { method: function () { } },
          app = new App({ http: 8080 }, base);

      assert.equal(app.options.http, 8080);
      assert.equal(app.method, base.method);
    });
  });

  describe('.preboot(fn)', function () {
    it('should be called on an sync start', function () {
      var app = expressApp(8082);

      // Override this for testing purposes.
      app._listen = function (callback) { callback(); };

      var count = 0;
      app.preboot(function (app, options, next) {
        count++;
        next();
      });

      app.start(function (err) {
        assert.ok(!err);
        assert.equal(count, 1);
      });
    });
  });

  describe('.start([options], callback', function () {
    it('should mixin any options provided', function () {
      var app = new App();

      // Override this for testing purposes.
      app._listen = function (callback) { callback(); };

      app.start({ http: 8080 }, function (err) {
        assert.ok(!err);
        assert.equal(app.options.http, 8080);
      });
    });

    it('should listen on any port provided', function (done) {
      var app = expressApp(8081);

      app.start(function (err) {
        assert.ok(!err);
        assert.ok(app.servers);
        assert.ok(app.servers.http);
        done();
      });
    });

    it('should error if `app.handle` is not defined', function (done) {
      var app = new App({ http: 8081 });
      app.start(function (err) {
        assert.equal(err.message, 'A handle function must be defined.');
        done();
      });
    });
  });

  describe('.close(callback)', function () {
    it('should close a single HTTP server', function (done) {
      var app = expressApp(8083);
      app.start(function (err) {
        assert.ok(!err);
        app.close(function (err) {
          assert.ok(!err);
          done();
        });
      });
    });

    it('should close HTTP and HTTPS servers');

    it('should respnd with an error if a server fails', function (done) {
      var apps = {
        first: expressApp(8084),
        second: expressApp(8084)
      };

      apps.first.start(function (err) {
        assert.ok(!err);
        apps.second.start(function (err) {
          assert.ok(!err.https);
          assert.ok(err.http);
          assert.equal(err.http.code, 'EADDRINUSE');

          apps.first.close(done);
        });
      });
    });

    it('should respond with an error if no servers exist', function (done) {
      var app = expressApp(8085);

      // Override this for testing purposes.
      app._listen = function (callback) { callback(); };

      app.start(function (err) {
        assert.ok(!err);
        app.close(function (err) {
          assert.equal(err.message, 'No servers to close.');
          done();
        });
      });
    });
  });
});
<commit_msg>[test] Added unit tests for config shim and "preboot" perform.<commit_after>'use strict';

var assert = require('assert'),
    express = require('express'),
    App = require('../');

/*
 * Simple helper function that creates a basic
 * app that mixes in express.
 */
function expressApp(port) {
  var options = typeof port === 'number'
    ? { http: port }
    : port;

  return new App(options, express());
}

describe('broadway', function () {
  it('should define the correct interface', function () {
    var app = new App();
    assert.ok(app.preboot);
    assert.ok(app.mixin);
    assert.ok(app.start);
    assert.ok(app.close);
    assert.ok(app.config.get);
    assert.ok(app.perform);
    assert.ok(app._listen);
  });

  describe('new App(options?, [base])', function () {
    it('should accept only options', function () {
      var app = new App({ http: 8080 });
      assert.equal(app.options.http, 8080);
    });

    it('should accept options and a base', function () {
      var base = { method: function () { } },
          app = new App({ http: 8080 }, base);

      assert.equal(app.options.http, 8080);
      assert.equal(app.method, base.method);
    });

    it('should define a config shim', function () {
      var app = new App({ http: 8080 });
      assert.equal(app.config.get('http'), 8080);
    });
  });

  describe('.preboot(fn)', function () {
    it('should be called on an sync start', function () {
      var app = expressApp(8082);

      // Override this for testing purposes.
      app._listen = function (callback) { callback(); };

      var count = 0;
      app.preboot(function (app, options, next) {
        count++;
        next();
      });

      app.start(function (err) {
        assert.ok(!err);
        assert.equal(count, 1);
      });
    });
  });

  describe('.start([options], callback', function () {
    it('should mixin any options provided', function () {
      var app = new App();

      // Override this for testing purposes.
      app._listen = function (callback) { callback(); };

      app.start({ http: 8080 }, function (err) {
        assert.ok(!err);
        assert.equal(app.options.http, 8080);
      });
    });

    it('should listen on any port provided', function (done) {
      var app = expressApp(8081);

      app.start(function (err) {
        assert.ok(!err);
        assert.ok(app.servers);
        assert.ok(app.servers.http);
        done();
      });
    });

    it('should error if `app.handle` is not defined', function (done) {
      var app = new App({ http: 8082 });
      app.start(function (err) {
        assert.equal(err.message, 'A handle function must be defined.');
        done();
      });
    });

    it('should error if a `.before("preboot")` errors', function (done) {
      var app = new App({ http: 8090 });
      app.before('preboot', function (app, options, callback) {
        return callback(new Error('Bad preboot'));
      });

      app.start(function (err) {
        assert.ok(err);
        assert.equal(err.message, 'Bad preboot');
        done();
      });
    });
  });

  describe('.close(callback)', function () {
    it('should close a single HTTP server', function (done) {
      var app = expressApp(8083);
      app.start(function (err) {
        assert.ok(!err);
        app.close(function (err) {
          assert.ok(!err);
          done();
        });
      });
    });

    it('should close HTTP and HTTPS servers');

    it('should respnd with an error if a server fails', function (done) {
      var apps = {
        first: expressApp(8084),
        second: expressApp(8084)
      };

      apps.first.start(function (err) {
        assert.ok(!err);
        apps.second.start(function (err) {
          assert.ok(!err.https);
          assert.ok(err.http);
          assert.equal(err.http.code, 'EADDRINUSE');

          apps.first.close(done);
        });
      });
    });

    it('should respond with an error if no servers exist', function (done) {
      var app = expressApp(8085);

      // Override this for testing purposes.
      app._listen = function (callback) { callback(); };

      app.start(function (err) {
        assert.ok(!err);
        app.close(function (err) {
          assert.equal(err.message, 'No servers to close.');
          done();
        });
      });
    });
  });
});
<|endoftext|>