<commit_before>/*
 * Paper.js
 *
 * This file is part of Paper.js, a JavaScript Vector Graphics Library,
 * based on Scriptographer.org and designed to be largely API compatible.
 * http://paperjs.org/
 * http://scriptographer.org/
 *
 * Copyright (c) 2011, Juerg Lehni & Jonathan Puckey
 * http://lehni.org/ & http://jonathanpuckey.com/
 *
 * Distributed under the MIT license. See LICENSE file for details.
 *
 * All rights reserved.
 */

/**
 * @name Segment
 *
 * @class The Segment object represents the points of a path through which its
 * {@link Curve} objects pass. The segments of a path can be accessed through
 * its {@link Path#segments} array.
 *
 * Each segment consists of an anchor point ({@link Segment#point}) and
 * optionaly an incoming and an outgoing handle ({@link Segment#handleIn} and
 * {@link Segment#handleOut}), describing the tangents of the two {@link Curve}
 * objects that are connected by this segment.
 */
var Segment = this.Segment = Base.extend(/** @lends Segment# */{
	/**
	 * Creates a new Segment object.
	 *
	 * @param {Point} [point={x: 0, y: 0}] the anchor point of the segment
	 * @param {Point} [handleIn={x: 0, y: 0}] the handle point relative to the
	 *        anchor point of the segment that describes the in tangent of the
	 *        segment.
	 * @param {Point} [handleOut={x: 0, y: 0}] the handle point relative to the
	 *        anchor point of the segment that describes the out tangent of the
	 *        segment.
	 *
	 * @example {@paperscript}
	 * var handleIn = new Point(-80, -100);
	 * var handleOut = new Point(80, 100);
	 *
	 * var firstPoint = new Point(100, 50);
	 * var firstSegment = new Segment(firstPoint, null, handleOut);
	 *
	 * var secondPoint = new Point(300, 50);
	 * var secondSegment = new Segment(secondPoint, handleIn, null);
	 *
	 * var path = new Path(firstSegment, secondSegment);
	 * path.strokeColor = 'black';
	 */
	initialize: function(arg0, arg1, arg2, arg3, arg4, arg5) {
		var count = arguments.length,
			createPoint = SegmentPoint.create,
			point, handleIn, handleOut;
		if (count == 0) {
			// Nothing
		} else if (count == 1) {
			// TODO: If beans are not activated, this won't copy from existing
			// segments. OK?
			if (arg0.point) {
				point = arg0.point;
				handleIn = arg0.handleIn;
				handleOut = arg0.handleOut;
			} else {
				point = arg0;
			}
		} else if (count < 6) {
			if (count == 2 && arg1.x === undefined) {
				point = [ arg0, arg1 ];
			} else {
				point = arg0;
				// Doesn't matter if these arguments exist, SegmentPointcreate
				// produces creates points with (0, 0) otherwise
				handleIn = arg1;
				handleOut = arg2;
			}
		} else if (count == 6) {
			point = [ arg0, arg1 ];
			handleIn = [ arg2, arg3 ];
			handleOut = [ arg4, arg5 ];
		}
		createPoint(this, '_point', point);
		createPoint(this, '_handleIn', handleIn);
		createPoint(this, '_handleOut', handleOut);
	},

	_changed: function(point) {
		if (!this._path)
			return;
		// Delegate changes to affected curves if they exist
		var curve = this._path._curves && this.getCurve(), other;
		if (curve) {
			curve._changed();
			// Get the other affected curve, which is the previous one for
			// _point or _handleIn changing when this segment is _segment1 of
			// the curve, for all other cases it's the next (e.g. _handleOut
			// when this segment is _segment2)
			if (other = (curve[point == this._point
					|| point == this._handleIn && curve._segment1 == this
					? 'getPrevious' : 'getNext']())) {
				other._changed();
			}
		}
		this._path._changed(Change.GEOMETRY);
	},

	/**
	 * The anchor point of the segment.
	 *
	 * @type Point
	 * @bean
	 */
	getPoint: function() {
		return this._point;
	},

	setPoint: function(point) {
		point = Point.read(arguments);
		// Do not replace the internal object but update it instead, so
		// references to it are kept alive.
		this._point.set(point.x, point.y);
	},

	/**
	 * The handle point relative to the anchor point of the segment that
	 * describes the in tangent of the segment.
	 *
	 * @type Point
	 * @bean
	 */
	getHandleIn: function() {
		return this._handleIn;
	},

	setHandleIn: function(point) {
		point = Point.read(arguments);
		// See #setPoint:
		this._handleIn.set(point.x, point.y);
		// Update corner accordingly
		// this.corner = !this._handleIn.isColinear(this._handleOut);
	},

	/**
	 * The handle point relative to the anchor point of the segment that
	 * describes the out tangent of the segment.
	 *
	 * @type Point
	 * @bean
	 */
	getHandleOut: function() {
		return this._handleOut;
	},

	setHandleOut: function(point) {
		point = Point.read(arguments);
		// See #setPoint:
		this._handleOut.set(point.x, point.y);
		// Update corner accordingly
		// this.corner = !this._handleIn.isColinear(this._handleOut);
	},

	_isSelected: function(point) {
		var state = this._selectionState;
		return point == this._point ? !!(state & SelectionState.POINT)
			: point == this._handleIn ? !!(state & SelectionState.HANDLE_IN)
			: point == this._handleOut ? !!(state & SelectionState.HANDLE_OUT)
			: false;
	},

	_setSelected: function(point, selected) {
		var path = this._path,
			selected = !!selected, // convert to boolean
			state = this._selectionState || 0,
			// For performance reasons use array indices to access the various
			// selection states: 0 = point, 1 = handleIn, 2 = handleOut
			selection = [
				!!(state & SelectionState.POINT),
				!!(state & SelectionState.HANDLE_IN),
				!!(state & SelectionState.HANDLE_OUT)
			];
		if (point == this._point) {
			if (selected) {
				// We're selecting point, deselect the handles
				selection[1] = selection[2] = false;
			} else {
				var previous = this.getPrevious(),
					next = this.getNext();
				// When deselecting a point, the handles get selected instead
				// depending on the selection state of their neighbors.
				selection[1] = previous && (previous._point.isSelected()
						|| previous._handleOut.isSelected());
				selection[2] = next && (next._point.isSelected()
						|| next._handleIn.isSelected());
			}
			selection[0] = selected;
		} else {
			var index = point == this._handleIn ? 1 : 2;
			if (selection[index] != selected) {
				// When selecting handles, the point get deselected.
				if (selected)
					selection[0] = false;
				selection[index] = selected;
				// Let path know that we changed something and the view
				// should be redrawn
				path._changed(Change.ATTRIBUTE);
			}
		}
		this._selectionState = (selection[0] ? SelectionState.POINT : 0)
				| (selection[1] ? SelectionState.HANDLE_IN : 0)
				| (selection[2] ? SelectionState.HANDLE_OUT : 0);
		// If the selection state of the segment has changed, we need to let
		// it's path know and possibly add or remove it from
		// project._selectedItems
		if (path && state != this._selectionState)
			path._updateSelection(this, state, this._selectionState);
	},

	/**
	 * Specifies whether the {@link #point} of the segment is selected.
	 * @type Boolean
	 * @bean
	 */
	isSelected: function() {
		return this._isSelected(this._point);
	},

	setSelected: function(selected) {
		this._setSelected(this._point, selected);
	},

	/**
	 * {@grouptitle Hierarchy}
	 *
	 * The index of the segment in the {@link Path#segments} array that the
	 * segment belongs to.
	 *
	 * @type Number
	 * @bean
	 */
	getIndex: function() {
		return this._index !== undefined ? this._index : null;
	},

	/**
	 * The path that the segment belongs to.
	 *
	 * @type Path
	 * @bean
	 */
	getPath: function() {
		return this._path || null;
	},

	/**
	 * The curve that the segment belongs to.
	 *
	 * @type Curve
	 * @bean
	 */
	getCurve: function() {
		if (this._path) {
			var index = this._index;
			// The last segment of an open path belongs to the last curve
			if (!this._path._closed && index == this._path._segments.length - 1)
				index--;
			return this._path.getCurves()[index] || null;
		}
		return null;
	},

	/**
	 * {@grouptitle Sibling Segments}
	 *
	 * The next segment in the {@link Path#segments} array that the segment
	 * belongs to. If the segments belongs to a closed path, the first segment
	 * is returned for the last segment of the path.
	 *
	 * @type Segment
	 * @bean
	 */
	getNext: function() {
		var segments = this._path && this._path._segments;
		return segments && (segments[this._index + 1]
				|| this._path._closed && segments[0]) || null;
	},

	/**
	 * The previous segment in the {@link Path#segments} array that the
	 * segment belongs to. If the segments belongs to a closed path, the last
	 * segment is returned for the first segment of the path.
	 *
	 * @type Segment
	 * @bean
	 */
	getPrevious: function() {
		var segments = this._path && this._path._segments;
		return segments && (segments[this._index - 1]
				|| this._path._closed && segments[segments.length - 1]) || null;
	},

	/**
	 * Returns the reversed the segment, without modifying the segment itself.
	 * @return {Segment} the reversed segment
	 */
	reverse: function() {
		return new Segment(this._point, this._handleOut, this._handleIn);
	},

	/**
	 * Removes the segment from the path that it belongs to.
	 */
	remove: function() {
		return this._path ? !!this._path.removeSegment(this._index) : false;
	},

	equals: function(segment) {
		return segment == this || segment
				&& this._point.equals(segment._point)
				&& this._handleIn.equals(segment._handleIn)
				&& this._handleOut.equals(segment._handleOut);
	},

	/**
	 * @return {String} A string representation of the segment.
	 */
	toString: function() {
		var parts = [ 'point: ' + this._point ];
		if (!this._handleIn.isZero())
			parts.push('handleIn: ' + this._handleIn);
		if (!this._handleOut.isZero())
			parts.push('handleOut: ' + this._handleOut);
		return '{ ' + parts.join(', ') + ' }';
	},

	_transformCoordinates: function(matrix, coords, change) {
		// Use matrix.transform version() that takes arrays of multiple
		// points for largely improved performance, as no calls to
		// Point.read() and Point constructors are necessary.
		var point = this._point,
			// If change is true, only transform handles if they are set, as
			// _transformCoordinates is called only to change the segment, no
			// to receive the coords.
			// This saves some computation time. If change is false, always
			// use the real handles, as we just want to receive a filled
			// coords array for getBounds().
			handleIn =  !change || !this._handleIn.isZero()
					? this._handleIn : null,
			handleOut = !change || !this._handleOut.isZero()
					? this._handleOut : null,
			x = point._x,
			y = point._y,
			i = 2;
		coords[0] = x;
		coords[1] = y;
		// We need to convert handles to absolute coordinates in order
		// to transform them.
		if (handleIn) {
			coords[i++] = handleIn._x + x;
			coords[i++] = handleIn._y + y;
		}
		if (handleOut) {
			coords[i++] = handleOut._x + x;
			coords[i++] = handleOut._y + y;
		}
		// If no matrix was previded, this was just called to get the coords and
		// we are done now.
		if (!matrix)
			return;
		matrix._transformCoordinates(coords, 0, coords, 0, i / 2);
		x = coords[0];
		y = coords[1];
		if (change) {
			// If change is true, we need to set the new values back
			point._x = x;
			point._y = y;
			i  = 2;
			if (handleIn) {
				handleIn._x = coords[i++] - x;
				handleIn._y = coords[i++] - y;
			}
			if (handleOut) {
				handleOut._x = coords[i++] - x;
				handleOut._y = coords[i++] - y;
			}
		} else {
			// We want to receive the results in coords, so make sure
			// handleIn and out are defined too, even if they're 0
			if (!handleIn) {
				coords[i++] = x;
				coords[i++] = y;
			}
			if (!handleOut) {
				coords[i++] = x;
				coords[i++] = y;
			}
		}
	}
});
<commit_msg>Define Segment#clone().<commit_after>/*
 * Paper.js
 *
 * This file is part of Paper.js, a JavaScript Vector Graphics Library,
 * based on Scriptographer.org and designed to be largely API compatible.
 * http://paperjs.org/
 * http://scriptographer.org/
 *
 * Copyright (c) 2011, Juerg Lehni & Jonathan Puckey
 * http://lehni.org/ & http://jonathanpuckey.com/
 *
 * Distributed under the MIT license. See LICENSE file for details.
 *
 * All rights reserved.
 */

/**
 * @name Segment
 *
 * @class The Segment object represents the points of a path through which its
 * {@link Curve} objects pass. The segments of a path can be accessed through
 * its {@link Path#segments} array.
 *
 * Each segment consists of an anchor point ({@link Segment#point}) and
 * optionaly an incoming and an outgoing handle ({@link Segment#handleIn} and
 * {@link Segment#handleOut}), describing the tangents of the two {@link Curve}
 * objects that are connected by this segment.
 */
var Segment = this.Segment = Base.extend(/** @lends Segment# */{
	/**
	 * Creates a new Segment object.
	 *
	 * @param {Point} [point={x: 0, y: 0}] the anchor point of the segment
	 * @param {Point} [handleIn={x: 0, y: 0}] the handle point relative to the
	 *        anchor point of the segment that describes the in tangent of the
	 *        segment.
	 * @param {Point} [handleOut={x: 0, y: 0}] the handle point relative to the
	 *        anchor point of the segment that describes the out tangent of the
	 *        segment.
	 *
	 * @example {@paperscript}
	 * var handleIn = new Point(-80, -100);
	 * var handleOut = new Point(80, 100);
	 *
	 * var firstPoint = new Point(100, 50);
	 * var firstSegment = new Segment(firstPoint, null, handleOut);
	 *
	 * var secondPoint = new Point(300, 50);
	 * var secondSegment = new Segment(secondPoint, handleIn, null);
	 *
	 * var path = new Path(firstSegment, secondSegment);
	 * path.strokeColor = 'black';
	 */
	initialize: function(arg0, arg1, arg2, arg3, arg4, arg5) {
		var count = arguments.length,
			createPoint = SegmentPoint.create,
			point, handleIn, handleOut;
		if (count == 0) {
			// Nothing
		} else if (count == 1) {
			// TODO: If beans are not activated, this won't copy from existing
			// segments. OK?
			if (arg0.point) {
				point = arg0.point;
				handleIn = arg0.handleIn;
				handleOut = arg0.handleOut;
			} else {
				point = arg0;
			}
		} else if (count < 6) {
			if (count == 2 && arg1.x === undefined) {
				point = [ arg0, arg1 ];
			} else {
				point = arg0;
				// Doesn't matter if these arguments exist, SegmentPointcreate
				// produces creates points with (0, 0) otherwise
				handleIn = arg1;
				handleOut = arg2;
			}
		} else if (count == 6) {
			point = [ arg0, arg1 ];
			handleIn = [ arg2, arg3 ];
			handleOut = [ arg4, arg5 ];
		}
		createPoint(this, '_point', point);
		createPoint(this, '_handleIn', handleIn);
		createPoint(this, '_handleOut', handleOut);
	},

	_changed: function(point) {
		if (!this._path)
			return;
		// Delegate changes to affected curves if they exist
		var curve = this._path._curves && this.getCurve(), other;
		if (curve) {
			curve._changed();
			// Get the other affected curve, which is the previous one for
			// _point or _handleIn changing when this segment is _segment1 of
			// the curve, for all other cases it's the next (e.g. _handleOut
			// when this segment is _segment2)
			if (other = (curve[point == this._point
					|| point == this._handleIn && curve._segment1 == this
					? 'getPrevious' : 'getNext']())) {
				other._changed();
			}
		}
		this._path._changed(Change.GEOMETRY);
	},

	/**
	 * The anchor point of the segment.
	 *
	 * @type Point
	 * @bean
	 */
	getPoint: function() {
		return this._point;
	},

	setPoint: function(point) {
		point = Point.read(arguments);
		// Do not replace the internal object but update it instead, so
		// references to it are kept alive.
		this._point.set(point.x, point.y);
	},

	/**
	 * The handle point relative to the anchor point of the segment that
	 * describes the in tangent of the segment.
	 *
	 * @type Point
	 * @bean
	 */
	getHandleIn: function() {
		return this._handleIn;
	},

	setHandleIn: function(point) {
		point = Point.read(arguments);
		// See #setPoint:
		this._handleIn.set(point.x, point.y);
		// Update corner accordingly
		// this.corner = !this._handleIn.isColinear(this._handleOut);
	},

	/**
	 * The handle point relative to the anchor point of the segment that
	 * describes the out tangent of the segment.
	 *
	 * @type Point
	 * @bean
	 */
	getHandleOut: function() {
		return this._handleOut;
	},

	setHandleOut: function(point) {
		point = Point.read(arguments);
		// See #setPoint:
		this._handleOut.set(point.x, point.y);
		// Update corner accordingly
		// this.corner = !this._handleIn.isColinear(this._handleOut);
	},

	_isSelected: function(point) {
		var state = this._selectionState;
		return point == this._point ? !!(state & SelectionState.POINT)
			: point == this._handleIn ? !!(state & SelectionState.HANDLE_IN)
			: point == this._handleOut ? !!(state & SelectionState.HANDLE_OUT)
			: false;
	},

	_setSelected: function(point, selected) {
		var path = this._path,
			selected = !!selected, // convert to boolean
			state = this._selectionState || 0,
			// For performance reasons use array indices to access the various
			// selection states: 0 = point, 1 = handleIn, 2 = handleOut
			selection = [
				!!(state & SelectionState.POINT),
				!!(state & SelectionState.HANDLE_IN),
				!!(state & SelectionState.HANDLE_OUT)
			];
		if (point == this._point) {
			if (selected) {
				// We're selecting point, deselect the handles
				selection[1] = selection[2] = false;
			} else {
				var previous = this.getPrevious(),
					next = this.getNext();
				// When deselecting a point, the handles get selected instead
				// depending on the selection state of their neighbors.
				selection[1] = previous && (previous._point.isSelected()
						|| previous._handleOut.isSelected());
				selection[2] = next && (next._point.isSelected()
						|| next._handleIn.isSelected());
			}
			selection[0] = selected;
		} else {
			var index = point == this._handleIn ? 1 : 2;
			if (selection[index] != selected) {
				// When selecting handles, the point get deselected.
				if (selected)
					selection[0] = false;
				selection[index] = selected;
				// Let path know that we changed something and the view
				// should be redrawn
				path._changed(Change.ATTRIBUTE);
			}
		}
		this._selectionState = (selection[0] ? SelectionState.POINT : 0)
				| (selection[1] ? SelectionState.HANDLE_IN : 0)
				| (selection[2] ? SelectionState.HANDLE_OUT : 0);
		// If the selection state of the segment has changed, we need to let
		// it's path know and possibly add or remove it from
		// project._selectedItems
		if (path && state != this._selectionState)
			path._updateSelection(this, state, this._selectionState);
	},

	/**
	 * Specifies whether the {@link #point} of the segment is selected.
	 * @type Boolean
	 * @bean
	 */
	isSelected: function() {
		return this._isSelected(this._point);
	},

	setSelected: function(selected) {
		this._setSelected(this._point, selected);
	},

	/**
	 * {@grouptitle Hierarchy}
	 *
	 * The index of the segment in the {@link Path#segments} array that the
	 * segment belongs to.
	 *
	 * @type Number
	 * @bean
	 */
	getIndex: function() {
		return this._index !== undefined ? this._index : null;
	},

	/**
	 * The path that the segment belongs to.
	 *
	 * @type Path
	 * @bean
	 */
	getPath: function() {
		return this._path || null;
	},

	/**
	 * The curve that the segment belongs to.
	 *
	 * @type Curve
	 * @bean
	 */
	getCurve: function() {
		if (this._path) {
			var index = this._index;
			// The last segment of an open path belongs to the last curve
			if (!this._path._closed && index == this._path._segments.length - 1)
				index--;
			return this._path.getCurves()[index] || null;
		}
		return null;
	},

	/**
	 * {@grouptitle Sibling Segments}
	 *
	 * The next segment in the {@link Path#segments} array that the segment
	 * belongs to. If the segments belongs to a closed path, the first segment
	 * is returned for the last segment of the path.
	 *
	 * @type Segment
	 * @bean
	 */
	getNext: function() {
		var segments = this._path && this._path._segments;
		return segments && (segments[this._index + 1]
				|| this._path._closed && segments[0]) || null;
	},

	/**
	 * The previous segment in the {@link Path#segments} array that the
	 * segment belongs to. If the segments belongs to a closed path, the last
	 * segment is returned for the first segment of the path.
	 *
	 * @type Segment
	 * @bean
	 */
	getPrevious: function() {
		var segments = this._path && this._path._segments;
		return segments && (segments[this._index - 1]
				|| this._path._closed && segments[segments.length - 1]) || null;
	},

	/**
	 * Returns the reversed the segment, without modifying the segment itself.
	 * @return {Segment} the reversed segment
	 */
	reverse: function() {
		return new Segment(this._point, this._handleOut, this._handleIn);
	},

	/**
	 * Removes the segment from the path that it belongs to.
	 */
	remove: function() {
		return this._path ? !!this._path.removeSegment(this._index) : false;
	},

	clone: function() {
		return new Segment(this._point, this._handleIn, this._handleOut);
	},

	equals: function(segment) {
		return segment == this || segment
				&& this._point.equals(segment._point)
				&& this._handleIn.equals(segment._handleIn)
				&& this._handleOut.equals(segment._handleOut);
	},

	/**
	 * @return {String} A string representation of the segment.
	 */
	toString: function() {
		var parts = [ 'point: ' + this._point ];
		if (!this._handleIn.isZero())
			parts.push('handleIn: ' + this._handleIn);
		if (!this._handleOut.isZero())
			parts.push('handleOut: ' + this._handleOut);
		return '{ ' + parts.join(', ') + ' }';
	},

	_transformCoordinates: function(matrix, coords, change) {
		// Use matrix.transform version() that takes arrays of multiple
		// points for largely improved performance, as no calls to
		// Point.read() and Point constructors are necessary.
		var point = this._point,
			// If change is true, only transform handles if they are set, as
			// _transformCoordinates is called only to change the segment, no
			// to receive the coords.
			// This saves some computation time. If change is false, always
			// use the real handles, as we just want to receive a filled
			// coords array for getBounds().
			handleIn =  !change || !this._handleIn.isZero()
					? this._handleIn : null,
			handleOut = !change || !this._handleOut.isZero()
					? this._handleOut : null,
			x = point._x,
			y = point._y,
			i = 2;
		coords[0] = x;
		coords[1] = y;
		// We need to convert handles to absolute coordinates in order
		// to transform them.
		if (handleIn) {
			coords[i++] = handleIn._x + x;
			coords[i++] = handleIn._y + y;
		}
		if (handleOut) {
			coords[i++] = handleOut._x + x;
			coords[i++] = handleOut._y + y;
		}
		// If no matrix was previded, this was just called to get the coords and
		// we are done now.
		if (!matrix)
			return;
		matrix._transformCoordinates(coords, 0, coords, 0, i / 2);
		x = coords[0];
		y = coords[1];
		if (change) {
			// If change is true, we need to set the new values back
			point._x = x;
			point._y = y;
			i  = 2;
			if (handleIn) {
				handleIn._x = coords[i++] - x;
				handleIn._y = coords[i++] - y;
			}
			if (handleOut) {
				handleOut._x = coords[i++] - x;
				handleOut._y = coords[i++] - y;
			}
		} else {
			// We want to receive the results in coords, so make sure
			// handleIn and out are defined too, even if they're 0
			if (!handleIn) {
				coords[i++] = x;
				coords[i++] = y;
			}
			if (!handleOut) {
				coords[i++] = x;
				coords[i++] = y;
			}
		}
	}
});
<|endoftext|>


<commit_before>// This is the controller for the individual date ideas - i.e. the one that has all the Foursquare venue details,
// including the address, opening hours, and map.

angular.module('dateworthy.idea', ['ngOpenFB', 'ngCordova'])

.controller('IdeaCtrl', ['$ionicHistory', '$state', '$location', '$q', '$scope', '$rootScope','$stateParams', 'DateData', 'LikeADate', 'FlagADate', function($ionicHistory, $state, $location, $q, $scope, $rootScope, $stateParams, DateData, LikeADate, FlagADate) {
  $scope.ideas = {};

  $scope.initMap = function(latitude, longitude, name){
    //console.log($scope.idea);
    //console.log("Initiating Map...", latitude, longitude);
    var myLatlng = new google.maps.LatLng(latitude, longitude);
    var mapOptions = {
        draggable: false,
        scrollwheel: false,
        center: myLatlng,
        zoom: 16,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var venueMap = new google.maps.Map(document.getElementById("venueMap" + $stateParams.ideaId), mapOptions);
    navigator.geolocation.getCurrentPosition(function(pos) {
      venueMap.setCenter(new google.maps.LatLng(latitude, longitude));
      var myLocation = new google.maps.Marker({
          position: new google.maps.LatLng(latitude, longitude),
          map: venueMap,
          title: name
      });
    });
    $scope["venueMap" + $stateParams.ideaId] = venueMap;
    $scope.idea.mapInit = true;
  };

  $scope.$on('$stateChangeSuccess', function() {
    if ($state.includes('idea')) {
      $scope.ideaOrFavorite = 'idea';
      DateData.getDateIdeas(function(ideas) {
        $scope.ideas = ideas;
        console.log($scope.ideas);
        $scope.currentIdea = Number($stateParams.ideaId);
        $scope.imgWidth = window.innerWidth + 'px';
        console.log("innerwidth is", $scope.imgWidth);
        $scope.idea = $scope.ideas[$scope.currentIdea];
        if(!$scope.idea.imgUrl){
          $scope.idea.imgUrl = "./img/placeholder.jpg";
        }
        $scope.idea.index = $scope.currentIdea;
        $scope.idea.last = false;
        $scope.idea.mapInit = false;
        $scope.idea.flagged = $scope.idea.flagged || false;
        console.log("$scope.idea.index", $scope.idea.index);
        if ($scope.idea.index === $scope.ideas.length - 1) {
          $scope.idea.last = true;
        }
        $scope.idea.detailsVisible = false;
      });
    } else if ($state.includes('favorite-single')) {
      $scope.ideaOrFavorite = 'favorite';
      $scope.imgWidth = window.innerWidth + 'px';
      console.log("innerwidth is", $scope.imgWidth);
      $scope.idea = DateData.favorite;
      $scope.idea.index = $stateParams.ideaId;
      $scope.idea.last = true;
      $scope.idea.mapInit = false;
      console.log($scope.idea);
      $scope.idea.flagged = $scope.idea.flagged || false;
      $scope.idea.detailsVisible = false;
    }
  });

  $scope.currentIdea = 0;

  $scope.showDetails = function() {
    console.log("Details should be vis now");
    $scope.idea.detailsVisible = true;
    console.log("$scope.idea.detailsVisible", $scope.idea.detailsVisible);
  }

  $scope.like = function() {
    var currentIdea = $scope.currentIdea;
    $scope.ideas[currentIdea].liked = 1;
    $scope.ideas[currentIdea].disliked = 0;
    var tagnames = DateData.getTags();
    for (var prop in tagnames) {
      if(tagnames[prop] !== undefined){
        LikeADate.increaseTagWeight(tagnames[prop], function(results){console.log(results)});
      }
    };
    LikeADate.markLikeDislike($scope.ideas[currentIdea].dateIdeaID, 1);
  }

  $scope.dislike = function() {
    var currentIdea = $scope.currentIdea;
    $scope.ideas[$scope.currentIdea].disliked = 1;
    $scope.ideas[$scope.currentIdea].liked = 0;
    var tagnames = DateData.getTags();
    for (var prop in tagnames) {
      if(tagnames[prop] !== undefined){
        LikeADate.decreaseTagWeight(tagnames[prop], function(results){console.log(results)});
      }
    };
    LikeADate.markLikeDislike($scope.ideas[currentIdea].dateIdeaID, -1);
  };

  $scope.flagDate = function() {
    var dateIdeaID = $scope.ideas[$scope.currentIdea].dateIdeaID;
    FlagADate.flagDate(dateIdeaID, function() {
      $scope.idea.flagged = true;
    });
  };

  $scope.nextIdea= function(){
    var next = Number($scope.currentIdea) + 1;
    $state.go('idea', {ideaId: next});
  };

  $scope.prevIdea= function(){
    if($scope.ideaOrFavorite === 'idea'){
      var prev = Number($scope.currentIdea) - 1;
      $state.go('idea', {ideaId: prev});
    } else {
      var lastPage = $rootScope.history.pop();
      $location.path(lastPage);
    }
  };

  $scope.showFavorites = function(){
    if($scope.userData && $scope.userData.email === "thenefariouschicken@gmail.com"){
      return false;
    } else {
      return true;
    }
  };
  $scope.clearData = function(){
    $scope.ideas = [];
    $scope.currentIdea = 0;
    DateData.clearData();
    $state.go('home');
  };

  $scope.savedLikes = function() {
    $rootScope.history.push($location.$$path);
    $state.go('favorites');
  }

}]);

<commit_msg>(fix) let users drag the map around on the idea page<commit_after>// This is the controller for the individual date ideas - i.e. the one that has all the Foursquare venue details,
// including the address, opening hours, and map.

angular.module('dateworthy.idea', ['ngOpenFB', 'ngCordova'])

.controller('IdeaCtrl', ['$ionicHistory', '$state', '$location', '$q', '$scope', '$rootScope','$stateParams', 'DateData', 'LikeADate', 'FlagADate', function($ionicHistory, $state, $location, $q, $scope, $rootScope, $stateParams, DateData, LikeADate, FlagADate) {
  $scope.ideas = {};

  $scope.initMap = function(latitude, longitude, name){
    //console.log($scope.idea);
    //console.log("Initiating Map...", latitude, longitude);
    var myLatlng = new google.maps.LatLng(latitude, longitude);
    var mapOptions = {
        draggable: true,
        scrollwheel: false,
        center: myLatlng,
        zoom: 16,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var venueMap = new google.maps.Map(document.getElementById("venueMap" + $stateParams.ideaId), mapOptions);
    navigator.geolocation.getCurrentPosition(function(pos) {
      venueMap.setCenter(new google.maps.LatLng(latitude, longitude));
      var myLocation = new google.maps.Marker({
          position: new google.maps.LatLng(latitude, longitude),
          map: venueMap,
          title: name
      });
    });
    $scope["venueMap" + $stateParams.ideaId] = venueMap;
    $scope.idea.mapInit = true;
  };

  $scope.$on('$stateChangeSuccess', function() {
    if ($state.includes('idea')) {
      $scope.ideaOrFavorite = 'idea';
      DateData.getDateIdeas(function(ideas) {
        $scope.ideas = ideas;
        console.log($scope.ideas);
        $scope.currentIdea = Number($stateParams.ideaId);
        $scope.imgWidth = window.innerWidth + 'px';
        console.log("innerwidth is", $scope.imgWidth);
        $scope.idea = $scope.ideas[$scope.currentIdea];
        if(!$scope.idea.imgUrl){
          $scope.idea.imgUrl = "./img/placeholder.jpg";
        }
        $scope.idea.index = $scope.currentIdea;
        $scope.idea.last = false;
        $scope.idea.mapInit = false;
        $scope.idea.flagged = $scope.idea.flagged || false;
        console.log("$scope.idea.index", $scope.idea.index);
        if ($scope.idea.index === $scope.ideas.length - 1) {
          $scope.idea.last = true;
        }
        $scope.idea.detailsVisible = false;
      });
    } else if ($state.includes('favorite-single')) {
      $scope.ideaOrFavorite = 'favorite';
      $scope.imgWidth = window.innerWidth + 'px';
      console.log("innerwidth is", $scope.imgWidth);
      $scope.idea = DateData.favorite;
      $scope.idea.index = $stateParams.ideaId;
      $scope.idea.last = true;
      $scope.idea.mapInit = false;
      console.log($scope.idea);
      $scope.idea.flagged = $scope.idea.flagged || false;
      $scope.idea.detailsVisible = false;
    }
  });

  $scope.currentIdea = 0;

  $scope.showDetails = function() {
    console.log("Details should be vis now");
    $scope.idea.detailsVisible = true;
    console.log("$scope.idea.detailsVisible", $scope.idea.detailsVisible);
  }

  $scope.like = function() {
    var currentIdea = $scope.currentIdea;
    $scope.ideas[currentIdea].liked = 1;
    $scope.ideas[currentIdea].disliked = 0;
    var tagnames = DateData.getTags();
    for (var prop in tagnames) {
      if(tagnames[prop] !== undefined){
        LikeADate.increaseTagWeight(tagnames[prop], function(results){console.log(results)});
      }
    };
    LikeADate.markLikeDislike($scope.ideas[currentIdea].dateIdeaID, 1);
  }

  $scope.dislike = function() {
    var currentIdea = $scope.currentIdea;
    $scope.ideas[$scope.currentIdea].disliked = 1;
    $scope.ideas[$scope.currentIdea].liked = 0;
    var tagnames = DateData.getTags();
    for (var prop in tagnames) {
      if(tagnames[prop] !== undefined){
        LikeADate.decreaseTagWeight(tagnames[prop], function(results){console.log(results)});
      }
    };
    LikeADate.markLikeDislike($scope.ideas[currentIdea].dateIdeaID, -1);
  };

  $scope.flagDate = function() {
    var dateIdeaID = $scope.ideas[$scope.currentIdea].dateIdeaID;
    FlagADate.flagDate(dateIdeaID, function() {
      $scope.idea.flagged = true;
    });
  };

  $scope.nextIdea= function(){
    var next = Number($scope.currentIdea) + 1;
    $state.go('idea', {ideaId: next});
  };

  $scope.prevIdea= function(){
    if($scope.ideaOrFavorite === 'idea'){
      var prev = Number($scope.currentIdea) - 1;
      $state.go('idea', {ideaId: prev});
    } else {
      var lastPage = $rootScope.history.pop();
      $location.path(lastPage);
    }
  };

  $scope.showFavorites = function(){
    if($scope.userData && $scope.userData.email === "thenefariouschicken@gmail.com"){
      return false;
    } else {
      return true;
    }
  };
  $scope.clearData = function(){
    $scope.ideas = [];
    $scope.currentIdea = 0;
    DateData.clearData();
    $state.go('home');
  };

  $scope.savedLikes = function() {
    $rootScope.history.push($location.$$path);
    $state.go('favorites');
  }

}]);

<|endoftext|>


<commit_before>/**
 * @namespace Lyria
 * Lyria namespace decleration
 */
define('lyria/prefab', ['lyria/scene'], function(Scene) {
	'use strict';

  // TODO: Allow own Prefab.requireAlways similar to Scene.requireAlways

	//Lyria.Prefab
	return Scene;

});<commit_msg>lyria/prefab is now an anonymous module<commit_after>/**
 * @namespace Lyria
 * Lyria namespace decleration
 */
define(['lyria/scene'], function(Scene) {
	'use strict';

  // TODO: Allow own Prefab.requireAlways similar to Scene.requireAlways

	//Lyria.Prefab
	return Scene;

});<|endoftext|>


<commit_before>;(function(){

    var unwanted_sources = [
        "assets.adobedtm.com",
        "demdex.net", // cpex.demdex.net, fast.cpex.demdex.net
        "gemius.pl",  // gacz.hut.gemius.pl, ls.hit.gemius.pl
        "adform.net",
        "ib.adnxs.com",
        "pixel.yabidos.com",
        "amazonaws.com",
        "bbnaut.ibillboard.com",
        "bbelements.com" // go.eu.bbelements.com
    ]

    var unwanted_ids = [
        "gemius",
        "bmone2t",
        "adform-adbox",
        "bannery300x300",
        "bannery160x600P",
        "bbswfcontainer",
        "cboxOverlay",
        "colorbox",
        "adfrom",
        "bmone2n"
    ]

    var removeIfUnwanted = function (node) {
        if (node.id) {
            for (var i = 0; i < unwanted_ids.length; i++) {
                if (node.id.indexOf(unwanted_ids[i]) !== -1) {
                    node.remove()
                    return true
                }
            }
        }

        if (node.localName === "object" && node.data) {
            node.src = node.data
        }

        if (node.localName === "script" || node.localName === "iframe" || node.localName === "object") {
            for (var i = 0; i < unwanted_sources.length; i++) {
                var unwanted_source = unwanted_sources[i]
                if (node.src.indexOf(unwanted_source) !== -1) {
                    node.remove()
                    return true
                }
            }
        }

        return false
    }

    /*var logMutation = function (mutation, removed) {
        return
        console.log("mutation")
        console.log("    type:        ", mutation.type)
        console.log("    target:      ", mutation.target)
        console.log("    added_nodes: ")
        if (removed === true) {
            console.warn("********REMOVED********")
        }
    }*/

    var observer = new MutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {
            /*if (removeIfUnwanted(mutation.target)) {
                console.warn("target removed", mutation.target)
                console.log("              ", mutation.target.localName + "#" + mutation.target.id)
            }*/

            mutation.addedNodes.forEach(function(node){
                if (removeIfUnwanted(node)) {
                    console.warn("node removed", node)
                }
            })
        })
    })

    var config = {
        attributes: false,
        childList: true,
        characterData: true,
        subtree: true
    }

    observer.observe(document, config)
})()<commit_msg>Add more ids to block<commit_after>;(function(){

    var unwanted_sources = [
        "assets.adobedtm.com",
        "demdex.net", // cpex.demdex.net, fast.cpex.demdex.net
        "gemius.pl",  // gacz.hut.gemius.pl, ls.hit.gemius.pl
        "adform.net",
        "ib.adnxs.com",
        "pixel.yabidos.com",
        "amazonaws.com",
        "bbnaut.ibillboard.com",
        "bbelements.com" // go.eu.bbelements.com
    ]

    var unwanted_ids = [
        "gemius",
        "bmone2t",
        "adform-adbox",
        "bannery300x300",
        "bannery160x600P",
        "bbswfcontainer",
        "cboxOverlay",
        "colorbox",
        "adfrom",
        "bmone2n",
        "bnx300x300",
        "bnx160x600P"
    ]

    var removeIfUnwanted = function (node) {
        if (node.id) {
            for (var i = 0; i < unwanted_ids.length; i++) {
                if (node.id.indexOf(unwanted_ids[i]) !== -1) {
                    node.remove()
                    return true
                }
            }
        }

        if (node.localName === "object" && node.data) {
            node.src = node.data
        }

        if (node.localName === "script" || node.localName === "iframe" || node.localName === "object") {
            for (var i = 0; i < unwanted_sources.length; i++) {
                var unwanted_source = unwanted_sources[i]
                if (node.src.indexOf(unwanted_source) !== -1) {
                    node.remove()
                    return true
                }
            }
        }

        return false
    }

    /*var logMutation = function (mutation, removed) {
        return
        console.log("mutation")
        console.log("    type:        ", mutation.type)
        console.log("    target:      ", mutation.target)
        console.log("    added_nodes: ")
        if (removed === true) {
            console.warn("********REMOVED********")
        }
    }*/

    var observer = new MutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {
            /*if (removeIfUnwanted(mutation.target)) {
                console.warn("target removed", mutation.target)
                console.log("              ", mutation.target.localName + "#" + mutation.target.id)
            }*/

            mutation.addedNodes.forEach(function(node){
                if (removeIfUnwanted(node)) {
                    console.warn("node removed", node)
                }
            })
        })
    })

    var config = {
        attributes: false,
        childList: true,
        characterData: true,
        subtree: true
    }

    observer.observe(document, config)
})()<|endoftext|>


<commit_before>//This function is the typer fucntion which prints a character one by one by taking a string and delay as input
var type = function (component, message, index, interval) {

    if (index < message.length) {
        $(component).append(message[index++]);
        setTimeout(function () {
            type(component, message, index, interval)
        }, interval);
    }
}

//This function when called proceeds to load the actual webpage after the loading animation is finished!
var load_page = function () {

    //This function is executed after the loading is done. It hides the LOAD_SCREEN and shows the FULL_PAGE
    setTimeout(function () {

        $(".LOAD_SCREEN").animate({
            opacity: 0.0
        }, 1000).css('display', 'none');

        $(".ENTIRE_PAGE, .menu")
            .css('display', 'block')
            .animate({
                opacity: 1.0
            }, 1000);
    }, 1000);

    //This function registers a permanant Async task that constantly keeps performing the typing animation that was earlier defined
    //in loading screen. Its redundant, but I was unable to give a unique function without global variables
    var rep = 0;
    setInterval(function () {
        $("#my_subtitle").text("> ");
        var text = "";
        switch (rep) {
            case 1:
                rep = 1;
                text = "Designer.";
                break;
            case 2:
                rep = 2;
                text = "Enthusiast.";
                break;
            default:
                rep = 0;
                text = "Coder.";
        }

        type("#my_subtitle", text, -1, 40);
        rep = (rep + 1) % 3;
    }, 2000);

    //End of Page Load Function
}

//This anonymous function registers an onMouseScroll Event Listener and overrides the default scroll
$(function () {

    var $window = $(window); //Window object

    var scrollTime = 1; //Scroll time
    var scrollDistance = $(window).height(); //Distance. Use smaller value for shorter scroll and greater value for longer scroll

    $window.on("mousewheel DOMMouseScroll", function (event) {

        event.preventDefault();

        var delta = event.originalEvent.wheelDelta / 120 || -event.originalEvent.detail / 3;
        var scrollTop = $window.scrollTop();
        var finalScroll = scrollTop - parseInt(delta * scrollDistance);

        TweenMax.to($window, scrollTime, {
            scrollTo: {
                y: finalScroll,
                autoKill: true
            },
            ease: Power1.easeOut, //For more easing functions see https://api.greensock.com/js/com/greensock/easing/package-detail.html
            autoKill: true,
            overwrite: 5
        });

    });

});

//This is the first functio nthat is ever called. It executes and animates the Load Screen, and implicitly calls load_page()
//So until the animation is complete the page isn't loaded
var loadscreen_animate = function () {
    var rep = 0;
    var exit = 0;

    var loadtyper = setInterval(function () {
        if (exit) {
            clearInterval(loadtyper);
            load_page();
            return;
        }
        $("#load_my_subtitle").text("> ");
        var text = "";
        switch (rep) {
            case 1:
                rep = 1;
                text = "Designer.";
                break;
            case 2:
                rep = 2;
                text = "Enthusiast.";
                exit = 1;
                break;
            default:
                rep = 0;
                text = "Coder.";
        }

        type("#load_my_subtitle", text, -1, 40);
        rep = (rep + 1) % 3;
    }, 2000);

}

loadscreen_animate();
//This function is called when the page finishes loading
$(document).ready(function () {

    //2.Smooth scroll
    $('a').click(function () {
        $('html, body').animate({
            scrollTop: $('[name="' + $.attr(this, 'href').substr(1) + '"]').offset().top
        }, 1000);
        return false;
    });

});
<commit_msg>Lazyload<commit_after>//This function is the typer function which prints a character one by one by taking a string and delay as input
var type = function (component, message, index, interval) {

    if (index < message.length) {
        $(component).append(message[index++]);
        setTimeout(function () {
            type(component, message, index, interval)
        }, interval);
    }
}

//This function when called proceeds to load the actual webpage after the loading animation is finished!
var load_page = function () {

    //This function is executed after the loading is done. It hides the LOAD_SCREEN and shows the FULL_PAGE
    setTimeout(function () {

        $(".LOAD_SCREEN").animate({
            opacity: 0.0
        }, 1000).css('display', 'none');

        $(".ENTIRE_PAGE, .menu")
            .css('display', 'block')
            .animate({
                opacity: 1.0
            }, 1000);
    }, 1000);

    //This function registers a permanant Async task that constantly keeps performing the typing animation that was earlier defined
    //in loading screen. Its redundant, but I was unable to give a unique function without global variables
    var rep = 0;
    setInterval(function () {
        $("#my_subtitle").text("> ");
        var text = "";
        switch (rep) {
            case 1:
                rep = 1;
                text = "Designer.";
                break;
            case 2:
                rep = 2;
                text = "Enthusiast.";
                break;
            default:
                rep = 0;
                text = "Coder.";
        }

        type("#my_subtitle", text, -1, 40);
        rep = (rep + 1) % 3;
    }, 2000);

    //End of Page Load Function
}

//This anonymous function registers an onMouseScroll Event Listener and overrides the default scroll
$(function () {

    var $window = $(window); //Window object

    var scrollTime = 1; //Scroll time
    var scrollDistance = $(window).height(); //Distance. Use smaller value for shorter scroll and greater value for longer scroll

    $window.on("mousewheel DOMMouseScroll", function (event) {

        event.preventDefault();

        var delta = event.originalEvent.wheelDelta / 120 || -event.originalEvent.detail / 3;
        var scrollTop = $window.scrollTop();
        var finalScroll = scrollTop - parseInt(delta * scrollDistance);

        TweenMax.to($window, scrollTime, {
            scrollTo: {
                y: finalScroll,
                autoKill: true
            },
            ease: Power1.easeOut, //For more easing functions see https://api.greensock.com/js/com/greensock/easing/package-detail.html
            autoKill: true,
            overwrite: 5
        });

    });

});

//This is the first function that is ever called. It executes and animates the Load Screen, and implicitly calls load_page()
//So until the animation is complete the page isn't loaded
var loadscreen_animate = function () {
    var rep = 1;
    var exit = 0;
    $("#load_my_subtitle").text("> Coder.");
    var loadtyper = setInterval(function () {

        var text = "";
        if (rep == 1) {
            rep = 1;
            text = " Designer. ";
            type("#load_my_subtitle", text, -1, 40);
            rep++;

        } else {
            text = "Enthusiast.";
            type("#load_my_subtitle", text, -1, 40);
            clearInterval(loadtyper);
            load_page();
            return;
        }

    }, 2000);

}

loadscreen_animate();
//This function is called when the page finishes loading

$(document).ready(function () {
    //1.Smooth scroll
    $('a').click(function () {
        $('html, body').animate({
            scrollTop: $('[name="' + $.attr(this, 'href').substr(1) + '"]').offset().top
        }, 1000);
        return false;
    });

});
<|endoftext|>


<commit_before>// eslint-disable filenames/match-exported
import createExpressServer from "./createExpressServer"
import createUniversalMiddleware from "./createUniversalMiddleware"
import addFallbackHandler from "./addFallbackHandler"

import Root from "../app/Root"
import State from "../app/State"
import Config from "../app/Config.yml"

export function start()
{
  var ssrData = {
    apolloUri: "http://localhost:9123",
    defaultLocale: Config.DEFAULT_LOCALE
  }

  return new Promise((resolve, reject) =>
  {
    const server = createExpressServer()

    // Bind our universal react app middleware as the handler for all get requests.
    server.get("*", createUniversalMiddleware({ Root, State, ssrData }))

    // Add default handling for any remaining errors which are not catched by our middleware
    addFallbackHandler(server)

    // Create an http listener for our express app.
    var listener = server.listen(process.env.SERVER_PORT)
    console.log(`Started React Server (Port: ${process.env.SERVER_PORT})`)
    resolve(listener)
  })
}

// Auto start server
start()
<commit_msg>Using stacktrace lib like in template<commit_after>// eslint-disable filenames/match-exported
import createExpressServer from "./createExpressServer"
import createUniversalMiddleware from "./createUniversalMiddleware"
import addFallbackHandler from "./addFallbackHandler"
import generateStacktrace from "./generateStacktrace"

import Root from "../app/Root"
import State from "../app/State"
import Config from "../app/Config.yml"

export function start()
{
  var ssrData = {
    apolloUri: "http://localhost:9123",
    defaultLocale: Config.DEFAULT_LOCALE
  }

  return new Promise((resolve, reject) =>
  {
    const server = createExpressServer()

    // Bind our universal react app middleware as the handler for all get requests.
    server.get("*", createUniversalMiddleware({ Root, State, ssrData }))

    // Add default handling for any remaining errors which are not catched by our middleware
    addFallbackHandler(server)

    // Create an http listener for our express app.
    var listener = server.listen(process.env.SERVER_PORT)
    console.log(`Started React Server (Port: ${process.env.SERVER_PORT})`)
    resolve(listener)
  })
    .catch(async (error) =>
    {
      const message = await generateStacktrace(error)
      console.error(message)
    })
}

// Auto start server
start()
<|endoftext|>


<commit_before>/* Viper's Pit v1.0 Scripts.
    By: Blade, cares, Ethan
    Credit to: Max, Lutra
*/

Config = {
    // Configuration for the script.
    servername: "Viper's Pit",

    maintainers: ['V.', 'Max', 'Comrade Mario'],
	masters: ['Blade', 'Jigglypuff'],

    // Repo to load plugins from.
    repourl: "https://raw.githubusercontent.com/VipersPit/Scripts/master/",
    // Repo to load data (announcement/description + tiers) from.
    dataurl: "https://raw.githubusercontent.com/VipersPit/Server-Shit/gh-pages/",
    emotesurl: 'http://viperspit.github.io/Emotes/emotes.json',

    // Plugin directory.
    plugindir: "plugins/",
    datadir: "data/",

    // Do not touch unless you are adding a new plugin.
    // Plugins to load on script load.
    plugins: ['bot', 'reg', 'ranks', 'utils', 'rtd', 'yeolde', 'channeldata', 'emotes', 'lists', 'init', 'feedmon', 'tours', 'commands', 'events'],
    data: ['emoji'],

    // Whether or not to load plugins from repourl. If set to false, they will load locally.
    load_from_web: true,
    // If HTML should be stripped from channel messages outputted onto the server window.
    stripHtmlFromChannelMessages: true,
    // If emotes are enabled.
    emotesEnabled: true,
    // If custom channels are enabled
    channelsEnabled: true,
    // Character limit in messages.
    characterLimit: 600
};

(function() {
    var dir = Config.plugindir,
        datadir = Config.datadir;
    sys.makeDir(dir);
    sys.makeDir(datadir);

    require = function require(name, webcall, noCache) {
        if ((name in require.cache) && !webcall && !noCache) {
            return require.cache[name];
        }

        var __fileContent,
            __fname = dir + name + ".js",
            module, __resp;

        if (webcall) {
            __resp = sys.synchronousWebCall(Config.repourl + "plugins/" + name + ".js");
            if (!__resp || __resp.substr(0, 9) === "<!DOCTYPE") {
                throw new Error("Failed to load plugin " + name + " from " + Config.repourl + "plugins/" + name + ".js");
            }
            sys.writeToFile(__fname, __resp);
        }

        if (!sys.fileExists(__fname)) {
            throw {name: "NoFileError", toString: function () { return "Couldn't find file " + (__fname) + "."; }};
        }

        __fileContent = sys.getFileContent(__fname);

        module = {
            exports: {},
            reload: function () { return false; },
            name: name
        };

        if (name in require.cache) {
            if (require.meta[name].onUnload) {
                require.meta[name].onUnload();
            }
        }

        try {
            sys.eval("(function (module, exports) { " + __fileContent + " }(module, module.exports));", __fname);
        } catch (e) {
            sys.sendAll("Error loading module " + name + ": " + e + " on line " + e.lineNumber);
            print(e.backtracetext);
            throw e;
        }

        print("Loaded module " + name);

        require.cache[name] = module.exports;
        require.meta[name] = module;
        return module.exports;
    };

    require.reload = function require_reload(name) {
        require(name, false, false);
        return require.meta[name].reload();
    };

    if (!require.cache || (typeof FULLRELOAD === 'boolean' && FULLRELOAD === true)) {
        require.cache = {};
        require.meta  = {};
    }

    FULLRELOAD = false;

    require.callPlugins = function require_callPlugins(event) {
        var args = Array.prototype.slice.call(arguments, 1),
            plugins = this.meta,
            exports, plugin;

        for (plugin in plugins) {
            exports = plugins[plugin].exports;
            if (event in exports) {
                try {
                    exports[event].apply(exports, args);
                } catch (e) {
                    print("Plugin error (" + plugins[plugin].name + ") on line " + e.lineNumber + ": " + e);
                    print(e.backtracetext);
                }
            }
        }
    };

    var plugin, data, resp, i;

    for (i = 0; i < Config.plugins.length; i += 1) {
        plugin = Config.plugins[i];
        require(plugin, Config.load_from_web);
    }

    for (i = 0; i < Config.data.length; i += 1) {
        data = Config.data[i] + ".json";

        if (!sys.fileExists(datadir + data)) {
            resp = sys.synchronousWebCall(Config.repourl + "data/" + data);
            sys.writeToFile(datadir + data, resp);
        }
    }
}());

function poUser(id) {
    var ip = sys.ip(id);

    this.id = id;
    this.ip = ip;
    this.floodCount = 0;
    this.teamChanges = 0;
    this.caps = 0;
    this.muted = false;
    this.semuted = false;

    this.originalName = sys.name(id);
    this.loginTime = sys.time();

    // This is an array so we can track multiple emotes in their last message.
    this.lastEmote = [];
    this.lastMessage = {message: "", time: 0};
}

function poChannel(chanId) {
    this.id   = chanId;
    this.name = sys.channel(chanId);

    this.creator = '';
    this.topic   = '';
    this.setBy   = '';

    this.members = {};
    this.auth    = {};
    this.mutes   = {};
    this.bans    = {};

    this.bots     = true;
    this.isPublic = true;
}

try {
    ChannelManager = require('channeldata').manager;
} catch (ex) {
    ChannelManager = {};
    sys.sendAll("Couldn't load ChannelManager: " + ex);
}

SESSION.identifyScriptAs("Viper's Pit Script v0.10.1");
SESSION.registerUserFactory(poUser);
SESSION.registerChannelFactory(poChannel);
SESSION.refill();

var poScript;
poScript = ({
    serverStartUp: function serverStartUp() {
        startUpTime = sys.time();
        script.init();
    },
    serverShutDown: function serverShutDown() {
        Reg.saveData();
        require.callPlugins("serverShutDown");
    },
    init: function init() {
        require.reload('utils');

        require.reload('reg');
        require.reload('ranks');
        require.reload('bot');

        require.reload('yeolde');
        require.reload('rtd');

        require.reload('feedmon');
        require.reload('tours');

        require.reload('init');

        require.reload('emotes');
        require.reload('lists');

        sys.resetProfiling();
    },
    step: function step() {
        require.callPlugins("step");
    },
    warning: function warning(func, message, backtrace) {
        require.callPlugins("warning", func, message, backtrace);
    },
    beforeNewMessage: function beforeNewMessage(message) {
        require.callPlugins("beforeNewMessage", message);
    },
    afterNewMessage: function afterNewMessage(message) {
        require.callPlugins("afterNewMessage", message);
    },
    beforeServerMessage: function (message) {
        require.callPlugins("beforeServerMessage", message);
    },
    beforeChannelJoin: function beforeChannelJoin(src, channel) {
        require.callPlugins("beforeChannelJoin", src, channel);
    },
    beforeChannelDestroyed: function beforeChannelDestroyed(channel) {
        require.callPlugins("beforeChannelDestroyed", channel);
    },
    afterChannelCreated: function afterChannelCreated(chan, name, src) {
        require.callPlugins("afterChannelCreated", chan, name, src);
    },
    afterChannelJoin: function afterChannelJoin(src, chan) {
        require.callPlugins("afterChannelJoin", src, chan);
    },
    beforeLogIn: function beforeLogIn(src) {
        require.callPlugins("beforeLogIn", src);
    },
    afterLogIn: function afterLogIn(src, defaultChan) {
        require.callPlugins("afterLogIn", src, defaultChan);
    },
    beforeChangeTier: function(src, team, oldtier, newtier) {
        require.callPlugins("beforeChangeTier", src, team, oldtier, newtier);
    },
    beforeChangeTeam: function beforeChangeTeam(src) {
        require.callPlugins("beforeChangeTeam", src);
    },
    beforeChatMessage: function beforeChatMessage(src, message, chan) {
        require.callPlugins("beforeChatMessage", src, message, chan);
    },
    beforeLogOut: function beforeLogOut(src) {
        require.callPlugins("beforeLogOut", src);
    },
    afterChangeTeam: function afterChangeTeam(src) {
        require.callPlugins("afterChangeTeam", src);
    },
    beforePlayerKick: function beforePlayerKick(src, bpl) {
        require.callPlugins("beforePlayerKick", src, bpl);
    },
    beforePlayerBan: function beforePlayerBan(src, bpl, time) {
        require.callPlugins("beforePlayerBan", src, bpl, time);
    },
    beforeChallengeIssued: function beforeChallengeIssued(src, dest) {
        require.callPlugins("beforeChallengeIssued", src, dest);
    },
    /*afterPlayerAway: function afterPlayerAway(src, mode) {
    },*/
    beforeBattleMatchup: function beforeBattleMatchup(src, dest, clauses, rated, mode, team1, team2) {
        require.callPlugins("beforeBattleMatchup", src, dest, clauses, rated, mode, team1, team2);
    },
    afterBattleStarted: function afterBattleStarted(src, dest, info, id, t1, t2) {
        require.callPlugins("afterBattleStarted", src, dest, info, id, t1, t2);
    },
    afterBattleEnded: function afterBattleEnded(src, dest, desc) {
        require.callPlugins("afterBattleEnded", src, dest, desc);
    },
    afterChatMessage: function afterChatMessage(src, message, chan) {
        require.callPlugins("afterChatMessage", src, message, chan);
    },
    beforePlayerRegister: function (src) {
        Utils.watch.notify(Utils.nameIp(src) + " registered.");
    },
    battleConnectionLost: function() {
        Utils.watch.notify("Connection to the battle server has been lost.");
    }
});
<commit_msg>ayy lmao<commit_after>/* Viper's Pit v1.0 Scripts.
    By: Blade, cares, Ethan
    Credit to: Max, Lutra
*/

Config = {
    // Configuration for the script.
    servername: "Viper's Pit",

    maintainers: ['V.', 'Comrade Mario'],
	masters: ['Blade', 'Jigglypuff', 'Max'],

    // Repo to load plugins from.
    repourl: "https://raw.githubusercontent.com/VipersPit/Scripts/master/",
    // Repo to load data (announcement/description + tiers) from.
    dataurl: "https://raw.githubusercontent.com/VipersPit/Server-Shit/gh-pages/",
    emotesurl: 'http://viperspit.github.io/Emotes/emotes.json',

    // Plugin directory.
    plugindir: "plugins/",
    datadir: "data/",

    // Do not touch unless you are adding a new plugin.
    // Plugins to load on script load.
    plugins: ['bot', 'reg', 'ranks', 'utils', 'rtd', 'yeolde', 'channeldata', 'emotes', 'lists', 'init', 'feedmon', 'tours', 'commands', 'events'],
    data: ['emoji'],

    // Whether or not to load plugins from repourl. If set to false, they will load locally.
    load_from_web: true,
    // If HTML should be stripped from channel messages outputted onto the server window.
    stripHtmlFromChannelMessages: true,
    // If emotes are enabled.
    emotesEnabled: true,
    // If custom channels are enabled
    channelsEnabled: true,
    // Character limit in messages.
    characterLimit: 600
};

(function() {
    var dir = Config.plugindir,
        datadir = Config.datadir;
    sys.makeDir(dir);
    sys.makeDir(datadir);

    require = function require(name, webcall, noCache) {
        if ((name in require.cache) && !webcall && !noCache) {
            return require.cache[name];
        }

        var __fileContent,
            __fname = dir + name + ".js",
            module, __resp;

        if (webcall) {
            __resp = sys.synchronousWebCall(Config.repourl + "plugins/" + name + ".js");
            if (!__resp || __resp.substr(0, 9) === "<!DOCTYPE") {
                throw new Error("Failed to load plugin " + name + " from " + Config.repourl + "plugins/" + name + ".js");
            }
            sys.writeToFile(__fname, __resp);
        }

        if (!sys.fileExists(__fname)) {
            throw {name: "NoFileError", toString: function () { return "Couldn't find file " + (__fname) + "."; }};
        }

        __fileContent = sys.getFileContent(__fname);

        module = {
            exports: {},
            reload: function () { return false; },
            name: name
        };

        if (name in require.cache) {
            if (require.meta[name].onUnload) {
                require.meta[name].onUnload();
            }
        }

        try {
            sys.eval("(function (module, exports) { " + __fileContent + " }(module, module.exports));", __fname);
        } catch (e) {
            sys.sendAll("Error loading module " + name + ": " + e + " on line " + e.lineNumber);
            print(e.backtracetext);
            throw e;
        }

        print("Loaded module " + name);

        require.cache[name] = module.exports;
        require.meta[name] = module;
        return module.exports;
    };

    require.reload = function require_reload(name) {
        require(name, false, false);
        return require.meta[name].reload();
    };

    if (!require.cache || (typeof FULLRELOAD === 'boolean' && FULLRELOAD === true)) {
        require.cache = {};
        require.meta  = {};
    }

    FULLRELOAD = false;

    require.callPlugins = function require_callPlugins(event) {
        var args = Array.prototype.slice.call(arguments, 1),
            plugins = this.meta,
            exports, plugin;

        for (plugin in plugins) {
            exports = plugins[plugin].exports;
            if (event in exports) {
                try {
                    exports[event].apply(exports, args);
                } catch (e) {
                    print("Plugin error (" + plugins[plugin].name + ") on line " + e.lineNumber + ": " + e);
                    print(e.backtracetext);
                }
            }
        }
    };

    var plugin, data, resp, i;

    for (i = 0; i < Config.plugins.length; i += 1) {
        plugin = Config.plugins[i];
        require(plugin, Config.load_from_web);
    }

    for (i = 0; i < Config.data.length; i += 1) {
        data = Config.data[i] + ".json";

        if (!sys.fileExists(datadir + data)) {
            resp = sys.synchronousWebCall(Config.repourl + "data/" + data);
            sys.writeToFile(datadir + data, resp);
        }
    }
}());

function poUser(id) {
    var ip = sys.ip(id);

    this.id = id;
    this.ip = ip;
    this.floodCount = 0;
    this.teamChanges = 0;
    this.caps = 0;
    this.muted = false;
    this.semuted = false;

    this.originalName = sys.name(id);
    this.loginTime = sys.time();

    // This is an array so we can track multiple emotes in their last message.
    this.lastEmote = [];
    this.lastMessage = {message: "", time: 0};
}

function poChannel(chanId) {
    this.id   = chanId;
    this.name = sys.channel(chanId);

    this.creator = '';
    this.topic   = '';
    this.setBy   = '';

    this.members = {};
    this.auth    = {};
    this.mutes   = {};
    this.bans    = {};

    this.bots     = true;
    this.isPublic = true;
}

try {
    ChannelManager = require('channeldata').manager;
} catch (ex) {
    ChannelManager = {};
    sys.sendAll("Couldn't load ChannelManager: " + ex);
}

SESSION.identifyScriptAs("Viper's Pit Script v0.10.1");
SESSION.registerUserFactory(poUser);
SESSION.registerChannelFactory(poChannel);
SESSION.refill();

var poScript;
poScript = ({
    serverStartUp: function serverStartUp() {
        startUpTime = sys.time();
        script.init();
    },
    serverShutDown: function serverShutDown() {
        Reg.saveData();
        require.callPlugins("serverShutDown");
    },
    init: function init() {
        require.reload('utils');

        require.reload('reg');
        require.reload('ranks');
        require.reload('bot');

        require.reload('yeolde');
        require.reload('rtd');

        require.reload('feedmon');
        require.reload('tours');

        require.reload('init');

        require.reload('emotes');
        require.reload('lists');

        sys.resetProfiling();
    },
    step: function step() {
        require.callPlugins("step");
    },
    warning: function warning(func, message, backtrace) {
        require.callPlugins("warning", func, message, backtrace);
    },
    beforeNewMessage: function beforeNewMessage(message) {
        require.callPlugins("beforeNewMessage", message);
    },
    afterNewMessage: function afterNewMessage(message) {
        require.callPlugins("afterNewMessage", message);
    },
    beforeServerMessage: function (message) {
        require.callPlugins("beforeServerMessage", message);
    },
    beforeChannelJoin: function beforeChannelJoin(src, channel) {
        require.callPlugins("beforeChannelJoin", src, channel);
    },
    beforeChannelDestroyed: function beforeChannelDestroyed(channel) {
        require.callPlugins("beforeChannelDestroyed", channel);
    },
    afterChannelCreated: function afterChannelCreated(chan, name, src) {
        require.callPlugins("afterChannelCreated", chan, name, src);
    },
    afterChannelJoin: function afterChannelJoin(src, chan) {
        require.callPlugins("afterChannelJoin", src, chan);
    },
    beforeLogIn: function beforeLogIn(src) {
        require.callPlugins("beforeLogIn", src);
    },
    afterLogIn: function afterLogIn(src, defaultChan) {
        require.callPlugins("afterLogIn", src, defaultChan);
    },
    beforeChangeTier: function(src, team, oldtier, newtier) {
        require.callPlugins("beforeChangeTier", src, team, oldtier, newtier);
    },
    beforeChangeTeam: function beforeChangeTeam(src) {
        require.callPlugins("beforeChangeTeam", src);
    },
    beforeChatMessage: function beforeChatMessage(src, message, chan) {
        require.callPlugins("beforeChatMessage", src, message, chan);
    },
    beforeLogOut: function beforeLogOut(src) {
        require.callPlugins("beforeLogOut", src);
    },
    afterChangeTeam: function afterChangeTeam(src) {
        require.callPlugins("afterChangeTeam", src);
    },
    beforePlayerKick: function beforePlayerKick(src, bpl) {
        require.callPlugins("beforePlayerKick", src, bpl);
    },
    beforePlayerBan: function beforePlayerBan(src, bpl, time) {
        require.callPlugins("beforePlayerBan", src, bpl, time);
    },
    beforeChallengeIssued: function beforeChallengeIssued(src, dest) {
        require.callPlugins("beforeChallengeIssued", src, dest);
    },
    /*afterPlayerAway: function afterPlayerAway(src, mode) {
    },*/
    beforeBattleMatchup: function beforeBattleMatchup(src, dest, clauses, rated, mode, team1, team2) {
        require.callPlugins("beforeBattleMatchup", src, dest, clauses, rated, mode, team1, team2);
    },
    afterBattleStarted: function afterBattleStarted(src, dest, info, id, t1, t2) {
        require.callPlugins("afterBattleStarted", src, dest, info, id, t1, t2);
    },
    afterBattleEnded: function afterBattleEnded(src, dest, desc) {
        require.callPlugins("afterBattleEnded", src, dest, desc);
    },
    afterChatMessage: function afterChatMessage(src, message, chan) {
        require.callPlugins("afterChatMessage", src, message, chan);
    },
    beforePlayerRegister: function (src) {
        Utils.watch.notify(Utils.nameIp(src) + " registered.");
    },
    battleConnectionLost: function() {
        Utils.watch.notify("Connection to the battle server has been lost.");
    }
});
<|endoftext|>


<commit_before>// This script removes demo app files
import rimraf from 'rimraf';
import fs from 'fs';
import {chalkSuccess} from './chalkConfig';

/* eslint-disable no-console */

const pathsToRemove = [
  './src/actions/*',
  './src/utils',
  './src/components/*',
  './src/constants/*',
  './src/containers/*',
  './src/images',
  './src/reducers/*',
  './src/store/store.spec.js',
  './src/styles',
  './src/index.js',
  './tools/removeDemo.js'
];

const filesToCreate = [
  {
    path: './src/components/emptyTest.spec.js',
    content: '// Must have at least one test file in this directory or Mocha will throw an error.'
  },
  {
    path: './src/index.js',
    content: '// Set up your application entry point here...'
  },
  {
    path: './src/reducers/index.js',
    content: '// Set up your root reducer here...\n import { combineReducers } from \'redux\';\n export default combineReducers;'
  }
];

function removePath(path, callback) {
  rimraf(path, error => {
    if (error) throw new Error(error);
    callback();
  });
}

function createFile(file) {
  fs.writeFile(file.path, file.content, error => {
    if (error) throw new Error(error);
  });
}

function removePackageJsonScriptEntry(scriptName) {
  const packageJsonPath = './package.json';
  let fileData = fs.readFileSync(packageJsonPath);
  let content = JSON.parse(fileData);
  delete content.scripts[scriptName];
  fs.writeFileSync(packageJsonPath,
    JSON.stringify(content, null, 2) + '\n');
}

let numPathsRemoved = 0;
pathsToRemove.map(path => {
  removePath(path, () => {
    numPathsRemoved++;
    if (numPathsRemoved === pathsToRemove.length) { // All paths have been processed
      // Now we can create files since we're done deleting.
      filesToCreate.map(file => createFile(file));
    }
  });
});

removePackageJsonScriptEntry('remove-demo');

console.log(chalkSuccess('Demo app removed.'));
<commit_msg>keeps style folder but deletes everything in it (#546)<commit_after>// This script removes demo app files
import rimraf from 'rimraf';
import fs from 'fs';
import {chalkSuccess} from './chalkConfig';

/* eslint-disable no-console */

const pathsToRemove = [
  './src/actions/*',
  './src/utils',
  './src/components/*',
  './src/constants/*',
  './src/containers/*',
  './src/images',
  './src/reducers/*',
  './src/store/store.spec.js',
  './src/styles/*',
  './src/index.js',
  './tools/removeDemo.js'
];

const filesToCreate = [
  {
    path: './src/components/emptyTest.spec.js',
    content: '// Must have at least one test file in this directory or Mocha will throw an error.'
  },
  {
    path: './src/index.js',
    content: '// Set up your application entry point here...'
  },
  {
    path: './src/reducers/index.js',
    content: '// Set up your root reducer here...\n import { combineReducers } from \'redux\';\n export default combineReducers;'
  }
];

function removePath(path, callback) {
  rimraf(path, error => {
    if (error) throw new Error(error);
    callback();
  });
}

function createFile(file) {
  fs.writeFile(file.path, file.content, error => {
    if (error) throw new Error(error);
  });
}

function removePackageJsonScriptEntry(scriptName) {
  const packageJsonPath = './package.json';
  let fileData = fs.readFileSync(packageJsonPath);
  let content = JSON.parse(fileData);
  delete content.scripts[scriptName];
  fs.writeFileSync(packageJsonPath,
    JSON.stringify(content, null, 2) + '\n');
}

let numPathsRemoved = 0;
pathsToRemove.map(path => {
  removePath(path, () => {
    numPathsRemoved++;
    if (numPathsRemoved === pathsToRemove.length) { // All paths have been processed
      // Now we can create files since we're done deleting.
      filesToCreate.map(file => createFile(file));
    }
  });
});

removePackageJsonScriptEntry('remove-demo');

console.log(chalkSuccess('Demo app removed.'));
<|endoftext|>


<commit_before>/*
 * grunt-vc-apprepo
 * https://github.com/rajatpandit/grunt-vc-apprepo
 *
 * Copyright (c) 2014 Rajat Pandit
 * Licensed under the MIT license.
 */

'use strict';
module.exports = function(grunt) {

  // Please see the Grunt documentation for more information regarding task
  // creation: http://gruntjs.com/creating-tasks

  grunt.registerTask('apprepo', 'Plugin to create landing page for ios and android apps and push it to a remote server', function(build_id, start_commit, end_commit, binary_name) {
    var options = this.options(),
        git     = '/usr/bin/git',
        done    = this.async(),
        exec    = require('child_process').exec,
        ejs     = require('ejs'),
        async   = require('async'),
        fs      = require('fs'),
        command = 'cd /home/rp/repo-generator/repo-generator/ && git log ' + start_commit + '..' + end_commit + ' --pretty="%H|%ae|%s"',

        parse_commits = function(commits) {
            var logs  = [];
            commits   = commits.split('\n');
            commits.pop();
            commits.forEach(function(commit) {
                commit = commit.split('|');
                var single_commit = {
                    'hash': commit[0],
                    'author': commit[1],
                    'msg': commit[2]
                };
                logs.push(single_commit);
            });
            return logs;
        };

    async.waterfall([function(callback) {
        exec(command, function(err, stdout, stderr) {
            if(err) {
                grunt.log.writeln(stderr);
                throw err;
            }
            callback(null, parse_commits(stdout));
        });
    }, function(logs, callback) {
            var template_path     = __dirname + '/../templates/',
                html_template     = template_path + 'index.html.ejs',
                manifest_template = template_path + 'manifest.plist.ejs';

            // get parse the output of the manifest
            var manifest_output = ejs.render(fs.readFileSync(manifest_template, 'utf-8'), {
                app_url   : options['http_url'] + build_id,
                bundle_id : options['bundle_id'],
                app_name  : options['app_name']
            });

            var html_output = ejs.render(fs.readFileSync(html_template, 'utf-8'), {
                build_id: build_id,
                logs: logs
            });

    }]);

    });
};
<commit_msg>added changelogs output and writing to log files<commit_after>/*
 * grunt-vc-apprepo
 * https://github.com/rajatpandit/grunt-vc-apprepo
 *
 * Copyright (c) 2014 Rajat Pandit
 * Licensed under the MIT license.
 */

'use strict';
module.exports = function(grunt) {

  // Please see the Grunt documentation for more information regarding task
  // creation: http://gruntjs.com/creating-tasks

  grunt.registerTask('apprepo', 'Plugin to create landing page for ios and android apps and push it to a remote server', function(build_id, start_commit, end_commit, binary_name) {
    var options = this.options(),
        git     = '/usr/bin/git',
        done    = this.async(),
        exec    = require('child_process').exec,
        ejs     = require('ejs'),
        async   = require('async'),
        fs      = require('fs'),
        command = 'cd /home/rp/repo-generator/repo-generator/ && git log ' + start_commit + '..' + end_commit + ' --pretty="%H|%ae|%s"',

        parse_commits = function(commits) {
            var logs  = [];
            commits   = commits.split('\n');
            commits.pop();
            commits.forEach(function(commit) {
                commit = commit.split('|');
                var single_commit = {
                    'hash': commit[0],
                    'author': commit[1],
                    'msg': commit[2]
                };
                logs.push(single_commit);
            });
            if (logs.length){
                grunt.log.writeln('Found the following change logs');
                grunt.log.writeln('---');
                logs.forEach(function(log) {
                    grunt.log.writeln("%s - %s (%s)", log.hash.substr(0,5), log.msg, log.author);
                });
                grunt.log.writeln('---');
            }
            return logs;
        };

    async.waterfall([function(callback) {
        exec(command, function(err, stdout, stderr) {
            if(err) {
                grunt.log.writeln(stderr);
                throw err;
            }
            callback(null, parse_commits(stdout));
        });
    }, function(logs, callback) {
            var template_path     = __dirname + '/../templates/',
                html_template     = template_path + 'index.html.ejs',
                html_file         = options['output_path'] + 'index.html',
                manifest_template = template_path + 'manifest.plist.ejs',
                manifest_file     = options['output_path'] + 'manifest.plist';

            // get parse the output of the manifest
            var manifest_output = ejs.render(fs.readFileSync(manifest_template, 'utf-8'), {
                app_url   : options['http_url'] + build_id,
                bundle_id : options['bundle_id'],
                app_name  : options['app_name']
            });

            var html_output = ejs.render(fs.readFileSync(html_template, 'utf-8'), {
                build_id: build_id,
                logs: logs
            });
            fs.writeFile(html_file, html_output, function(err) {
                if (err) {
                    grunt.log.writeln('Error writing to %s', html_file);
                } else {
                    grunt.log.writeln('Wrote updated landing page at %s', html_file);
                }
            });
            fs.writeFile(manifest_file, manifest_output, function(err) {
                if (err) {
                    grunt.log.writeln('Error writing to %s', manifest_file);
                } else {
                    grunt.log.writeln('Wrote updated manifest file at %s', manifest_file);
                }
            });
    }]);

    });
};
<|endoftext|>


<commit_before>/*
Copyright (c) 2013, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://yuilibrary.com/license/
*/

var exec = require('child_process').spawn,
    path = require('path');

module.exports = function(grunt) {

    var VERSION = grunt.option('release-version');

    grunt.registerTask('yogi-build', 'Building YUI', function() {
        var done = this.async(),
            line = 'Building all modules with yogi',
            yogi = path.join(process.cwd(), 'node_modules/yogi/bin/yogi.js'),
            args = [
                yogi,
                'build',
                '--istanbul'
            ], child;

        if (grunt.option('release')) {
            line += ' for release ' + VERSION;
        }
        grunt.log.ok(line);

        if (grunt.option('release')) {
            args.push('--replace-version');
            args.push(VERSION);
            args.push('--build-dir');
            args.push(path.join(process.cwd(), 'release/', VERSION, 'dist', 'build'));
        } else {
            if (grunt.option('cache-build')) {
                args.push('--cache');
            }
        }

        child = exec(process.execPath, args, {
            cwd: path.join(process.cwd(), 'src'),
            stdio: 'inherit',
            env: process.env
        });

        child.on('exit', function(code) {
            if (code) {
                grunt.log.fail('yogi build exited with code: ' + code);
            }
            done();
        });

    });

};

<commit_msg>Fatal error when yogi bails<commit_after>/*
Copyright (c) 2013, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://yuilibrary.com/license/
*/

var exec = require('child_process').spawn,
    path = require('path');

module.exports = function(grunt) {

    var VERSION = grunt.option('release-version');

    grunt.registerTask('yogi-build', 'Building YUI', function() {
        var done = this.async(),
            line = 'Building all modules with yogi',
            yogi = path.join(process.cwd(), 'node_modules/yogi/bin/yogi.js'),
            args = [
                yogi,
                'build',
                '--istanbul'
            ], child;

        if (grunt.option('release')) {
            line += ' for release ' + VERSION;
        }
        grunt.log.ok(line);

        if (grunt.option('release')) {
            args.push('--replace-version');
            args.push(VERSION);
            args.push('--build-dir');
            args.push(path.join(process.cwd(), 'release/', VERSION, 'dist', 'build'));
        } else {
            if (grunt.option('cache-build')) {
                args.push('--cache');
            }
        }

        child = exec(process.execPath, args, {
            cwd: path.join(process.cwd(), 'src'),
            stdio: 'inherit',
            env: process.env
        });

        child.on('exit', function(code) {
            if (code) {
                grunt.fail.fatal('yogi build exited with code: ' + code);
            }
            done();
        });

    });

};

<|endoftext|>


<commit_before>var includeElems = []
var include_nodes = []

var excludeElems = []
var exclude_nodes = []

var frameDict;
var frameIndex_to_collabel

function getFrameDict(contents){
    // Get mapping from column label to index
    var content_dict = JSON.parse(contents)
    if("frameDict" in content_dict){
        return content_dict["frameDict"];
    }
    return;
}

function getFingerprintColumns(contents){
    // Get fingerprint column labels
    var column_labels = []
    var frameDict = JSON.parse(contents)["frameDict"]
    for (key in frameDict){
        column_labels.push(frameDict[key]);
    }
    return column_labels;
}

function updateIntersectFrames(){
    // Update the UI when user clicks table cell
    frameIndex_to_collabel = {}
    for (frameIndex in frameDict){
        var collabel = frameDict[frameIndex]
        frameIndex_to_collabel[collabel] = frameIndex
    }

    var include_sel = [];
    for (var i = 0; i < include_nodes.length; i++){
        include_sel.push(frameIndex_to_collabel[include_nodes[i]]);
    }

    var exclude_sel = [];
    for (var i = 0; i < exclude_nodes.length; i++){
        exclude_sel.push(frameIndex_to_collabel[exclude_nodes[i]]);
    }

    if(exclude_sel.length == 0){
        flareplot.framesIntersect(include_sel);
    }else{
        flareplot.framesIntersectSubtract(include_sel, exclude_sel)
    }

}

function twoStateSelection(el, row, col){
    // Allows users to toggle between include or ignore
    include_nodes = [];

    var index = includeElems.indexOf(el)
    if(index >= 0){
        el[0][0].className = "ignore";
        includeElems.splice(index, 1);
    }
    else{
        includeElems.push(el)
    }
    if(includeElems.length != 0){
        for (var i = 0; i < includeElems.length; i++){
            includeElems[i][0][0].className = "include";
            include_nodes.push(includeElems[i].col_header);
        }
    }
    console.log(include_nodes)
}

function threeStateSelection(el, row, col){
    // Allows user to toggle between include, exclude, and ignore nodes
    include_nodes = [];
    exclude_nodes = [];

    var includeIndex = includeElems.indexOf(el);
    var excludeIndex = excludeElems.indexOf(el);

    if(!(includeIndex >= 0) && !(excludeIndex >= 0)){
        el.html("&#10003")
        includeElems.push(el);
    }
    else if((includeIndex >= 0) && !(excludeIndex >= 0)){
        includeElems.splice(includeIndex, 1);
        el.html("X")
        excludeElems.push(el);
    }
    else if(excludeIndex >= 0){
        excludeElems.splice(excludeIndex, 1);
        el.html("")
        el[0][0].className = "ignore";
    }

    for (var i = 0; i < includeElems.length; i++){
        includeElems[i][0][0].className = "include";

        include_nodes.push(includeElems[i].col_header);
    }
    for (var j = 0; j < excludeElems.length; j++){
        excludeElems[j][0][0].className = "exclude";
        exclude_nodes.push(excludeElems[j].col_header);
    }

    console.log("Include Nodes: ", include_nodes, "Exclude Nodes: ", exclude_nodes)
}

function initFingerprintPanel(containerId, columnNames, callback, show_header, col_label_height){
    // Creates the grid and attaches printClick callback to each cell
    var numRows = 1;
    var numCols = columnNames.length;

    var outerPanel = d3.select(containerId).append('div')
        .attr("class", "fpPanelOuter")
        .attr("id", "fingerprintOuter")

    var panel = d3.select("#fingerprintOuter").append('table')
        .attr('class', 'fpPanel')
        .attr('id', 'fingerprint')

    // Column Headers
    var column_header_panel = panel.append("thead").append('tr');
    var col_headers = []
    for (var c = 0; c < numCols; ++c){
        var col_header = column_header_panel.append('th').style('height', col_label_height).append("span");
        if(show_header){
            col_header.html(columnNames[c]);
            col_headers.push(col_header);
        }else{
            col_header.html("");
            col_headers.push(col_header)
        }

    }

    // Fingerprint cells
    for (var r = 0; r < numRows; ++r){
        var tr = panel.append("tbody").append('tr');
        for (var c = 0; c < numCols; ++c){
            var cell = tr.append('td');
            cell.html("")
            cell.col_header = columnNames[c]; // Attribute to keep track of column header
            cell.on('click', function(el, r, c){
                return function(){
                    callback(el, r, c);
                }
            }(cell, r, c), false);
        }
    }

    return panel
}

function calcFingerprints(contents){
    function Comparator(a, b) {
        if (a[1] > b[1]) return -1;
        if (a[1] < b[1]) return 1;
        return 0;
    }

    var fingerprint_dict = {}
    var content_dict = JSON.parse(contents);
    var edges = content_dict["edges"];
    for (var i = 0; i < edges.length; i++){
        var e = edges[i];
        var frames = e["frames"];
        if(frames.length == 0){
            continue
        }
        var name1 = e["name1"];
        var name2 = e["name2"];
        if(!(frames in fingerprint_dict)){
            fingerprint_dict[frames] = 1;
        }else{
            fingerprint_dict[frames] += 1;
        }
    }

    fingerprint_list = [];
    for (key in fingerprint_dict){
        fingerprint_list.push([key, fingerprint_dict[key]]);
    }

    // Sort by frequency
    fingerprint_list = fingerprint_list.sort(Comparator);
    p = fingerprint_list;
    return fingerprint_list;
}

function threeStateRowSelection(tr, r, columnNames){
    include_nodes = []
    exclude_nodes = []
    var row_cells = tr[0][0].cells;

    for (var i = 0; i < row_cells.length; i++){
        var state = row_cells[i].className;
        if(state == "include"){
            include_nodes.push(columnNames[i])
        }else if(state == "exclude"){
            exclude_nodes.push(columnNames[i])
        }
    }
}

function initScrollableFingerprintPanel(containerId, columnNames, fingerpint_list, callback, show_header, col_label_height){
    // Creates the grid and attaches printClick callback to each cell
    var numRows = fingerprint_list.length;
    var numCols = columnNames.length;

    var outerPanel = d3.select(containerId).append('div')
        .attr("class", "fpPanelOuter")
        .attr("id", "fingerprintOuter")

    var panel = d3.select("#fingerprintOuter").append('table')
        .attr('class', 'fpScrolldown')
        .attr('id', 'scrolldown')

    // Column Headers
    var column_header_panel = panel.append("thead").append('tr');
    var col_headers = []
    for (var c = 0; c < numCols; c++){
        var col_header = column_header_panel.append('th').style('height', col_label_height).append("span")
        if(show_header){
            col_header.html(columnNames[c]);
            col_headers.push(col_header)
        }else{
            col_header.html("");
            col_headers.push(col_header)
        }
    }

    // Fingerprint cells
    var scroll_panel_body = panel.append("tbody")
    for (var r = 0; r < numRows; r++){
        var fpattern = fingerprint_list[r][0].split(",").map(Number);
        var count = fingerprint_list[r][1];

        var tr = scroll_panel_body.append('tr');
        for (var c = 0; c < numCols; c++){

            var cell = tr.append('td')
            cell.col_header = columnNames[c]; // Attribute to keep track of column header
            if(fpattern.includes(c)){
                cell[0][0].className = 'include';
            }else{
                cell[0][0].className = 'exclude';
            }
        }
        tr.on('click', function(tr, r, columnNames){
            return function(){
                callback(tr, r, columnNames);
            }
        }(tr, r, columnNames), false);

    }

    return panel
}
<commit_msg>Replaced typed X with 'ballot x'<commit_after>var includeElems = []
var include_nodes = []

var excludeElems = []
var exclude_nodes = []

var frameDict;
var frameIndex_to_collabel

function getFrameDict(contents){
    // Get mapping from column label to index
    var content_dict = JSON.parse(contents)
    if("frameDict" in content_dict){
        return content_dict["frameDict"];
    }
    return;
}

function getFingerprintColumns(contents){
    // Get fingerprint column labels
    var column_labels = []
    var frameDict = JSON.parse(contents)["frameDict"]
    for (key in frameDict){
        column_labels.push(frameDict[key]);
    }
    return column_labels;
}

function updateIntersectFrames(){
    // Update the UI when user clicks table cell
    frameIndex_to_collabel = {}
    for (frameIndex in frameDict){
        var collabel = frameDict[frameIndex]
        frameIndex_to_collabel[collabel] = frameIndex
    }

    var include_sel = [];
    for (var i = 0; i < include_nodes.length; i++){
        include_sel.push(frameIndex_to_collabel[include_nodes[i]]);
    }

    var exclude_sel = [];
    for (var i = 0; i < exclude_nodes.length; i++){
        exclude_sel.push(frameIndex_to_collabel[exclude_nodes[i]]);
    }

    if(exclude_sel.length == 0){
        flareplot.framesIntersect(include_sel);
    }else{
        flareplot.framesIntersectSubtract(include_sel, exclude_sel)
    }

}

function twoStateSelection(el, row, col){
    // Allows users to toggle between include or ignore
    include_nodes = [];

    var index = includeElems.indexOf(el)
    if(index >= 0){
        el[0][0].className = "ignore";
        includeElems.splice(index, 1);
    }
    else{
        includeElems.push(el)
    }
    if(includeElems.length != 0){
        for (var i = 0; i < includeElems.length; i++){
            includeElems[i][0][0].className = "include";
            include_nodes.push(includeElems[i].col_header);
        }
    }
    console.log(include_nodes)
}

function threeStateSelection(el, row, col){
    // Allows user to toggle between include, exclude, and ignore nodes
    include_nodes = [];
    exclude_nodes = [];

    var includeIndex = includeElems.indexOf(el);
    var excludeIndex = excludeElems.indexOf(el);

    if(!(includeIndex >= 0) && !(excludeIndex >= 0)){
        el.html("&#10003")
        includeElems.push(el);
    }
    else if((includeIndex >= 0) && !(excludeIndex >= 0)){
        includeElems.splice(includeIndex, 1);
        el.html("&#10007")
        excludeElems.push(el);
    }
    else if(excludeIndex >= 0){
        excludeElems.splice(excludeIndex, 1);
        el.html("")
        el[0][0].className = "ignore";
    }

    for (var i = 0; i < includeElems.length; i++){
        includeElems[i][0][0].className = "include";

        include_nodes.push(includeElems[i].col_header);
    }
    for (var j = 0; j < excludeElems.length; j++){
        excludeElems[j][0][0].className = "exclude";
        exclude_nodes.push(excludeElems[j].col_header);
    }

    console.log("Include Nodes: ", include_nodes, "Exclude Nodes: ", exclude_nodes)
}

function initFingerprintPanel(containerId, columnNames, callback, show_header, col_label_height){
    // Creates the grid and attaches printClick callback to each cell
    var numRows = 1;
    var numCols = columnNames.length;

    var outerPanel = d3.select(containerId).append('div')
        .attr("class", "fpPanelOuter")
        .attr("id", "fingerprintOuter")

    var panel = d3.select("#fingerprintOuter").append('table')
        .attr('class', 'fpPanel')
        .attr('id', 'fingerprint')

    // Column Headers
    var column_header_panel = panel.append("thead").append('tr');
    var col_headers = []
    for (var c = 0; c < numCols; ++c){
        var col_header = column_header_panel.append('th').style('height', col_label_height).append("span");
        if(show_header){
            col_header.html(columnNames[c]);
            col_headers.push(col_header);
        }else{
            col_header.html("");
            col_headers.push(col_header)
        }

    }

    // Fingerprint cells
    for (var r = 0; r < numRows; ++r){
        var tr = panel.append("tbody").append('tr');
        for (var c = 0; c < numCols; ++c){
            var cell = tr.append('td');
            cell.html("")
            cell.col_header = columnNames[c]; // Attribute to keep track of column header
            cell.on('click', function(el, r, c){
                return function(){
                    callback(el, r, c);
                }
            }(cell, r, c), false);
        }
    }

    return panel
}

function calcFingerprints(contents){
    function Comparator(a, b) {
        if (a[1] > b[1]) return -1;
        if (a[1] < b[1]) return 1;
        return 0;
    }

    var fingerprint_dict = {}
    var content_dict = JSON.parse(contents);
    var edges = content_dict["edges"];
    for (var i = 0; i < edges.length; i++){
        var e = edges[i];
        var frames = e["frames"];
        if(frames.length == 0){
            continue
        }
        var name1 = e["name1"];
        var name2 = e["name2"];
        if(!(frames in fingerprint_dict)){
            fingerprint_dict[frames] = 1;
        }else{
            fingerprint_dict[frames] += 1;
        }
    }

    fingerprint_list = [];
    for (key in fingerprint_dict){
        fingerprint_list.push([key, fingerprint_dict[key]]);
    }

    // Sort by frequency
    fingerprint_list = fingerprint_list.sort(Comparator);
    p = fingerprint_list;
    return fingerprint_list;
}

function threeStateRowSelection(tr, r, columnNames){
    include_nodes = []
    exclude_nodes = []
    var row_cells = tr[0][0].cells;

    for (var i = 0; i < row_cells.length; i++){
        var state = row_cells[i].className;
        if(state == "include"){
            include_nodes.push(columnNames[i])
        }else if(state == "exclude"){
            exclude_nodes.push(columnNames[i])
        }
    }
}

function initScrollableFingerprintPanel(containerId, columnNames, fingerpint_list, callback, show_header, col_label_height){
    // Creates the grid and attaches printClick callback to each cell
    var numRows = fingerprint_list.length;
    var numCols = columnNames.length;

    var outerPanel = d3.select(containerId).append('div')
        .attr("class", "fpPanelOuter")
        .attr("id", "fingerprintOuter")

    var panel = d3.select("#fingerprintOuter").append('table')
        .attr('class', 'fpScrolldown')
        .attr('id', 'scrolldown')

    // Column Headers
    var column_header_panel = panel.append("thead").append('tr');
    var col_headers = []
    for (var c = 0; c < numCols; c++){
        var col_header = column_header_panel.append('th').style('height', col_label_height).append("span")
        if(show_header){
            col_header.html(columnNames[c]);
            col_headers.push(col_header)
        }else{
            col_header.html("");
            col_headers.push(col_header)
        }
    }

    // Fingerprint cells
    var scroll_panel_body = panel.append("tbody")
    for (var r = 0; r < numRows; r++){
        var fpattern = fingerprint_list[r][0].split(",").map(Number);
        var count = fingerprint_list[r][1];

        var tr = scroll_panel_body.append('tr');
        for (var c = 0; c < numCols; c++){

            var cell = tr.append('td')
            cell.col_header = columnNames[c]; // Attribute to keep track of column header
            if(fpattern.includes(c)){
                cell[0][0].className = 'include';
            }else{
                cell[0][0].className = 'exclude';
            }
        }
        tr.on('click', function(tr, r, columnNames){
            return function(){
                callback(tr, r, columnNames);
            }
        }(tr, r, columnNames), false);

    }

    return panel
}
<|endoftext|>


<commit_before>z =[];

function test_suite(){if (GBrowserIsCompatible()) {
   tmap = new GMap2(document.getElementById("test_map"));
   GEvent.addListener(tmap, 'click', mapclick);
   tmap.setCenter(new GLatLng(49.833333, 73.166667), 10);

}}

function mapclick(overlay,  latlng,  overlaylatlng){
   if((z.length==2) || (z.length==0)){
   		tmap.clearOverlays();
   		z = [latlng];

   }
   else if(z.length==1){
		z.push(latlng);
		a = new ApproxPolyline(tmap, z,
	                           longsin, [-2*Math.PI, 2*Math.PI], 60);
	    console.log(a);
		b = a.get_map_lls();
		c = new GPolyline(b);
		start = new GMarker(b[0]);
		tmap.addOverlay(c);
   }
}

function longsin(x){
	if (x<-Math.PI || x>Math.PI) return 0;
	else return Math.sin(x);
}<commit_msg>removing console iteraction from tests<commit_after>z =[];

function test_suite(){if (GBrowserIsCompatible()) {
   tmap = new GMap2(document.getElementById("test_map"));
   GEvent.addListener(tmap, 'click', mapclick);
   tmap.setCenter(new GLatLng(49.833333, 73.166667), 10);

}}

function mapclick(overlay,  latlng,  overlaylatlng){
   if((z.length==2) || (z.length==0)){
   		tmap.clearOverlays();
   		z = [latlng];

   }
   else if(z.length==1){
		z.push(latlng);
		a = new ApproxPolyline(tmap, z,
	                           longsin, [-2*Math.PI, 2*Math.PI], 60);
		b = a.get_map_lls();
		c = new GPolyline(b);
		start = new GMarker(b[0]);
		tmap.addOverlay(c);
   }
}

function longsin(x){
	if (x<-Math.PI || x>Math.PI) return 0;
	else return Math.sin(x);
}<|endoftext|>